如何在HTML中使用JavaScript/JQuery将PNG图像二进制结果显示为图像

huangapple go评论75阅读模式
英文:

How to display PNG image binary result as image in HTML with Javascript/JQuery

问题

我正在使用这个AI服务的API,允许我编辑图像。我上传一张图像,然后通过该API服务提供的编辑进行处理,最后将结果下载,这是代码:

var form = new FormData();
form.append("api_token", "XXXXXXX1234AAAAAA");
form.append("trans_id", "XXXXBBBBVVVVVVVV"); //处理后的图像ID

var settings = {
  "url": "https://api-service.vanceai.com/web_api/v1/download?api_token=XXXXXXX1234AAAAAA",
  "method": "POST",
  "timeout": 0,
  "processData": false,
  "mimeType": "multipart/form-data",
  "contentType": false,
  "data": form
};

$.ajax(settings).done(function (response) {
        console.log(response); // 二进制结果
});

这是不是Blob的二进制结果。

如何在HTML中使用JavaScript/JQuery将PNG图像二进制结果显示为图像

我想在img标签中显示这个结果:

<img id="ml" src="">

我尝试了以下方法:

$("#ml").attr("src", 'data:image/png;base64,' + btoa(response));

$("#ml").attr("src", 'data:image/png;base64,' + btoa(encodeURIComponent(response)));

$("#ml").attr("src", 'data:image/png;base64,' + btoa(unescape(encodeURIComponent(response))));

但是我得到了以下错误:

如何在HTML中使用JavaScript/JQuery将PNG图像二进制结果显示为图像

或者

如何在HTML中使用JavaScript/JQuery将PNG图像二进制结果显示为图像

其中base64代码未正确显示。

我还尝试将其转换为Blob:

var blob = new Blob([response], {type: 'image/png'});
var reader = new FileReader();

reader.onload = function (e) {
   $('#ml').attr('src', e.target.result);
};

reader.readAsDataURL(blob);

但是我得到了相同的错误:

如何在HTML中使用JavaScript/JQuery将PNG图像二进制结果显示为图像

我使用了一个库:https://github.com/dankogai/js-base64

var emk = Base64.encode(response);
$("#ml").attr("src", 'data:image/png;base64,' + emk);

但结果仍然相同。

最后,我还尝试将此结果转换为Arraybuffer:

var ab = new ArrayBuffer(response.length);
var bb = new Blob([ab],{type: "image/png"});

var reader = new FileReader();
reader.readAsDataURL(bb); 
reader.onloadend = function() {
  var base64data = reader.result;                
  $("#ml").attr("src",base64data);
}

但是仍然出现相同的错误:

如何在HTML中使用JavaScript/JQuery将PNG图像二进制结果显示为图像

我希望能够得到您的帮助。

英文:

I'm using this AI service API which allows me edit images. I upload an image, then process applying an edition provided by this API service and finally the result is for download, this is the code:

var form = new FormData();
form.append(&quot;api_token&quot;, &quot;XXXXXXX1234AAAAAA&quot;);
form.append(&quot;trans_id&quot;, &quot;XXXXBBBBVVVVVVVV&quot;); //processed image ID

var settings = {
  &quot;url&quot;: &quot;https://api-service.vanceai.com/web_api/v1/download?api_token=XXXXXXX1234AAAAAA&quot;,
  &quot;method&quot;: &quot;POST&quot;,
  &quot;timeout&quot;: 0,
  &quot;processData&quot;: false,
  &quot;mimeType&quot;: &quot;multipart/form-data&quot;,
  &quot;contentType&quot;: false,
  &quot;data&quot;: form
};

$.ajax(settings).done(function (response) {
        console.log(response); // binary result
});

This is the binary result which is not a Blob:

如何在HTML中使用JavaScript/JQuery将PNG图像二进制结果显示为图像

I want to display this in an img tag:

&lt;img id=&quot;ml&quot; src=&quot;&quot;&gt;

I tried with these methods:

