[英]Function that returns the data URI Base64 string of image in Javascript
I'm really struggling to write a function for getting the Base64 encoding of an image. 我真的很努力编写一个函数来获取图像的Base64编码。 Since this function will be part of a bigger script that uses jsPDF.js to make PDFs on-the-fly from a website, It's important the be able to calculate those Base64 encodings as the result of a function.
由于此函数将是使用jsPDF.js从网站即时生成PDF的更大脚本的一部分,因此重要的是,能够将这些Base64编码作为函数的结果进行计算。 The images will be hosted on the same server, so no same-origin issues.
图像将托管在同一台服务器上,因此没有相同来源的问题。 I know the .toDataURL() method of the canvas element can do this and I also know that the image needs to be fully loaded in order to get the Data URL correctly, so I wrote this function
我知道canvas元素的.toDataURL()方法可以做到这一点,并且我还知道需要完全加载图像才能正确获取数据URL,因此我编写了此函数
// Encode image to Base64
function encodeBase64(url, format)
{
var image = new Image(),
canvas = document.createElement("canvas"),
context = canvas.getContext("2d");
image.src = url;
image.onload = function ()
{
canvas.width = image.width;
canvas.height = image.height;
context.drawImage(image, 0, 0, image.width, image.height);
var dataURL = canvas.toDataURL(format);
alert(dataURL);
};
}
The problem is that I don't know how to "extract" the dataURL value from the onload function so that the encodeBase64 function simply returns that value and I can put it in an array. 问题是我不知道如何从onload函数中“提取” dataURL值,以使encodeBase64函数仅返回该值,并且我可以将其放入数组中。 Alert returns that string correctly so I'm sure the code works, but if I try to write any other statement like "return dataURL" or similar I just get undefined value.
Alert正确返回了该字符串,因此我确定代码可以工作,但是如果我尝试编写任何其他语句,例如“ return dataURL”或类似的语句,则只会得到未定义的值。 Please help.
请帮忙。
First load all the images into an array. 首先将所有图像加载到数组中。
Then create the dataURLs using canvas and load the dataURLs into a second array. 然后使用画布创建dataURL,并将dataURL加载到第二个数组中。
Example code and a Demo: http://jsfiddle.net/m1erickson/fbdb3qbw/ 示例代码和演示: http : //jsfiddle.net/m1erickson/fbdb3qbw/
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; }
canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
// array for dataURLs
var dataURLs=[];
// put the paths to your images in imageURLs[]
var imageURLs=[];
// push all your image urls!
imageURLs.push({url:"https://dl.dropboxusercontent.com/u/139992952/stackoverflow/sun.png",format:null});
imageURLs.push({url:"https://dl.dropboxusercontent.com/u/139992952/stackoverflow/temp1.png",format:'image/jpeg'});
// the loaded images will be placed in images[]
var imgs=[];
var imagesOK=0;
loadAllImages(start);
function loadAllImages(callback){
for (var i=0; i<imageURLs.length; i++) {
var img = new Image();
img.format=imageURLs[i].format;
imgs.push(img);
dataURLs.push('');
img.index=imgs.length-1;
img.onload = function(){
imagesOK++;
if (imagesOK>=imageURLs.length ) {
callback();
}
};
img.onerror=function(){alert("image load failed");}
img.crossOrigin="anonymous";
img.src = imageURLs[i].url;
}
}
function start(){
// the imgs[] array now holds fully loaded images
// the imgs[] are in the same order as imageURLs[]
// now loop through each img and create its dataURL
for(var i=0;i<imgs.length;i++){
var img=imgs[i];
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img, 0, 0, img.width, img.height);
dataURLs[img.index] = canvas.toDataURL(img.format);
}
// Demo: report the results to the console
console.log(dataURLs);
}
}); // end $(function(){});
</script>
</head>
<body>
<h4>Fetch dataURLs from images (see results in the console)</h4>
<canvas id="canvas" width=300 height=300></canvas>
</body>
</html>
[ Addition: pulling urls from textarea ] [另外:从textarea中提取网址]
Here's how to pull the urls from the textarea. 这是从文本区域提取网址的方法。
(#loadImages is a button that's pushed when your user has typed the urls into the textbox). (#loadImages是当用户在文本框中输入网址时按下的按钮)。
I haven't looked at the jsPDF source so I can't speak to your dims
issue. 我没有看过jsPDF来源,所以我无法谈谈您的
dims
问题。
$('#loadImages').click(function(){
var inputText = document.getElementsByTagName("textarea")[0].value.split("\n");
for(var i = 0; i < inputText.length; i++){
imageURLs.push({url: inputText[i],format:"image/jpeg"});
}
loadAllImages(start);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.