全部产品
云市场

PHP SDK

更新时间:2019-07-05 17:07:09

准备工作

  1. 在安装和使用阿里云SDK前,确保您已经注册阿里云账号并生成访问访问密钥(AccessKey)。详情参考创建AccessKey
  2. 下载图像搜索PHP SDK。点击下载

完整代码示例

  1. <?php
  2. //用户根据自己下载包的情况进行引用
  3. require_once "./aliyun-php-sdk-core/Config.php";
  4. use ImageSearch\Request\V20190325\AddImageRequest;
  5. use ImageSearch\Request\V20190325\SearchImageRequest;
  6. use ImageSearch\Request\V20190325\DeleteImageRequest;
  7. DefaultProfile::addEndPoint("<region>", "<region>", "ImageSearch", "imagesearch.<region>.aliyuncs.com");
  8. $profile = DefaultProfile::getProfile("<region>", "<your-access-key-id>", "<your-access-key-secret>");
  9. $client = new DefaultAcsClient($profile);
  10. // 添加图片
  11. $addRequest = new AddImageRequest();
  12. $addRequest->setInstanceName("demo");
  13. $addRequest->setProductId("test");
  14. $addRequest->setPicName("test");
  15. $content = file_get_contents("/home/admin/demo.jpg");
  16. $encodePicContent = base64_encode($content);
  17. $addRequest->setPicContent($encodePicContent);
  18. // 选填,是否需要进行主体识别,默认为true。
  19. // 1.为true时,由系统进行主体识别,以识别的主体进行搜索,主体识别结果可在Response中获取。
  20. // 2. 为false时,则不进行主体识别,以整张图进行搜索。
  21. //$addRequest->setCrop("false");
  22. //$addRequest->setCrop("true");
  23. // 选填,图片的主体区域,格式为 x1,x2,y1,y2, 其中 x1,y1 是左上角的点,x2,y2是右下角的点。
  24. // 若用户设置了Region,则不论Crop参数为何值,都将以用户输入Region进行搜索。
  25. // $addRequest->setRegion("100,300,100,300");
  26. try {
  27. $addResponse = $client->getAcsResponse($addRequest);
  28. print_r($addResponse);
  29. } catch(ServerException $e) {
  30. print "Error: " . $e->getErrorCode() . " Message: " . $e->getMessage() . "\n";
  31. } catch(ClientException $e) {
  32. print "Error: " . $e->getErrorCode() . " Message: " . $e->getMessage() . "\n";
  33. }
  34. // 查询图片
  35. $searchRequest = new SearchImageRequest();
  36. $searchRequest->setInstanceName("demo");
  37. $searchRequest->setType("SearchByName");
  38. $searchRequest->setProductId("test");
  39. $searchRequest->setPicName("test");
  40. try {
  41. $searchResponse = $client->getAcsResponse($searchRequest);
  42. print_r($searchResponse);
  43. } catch(ServerException $e) {
  44. print "Error: " . $e->getErrorCode() . " Message: " . $e->getMessage() . "\n";
  45. } catch(ClientException $e) {
  46. print "Error: " . $e->getErrorCode() . " Message: " . $e->getMessage() . "\n";
  47. }
  48. // 删除图片
  49. $deleteRequest = new DeleteImageRequest();
  50. $deleteRequest->setInstanceName("demo");
  51. $deleteRequest->setProductId("test");
  52. try {
  53. $deleteResponse = $client->getAcsResponse($deleteRequest);
  54. print_r($deleteResponse);
  55. } catch(ServerException $e) {
  56. print "Error: " . $e->getErrorCode() . " Message: " . $e->getMessage() . "\n";
  57. } catch(ClientException $e) {
  58. print "Error: " . $e->getErrorCode() . " Message: " . $e->getMessage() . "\n";
  59. }