简体   繁体   English

将图像转换为Blob,javascript,反应

[英]Convert image to Blob, javascript, react

I feel that I have a pretty straight forward problem, but I've been taring my hair finding a question that answers it:我觉得我有一个非常直截了当的问题,但我一直在梳理头发,找到一个可以回答它的问题:

I have a create-react-app application.我有一个 create-react-app 应用程序。

I have an image in src/images/image.png , and I want to, programatically, convert that image to a Blob.我在src/images/image.png中有一张图片,我想以编程方式将该图片转换为 Blob。

How?如何?

If I render如果我渲染

<img src={require(relativePathToImage)} />

I see the image.我看到了图像。

And if I get it through an input field like:如果我通过输入字段获取它,例如:

<input
  type="file"
  accept="image/png"
  onChange={(e) => setImage(e.target.files[0])}
/>

I get the correct Blob set to image .我将正确的 Blob 设置为image

But how do I bypass doing it manually through the input-field and go directly from但是我如何绕过输入字段和 go 直接从
relativePathToImage to Blob ? relativePathToImageBlob

You can use javascript:您可以使用 javascript:

function imgToBlob(url) {
 let img=new Image();
 img.src=url;
 let canvas=document.createElement('canvas');
 img.onload=function() {
  canvas.width=img.width;
  canvas.height=img.height;
  canvas.getContext('2d').drawImage(img,0,0);
  canvas.toBlob(setLink,'image/png',1) // about toBlob function: https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob
   }
  }

function setLink(blob) {
 document.querySelector('a').href=URL.createObjectURL(blob)
  }

For this html:对于这个 html:

<a>Blob link</a>

Edit: You shuld add to the imgToBlob function line img.crossOringin="anonymus"编辑:您应该添加到imgToBlob function 行img.crossOringin="anonymus"

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

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