【发布时间】:2020-12-02 10:40:04
【问题描述】:
我是 React 新手,想显示下载为二进制数据的图像。我从 api 调用下载图像数据到 adobe lightroom api。 api 调用有效,因为图像在 Postman 中显示没有问题。我还可以将图像数据保存为 jpeg 文件,并且显示正常。
在 React 中,我想做<img src={`data:image/jpeg;base64,${theImage}`} />,为此我需要将二进制数据转换为 base64 编码的字符串。当我使用 cat image.jpeg|base64 > base64.txt 转换下载的 jpeg 时,生成的字符串可以在我的 React 应用程序中使用。
但是当我在 React 中尝试 var theImage = btoa(binarydata) 时,我得到了 Unhandled Rejection (InvalidCharacterError): Failed to execute 'btoa' on 'Window': The string to be encoded contains characters outside of the Latin1 range.
搜索问题后,我尝试使用var theImage = btoa(unescape(encodeURIComponent( binarydata ))) 和类似的建议解决方案,但从这些结果中得到的字符串并不像看起来那样是 jpeg 的有效 base64 编码(我尝试在线 base64 中的转换结果- >图像服务,没有显示图像)。我还尝试了其他建议的解决方案,例如 base64-js 和 js-base64 库,但这些库都没有创建可以在我的 React 代码中显示的有效 base64 有效图像。
btoa 抛出 latin1 异常时,如何将 jpeg 二进制数据转换为有效的 Base64 图像编码?
【问题讨论】:
-
旁注:在
dataURI 中,base64,之后不应有空格。 -
unescape(及其表亲escape)永远不应该被使用。它们是 1995 年以来的遗留问题。特别是,unescape不是encodeURIComponent的反面。 -
你是怎么得到
binarydata的?错误消息告诉您问题在于binarydata不是有效的binary string(其中包含字符代码值> 255 的字符)。 -
我通过对 Adobe lightroom API 的 API 调用获得它。
const resp = await axios.get('https://lr.adobe.io/v2/catalogs/<catalogid>/assets/${imageid}/renditions/thumbnail2x', {...调用在 Postman 中有效(显示图像)。文档在这里:adobe.io/apis/creativecloud/lightroom/apidocs.html#/assets/… -
这只是故事的一部分。一旦你得到
resp,你会怎么做?服务器如何发送数据?请注意,您不能只将 Blob 或 ArrayBuffer(例如)转储到btoa。
标签: javascript reactjs base64 jpeg