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

准备工作

  • 在安装和使用阿里云SDK前,确保您已经注册阿里云账号并生成访问密钥(AccessKey)。详情请参见创建AccessKey
  • 单击PHP SDK安装图像搜索PHP SDK,PHP版本要求大于等于5.3。

创建Client

创建Client代码示例如下。
chdir(dirname(__FILE__));
require_once "../../../aliyun-php-sdk-core/Config.php";
$product = "ImageSearch";
$region = "<Region>"; // 实例的地域信息,如: cn-shanghai(华东2), ap-southeast-1(亚太东南1) 
$accessKeyId = "<AccessKeyID>"; // 获取地址: https://ak-console.aliyun.com
$accessKeySecret = "<AccessKeySecret>";
$instanceName = "<InstanceName>"; // 购买的图像搜索实例名称,如: imagesearchtest
$domain = "imagesearch.".$region.".aliyuncs.com"; 
$profile = DefaultProfile::getProfile($region, $accessKeyId, $accessKeySecret);
DefaultProfile::addEndPoint($region, $region, $product, $domain);
$client = new DefaultAcsClient($profile);

新增图片

新增图片时,商品图片搜索实例您可以选择指定或者不指定类目ID,通用图片搜索实例请不要指定类目ID。
use ImageSearch\Request\V20180120\AddItemRequest;
$req = new AddItemRequest();
$req->setinstanceName($instanceName);
// 读取文件内容
$sampleFileName = "./1.jpg";
$content = file_get_contents($sampleFileName);
$req->setCateId("0");
$req->setItemId("1234");
$req->setCustContent("{\"key\":\"value\"}");
$req->addPicture("cloth1", $content);
if (!$req->buildPostContent()) {
    return ;
}
try {
    $response = $client->getAcsResponse($req);
    print_r($response);
} catch(ServerException $e) {
    print "Error: " . $e->getErrorCode() . " Message: " . $e->getMessage() . "\n";
} catch(ClientException $e) {
    print "Error: " . $e->getErrorCode() . " Message: " . $e->getMessage() . "\n";
}

查询图片

对于商品图像搜索,您可以选择指定或者不指定类目ID,如果指定则会从您指定的类目ID中进行搜索,如果没有指定则会从系统预测出的类目ID中进行搜索。对于通用图片搜索,您不需要指定类目ID。
use ImageSearch\Request\V20180120\SearchItemRequest;
$req = new SearchItemRequest();
$req->setinstanceName($instanceName);
$req->setNum(10);
$req->setStart(0);
// Read Image File
$sampleFileName = "./1.jpg";
$content = file_get_contents($sampleFileName);
fclose($handle);
$req->setSearchPicture($content);
if (!$req->buildPostContent()) {
    return ;
}
try {
    $response = $client->getAcsResponse($req);
    print_r($response);
} catch(ServerException $e) {
    print "Error: " . $e->getErrorCode() . " Message: " . $e->getMessage() . "\n";
} catch(ClientException $e) {
    print "Error: " . $e->getErrorCode() . " Message: " . $e->getMessage() . "\n";
}

删除图片

删除图片代码示例如下。
use ImageSearch\Request\V20180120\DeleteItemRequest;
$req = new DeleteItemRequest();
$req->setinstanceName($instanceName);
$req->setItemId("1234");
$req->addPicture("cloth1");
if (!$req->buildPostContent()) {
    return ;
}
try {
    $response = $client->getAcsResponse($req);
    print_r($response);
} catch(ServerException $e) {
    print "Error: " . $e->getErrorCode() . " Message: " . $e->getMessage() . "\n";
} catch(ClientException $e) {
    print "Error: " . $e->getErrorCode() . " Message: " . $e->getMessage() . "\n";
}