$(&quot;#ml&quot;).attr(&quot;src&quot;,&#39;data:image/png;base64,&#39;+ btoa(response) );

$(&quot;#ml&quot;).attr(&quot;src&quot;,&#39;data:image/png;base64,&#39;+ btoa(encodeURIComponent(response)) );

$(&quot;#ml&quot;).attr(&quot;src&quot;,&#39;data:image/png;base64,&#39;+ btoa(unescape(encodeURIComponent(response))) );

But I get these errors:

如何在HTML中使用JavaScript/JQuery将PNG图像二进制结果显示为图像

or

如何在HTML中使用JavaScript/JQuery将PNG图像二进制结果显示为图像

where base64 code doesn't display correctly.

I also tried converting to Blob:

var blob = new Blob([response], {type: &#39;image/png&#39;});
		var reader = new FileReader();

		reader.onload = function (e) {
		   $(&#39;#ml&#39;).attr(&#39;src&#39;, e.target.result);
		};

		reader.readAsDataURL(blob);

But I get the same error:

如何在HTML中使用JavaScript/JQuery将PNG图像二进制结果显示为图像

I used a library: https://github.com/dankogai/js-base64

var emk = Base64.encode(response);
$(&quot;#ml&quot;).attr(&quot;src&quot;,&#39;data:image/png;base64,&#39;+ emk );

But the result is the same.

Finally I also tried to convert this result to Arraybuffer:

  var ab = new ArrayBuffer(response.length);
  var bb = new Blob([ab],{type: &quot;image/png&quot;});

  var reader = new FileReader();
	  reader.readAsDataURL(bb); 
	  reader.onloadend = function() {
	  var base64data = reader.result;                
		  //console.log(base64data);

		  $(&quot;#ml&quot;).attr(&quot;src&quot;,base64data);
	  }

But it's the same error:

如何在HTML中使用JavaScript/JQuery将PNG图像二进制结果显示为图像

I'd like to receive your help.

答案1

得分: 2

以下是您要的代码翻译部分:

你想将响应作为二进制数据来处理而不是作为UTF-8文本
为此由于您使用jQuery的 [`ajax()`][1] 方法您需要在`settings`对象中添加一个新字段

```js
var settings = {
  "url": "https://api-service.vanceai.com/web_api/v1/download?api_token=XXXXXXX1234AAAAAA",
  "method": "POST",
  "timeout": 0,
  "processData": false,
  "mimeType": "multipart/form-data",
  "contentType": false,
  "data": form,
  // 添加这个新字段以将响应作为二进制数据来处理
  xhrFields: {
    responseType: "blob"
  }
};

然后在您的 done 回调函数中,response 将是一个 Blob 对象。您可以使用 URL.createObjectURL() 方法创建一个指向该 Blob 数据的符号链接。如果在显示图像后您不再需要 Blob 数据,可以撤销该符号链接。

$.ajax(settings).then((response) => {
  const url = URL.createObjectURL(response);
  $("#ml")
    .prop("src", url)
    .one("load", () => URL.revokeObjectURL(url));
});

<details>
<summary>英文:</summary>

You want to consume that response as binary data, not as UTF-8 text.  
To do so, since you use jQuery&#39;s [`ajax()`][1] method, you need to pass a new field in the `settings` object:

```js
var settings = {
  &quot;url&quot;: &quot;https://api-service.vanceai.com/web_api/v1/download?api_token=XXXXXXX1234AAAAAA&quot;,
  &quot;method&quot;: &quot;POST&quot;,
  &quot;timeout&quot;: 0,
  &quot;processData&quot;: false,
  &quot;mimeType&quot;: &quot;multipart/form-data&quot;,
  &quot;contentType&quot;: false,
  &quot;data&quot;: form,
  // Add this new field to consume the response a binary data
  xhrFields: {
    responseType: &quot;blob&quot;
  }
};

Then in your done callback, response will be a Blob object. You will be able to create a symlink to that Blob's data with the URL.createObjectURL() method. If after displaying that image you don't need the Blob data anymore, you can revoke the symlink.

$.ajax(settings).then((response) =&gt; {
  const url = URL.createObjectURL(response);
  $(&quot;#ml&quot;)
    .prop(&quot;src&quot;, url)
    .one(&quot;load&quot;, () =&gt; URL.revokeObjectURL(url));
});

huangapple
  • 本文由 发表于 2023年2月18日 02:22:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/75487996.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定