将原始图像数据转换为可在HTML中使用的数据

问题描述

在这里看到了几篇类似的文章,但是我找不到有效的解决方案,因此希望有关该主题的新话题可以提供更多的清晰度。

我正在使用Google Places API,当我尝试取回图像时,我得到的似乎是原始图像数据。我不知道该怎么办以及如何使其在html中可用。我曾尝试在base64中对其进行编码,然后将其应用于图像标签,就像我在某些帖子中所读到的那样,但它仅显示损坏的图像。最主要的问题是,直到/除非我可以在DOM中正确呈现它,我什至似乎没有任何方法可以验证我是否从api调用获取了合法的图像。

这是api调用的完整代码

function makeAPICall(url) {
  return fetch(url);
}    
makeAPICall(`http://localhost:5000/places/${searchString}`)
          .then(response => {
            return response.json();
          })
          .then(data => {
            responSEObject = data.results;
            renderResult(responSEObject[10]);
    
            return responSEObject[10];
          })
          .then(responSEObject => {
            makeAPICall(`http://localhost:5000/place/image/${responSEObject.photos[0].photo_reference}`)
              .then(response => {
    
                return response;
              })
              .then(photoData => {
                console.log(photoData.url);
                const encodedImg = btoa(photoData.url);
    
                bizImage.src = `data:image/jpeg;base64,${encodedImg}`;
              });
          });

试图处理图像的特定代码段:

.then(photoData => {
      console.log(photoData.url);
      const encodedImg = btoa(photoData.url);
    
      bizImage.src = `data:image/jpeg;base64,${encodedImg}`;
});

返回的原始数据的样本(整个blob太大,无法包含在帖子中):

����JFIF��*ExifII*1Google���ICC_PROFILE�mntrRGB XYZ �$acsp���-)�=ޯ�U�xB��ʃ9 descDybXYZ�bTRC�dmdd ��gXYZ hgTRC�lumi |meas �$bkpt �rXYZ �rTRC�tech �vued ��wtptpcprt�7chad�,descsRGB IEC61966-2-1 black scaledXYZ $����curv #(-27;@EJOTY^chmrw|������������������������� %+28>ELRY`gnu|����������������&/8AKT]gqz������������!-8COZfr~���������� -;HUcq~��������� +:IXgw��������'7HYj{�������+=Oat�������2FZn�������  % : O d y � � � � � �  ' = T j � � � � � �"9Qi������*C\u����� & @ Z t � � � � �.Id���� %A^z���� &Ca~����1Om����&Ed����#Cc����'Ij����4Vx���&Il����Ae����@e����

解决方法

因此,通过大量的阅读和研究,我对这个API有了更好的理解,并意识到我在以错误的方式进行操作。有一个client-side service用于放置地点和地图的api,应该用于这类事情,并实际上返回可用数据。完全公开,我觉得Google在这方面组织其文档的方式非常糟糕,但其中的信息仍然存在。

,
data:image/gif;base64,${encodedImg}

JFIF是JPEG文件交换格式。