简体   繁体   English

Google Places Photo API 返回一个图像,但是,我不知道如何将它发送到我的前端

[英]Google Places Photo API returns an image, however, I am not sure how to send it to my frontend

If I were to paste this URL in the browser, the API indeed returns an image:如果我将此 URL 粘贴到浏览器中,API 确实会返回一个图像:

https://maps.googleapis.com/maps/api/place/photo?
maxwidth=400&photoreference=examplereference&key=examplekey

Keep in mind I have removed photoreference because it is too long and the secret key because it should be private.请记住,我已经删除了 photoreference 因为它太长,并且因为它应该是私有的而删除了密钥。

After getting the image using PHP, I can't seem to send anything I can work with to my front end.使用 PHP 获取图像后,我似乎无法将可以使用的任何内容发送到我的前端。

$getImage = file_get_contents("https://maps.googleapis.com/maps/api/place/photo?maxwidth=400&photoreference=examplereference&key=examplekey");
$image = json_decode($getImage);
    return response()->json([
        'message' => 'Fetched sight!',
        'image' => $image
    ], 201);

If I try to send $image to the front-end it returns NULL and if I try to send $getImages , I get an error "Malformed UTF-8 characters, possibly incorrectly encoded" .如果我尝试将$image发送到前端,它会返回 NULL ,如果我尝试发送$getImages ,则会收到错误消息"Malformed UTF-8 characters, possibly incorrectly encoded"

Even after reading the documentation - https://developers.google.com/places/web-service/photos , I can't figure out what am I expected to receive from that request.即使在阅读了文档 - https://developers.google.com/places/web-service/photos 之后,我也无法弄清楚我期望从该请求中收到什么。

If you want to give an image content with a JSON API endpoint, you can base64 it's content.如果您想使用 JSON API 端点提供图像内容,您可以 base64 它的内容。

<?php

$getImage = file_get_contents("https://maps.googleapis.com/maps/api/place/photo?maxwidth=400&photoreference=examplereference&key=examplekey");
$image = base64_encode($getImage);
    return response()->json([
        'message' => 'Fetched sight!',
        'image' => $image
    ], 201);

On client side you can create image like this :在客户端,您可以创建这样的图像:

<img src="data:image/png;base64, <image content here>" />

Beware the client will perform some extra operations to create the image (not optimized for large image content).请注意,客户端将执行一些额外的操作来创建图像(未针对大图像内容进行优化)。

Another solution could be to download the image with your backend and serve it with a classic URL from your server.另一种解决方案可能是使用您的后端下载图像,并使用您服务器上的经典 URL 为其提供服务。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM