php - 谷歌云视觉在检测到物体后保存图像
问题描述
在使用谷歌云视觉检测对象后,我试图将图像保存在我的数据库中。我正在使用 php,框架 laravel,这是我的代码,
function detect_object($imagen){
$path = $imagen->getRealPath();
$imageAnnotator = new ImageAnnotatorClient(['credentials' => base_path('credentials.json')]);
$output = imagecreatefromjpeg($path);
list($width, $height, $type, $attr) = getimagesize($path);
# annotate the image
$image = file_get_contents($path);
$response = $imageAnnotator->objectLocalization($image);
$objects = $response->getLocalizedObjectAnnotations();
foreach ($objects as $object) {
$name = $object->getName();
$score = $object->getScore();
$vertices = $object->getBoundingPoly()->getNormalizedVertices();
// printf('%s (confidence %f)):' . PHP_EOL, $name, $score);
// print('normalized bounding polygon vertices: ');
// foreach ($vertices as $vertex) {
// printf(' (%f, %f)', $vertex->getX(), $vertex->getY());
// }
// print(PHP_EOL);
$vertices_finales = [];
foreach ($vertices as $vertex) {
array_push($vertices_finales, ($vertex->getX() * $width));
array_push($vertices_finales, ($vertex->getY() * $height));
}
imagepolygon($output, $vertices_finales, (sizeof($vertices_finales) / 2), 0x00ff00);
imagestring($output, 5, ($vertices_finales[0] + 10), ($vertices_finales[1] + 10), $name, 0x00ff00);
}
header('Content-Type: image/jpeg');
imagejpeg($output);
imagedestroy($output);
$imageAnnotator->close();
}
你可以帮帮我吗?谢谢
解决方案
我将假设您想获取imagejpeg()
处理后生成的原始二进制文件?
我知道如何做到这一点的唯一方法是使用输出缓冲区。
代替:
<?php
header('Content-Type: image/jpeg');
imagejpeg($output);
imagedestroy($output);
$imageAnnotator->close();
做:
<?php
ob_start();
imagejpeg($output);
$imgData = ob_get_clean();
# Do what you want with imgData, like insert into a binary field in a db, write to disk, etc
imagedestroy($output);
$imageAnnotator->close();
如果您还想将图像输出到浏览器,$imgData
请从您的detect_object()
函数返回并将其回显到浏览器
<?php
$imgData = detect_object($imagen);
header('Content-Type: image/jpeg');
echo $imgData
推荐阅读
- python - PyOpenGL 没有画大 VAO
- reactjs - 单击按钮时如何控制台记录来自另一个反应组件的数据?
- php - 我可以将 PHP 类方法输出保存到变量中吗
- c - 在 C shell 中实现管道
- r - R:如何填充这两条虚线之间的区域
- mysql - 如何将 SQL CASE 语句与另一个字段的 DISTINCT 结合起来
- scroll - 在 AMP 页面上使用跟踪代码管理器滚动事件无法跟踪百分比
- continuous-integration - GitHub Actions:Prettier 仅在 windows-latest 上发现错误
- python - 创建包含构造函数参数中的字典的类的多个实例
- selenium - 有什么方法可以为一项测试设置“noReset”Appium 功能吗?