Img url to dataurl using JavaScript

喜夏-厌秋 提交于 2020-03-18 12:11:33

问题


Using JavaScript, I want to convert an img tag like this:

<img width="11" height="14" src="http://mysite/file.gif" alt="File Icon">

Into one with a dataurl like this:

<img width="11" height="14" src="data:image/gif;base64,R0lGODlhCwAOAMQfAP////7+/vj4+Hh4eHd3d/v7+/Dw8HV1dfLy8ubm5vX19e3t7fr6+nl5edra2nZ2dnx8fMHBwYODg/b29np6eujo6JGRkeHh4eTk5LCwsN3d3dfX13Jycp2dnevr6////yH5BAEAAB8ALAAAAAALAA4AAAVq4NFw1DNAX/o9imAsBtKpxKRd1+YEWUoIiUoiEWEAApIDMLGoRCyWiKThenkwDgeGMiggDLEXQkDoThCKNLpQDgjeAsY7MHgECgx8YR8oHwNHfwADBACGh4EDA4iGAYAEBAcQIg0Dk gcEIQA7" alt="File Icon">

Is this possible?


回答1:


First, load the image into a canvas

var canvas = document.createElement("canvas");
context = canvas.getContext('2d');

make_base();

function make_base()
{
  base_image = new Image();
  base_image.src = 'img/base.png';
  base_image.onload = function(){
    context.drawImage(base_image, 100, 100);
  }
}

Make sure to update the context.drawImage(base_image, 100, 100); to values appropriate for your application.

Source: https://stackoverflow.com/a/6011402/3969707

Then convert the canvas to data.

var jpegUrl = canvas.toDataURL("image/jpeg");
var pngUrl = canvas.toDataURL(); // PNG is the default

Source: https://stackoverflow.com/a/15685877/3969707




回答2:


Here's how to get the data url of an image with fetch:

(async function() {
    let blob = await fetch("https://example.com/image.png").then(r => r.blob());
    let dataUrl = await new Promise(resolve => {
      let reader = new FileReader();
      reader.onload = () => resolve(reader.result);
      reader.readAsDataURL(blob);
    });
    // now do something with `dataUrl`
})();



回答3:


This really isn't something you may want to do in JavaScript as it requires the image be parsed in JavaScript which is very slow. You would be loading the image and then putting the output of the function into the img tag, which doesn't save bandwidth, decrease complexity, or improve security.

Your best bet is to do this server-side. I've used this to great success in the past for generating pages which need to have absolutely no linked/referenced external resources. You can, for jsPDF, then use raw JavaScript or jQuery to get the data of an image to pass into the PDF creation process.

This will work everywhere and not rely on resorting to canvas which doesn't have full mobile browser support.



来源:https://stackoverflow.com/questions/25690641/img-url-to-dataurl-using-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!