本文介绍图像搜索服务PHP SDK的使用方法及示例。

准备工作

  • 在安装和使用阿里云SDK前,确保您已经注册阿里云账号并生成访问密钥(AccessKey)。具体请参见创建AccessKey
  • 下载图像搜索PHP SDK

代码示例

完整代码示例如下。
<?php
    //用户根据自己下载包的情况进行引用
    require_once "./aliyun-php-sdk-core/Config.php";
    use ImageSearch\Request\V20190325\AddImageRequest;
    use ImageSearch\Request\V20190325\SearchImageRequest;
    use ImageSearch\Request\V20190325\DeleteImageRequest;
    DefaultProfile::addEndPoint("<region>", "<region>", "ImageSearch", "imagesearch.<region>.aliyuncs.com");
    $profile = DefaultProfile::getProfile("<region>", "<your-access-key-id>", "<your-access-key-secret>");
    $client = new DefaultAcsClient($profile);
    // 添加图片
    $addRequest = new AddImageRequest();
    $addRequest->setInstanceName("demo");
    $addRequest->setProductId("test");
    $addRequest->setPicName("test");
    $content = file_get_contents("/home/admin/demo.jpg");
    $encodePicContent = base64_encode($content);
    $addRequest->setPicContent($encodePicContent);
    // 选填,是否需要进行主体识别,默认为true。
    // 1.为true时,由系统进行主体识别,以识别的主体进行搜索,主体识别结果可在Response中获取。
    // 2. 为false时,则不进行主体识别,以整张图进行搜索。
    //$addRequest->setCrop("false");
    //$addRequest->setCrop("true");
    // 选填,图片的主体区域,格式为 x1,x2,y1,y2, 其中 x1,y1 是左上角的点,x2,y2是右下角的点。
    // 若用户设置了Region,则不论Crop参数为何值,都将以用户输入Region进行搜索。
    // $addRequest->setRegion("100,300,100,300"); 
    try {
        $addResponse = $client->getAcsResponse($addRequest);
        print_r($addResponse);
    } catch(ServerException $e) {
        print "Error: " . $e->getErrorCode() . " Message: " . $e->getMessage() . "\n";
    } catch(ClientException $e) {
        print "Error: " . $e->getErrorCode() . " Message: " . $e->getMessage() . "\n";
    }
    // 查询图片
    $searchRequest = new SearchImageRequest();
    $searchRequest->setInstanceName("demo");
    $searchRequest->setType("SearchByName");
    $searchRequest->setProductId("test");
    $searchRequest->setPicName("test");
    try {
        $searchResponse = $client->getAcsResponse($searchRequest);
        print_r($searchResponse);
    } catch(ServerException $e) {
        print "Error: " . $e->getErrorCode() . " Message: " . $e->getMessage() . "\n";
    } catch(ClientException $e) {
        print "Error: " . $e->getErrorCode() . " Message: " . $e->getMessage() . "\n";
    }
    // 删除图片
    $deleteRequest = new DeleteImageRequest();
    $deleteRequest->setInstanceName("demo");
    $deleteRequest->setProductId("test");
    try {
        $deleteResponse = $client->getAcsResponse($deleteRequest);
        print_r($deleteResponse);
    } catch(ServerException $e) {
        print "Error: " . $e->getErrorCode() . " Message: " . $e->getMessage() . "\n";
    } catch(ClientException $e) {
        print "Error: " . $e->getErrorCode() . " Message: " . $e->getMessage() . "\n";
    }