base64转换PNG数据的JavaScript文件对象 [英] Convert base64 png data to javascript file objects
问题描述
我有两个连接的base64 codeD PNG的,我要使用这个库对它们进行比较:
https://github.com/Huddle/Resemble.js
I have two base64 encoded png's, and i want to compare them using this library: https://github.com/Huddle/Resemble.js
我认为要做到这一点的最好办法是转换PNG的成文件对象使用的FileReader,
但我无法弄清楚如何这样:(
i think that the best way to do it is to convert the png's into file objects using fileReader, but i can't figure out how to to this :(
什么想法?
感谢您!
推荐答案
您可以创建一个的Blob
从您的base64数据,然后读 asDataURL
:
You can create a Blob
from your base64 data, and then read it asDataURL
:
var img_b64 = canvas.toDataURL('image/png');
var png = img_b64.split(',')[1];
var the_file = new Blob([window.atob(png)], {type: 'image/png', encoding: 'utf-8'});
var fr = new FileReader();
fr.onload = function ( oFREvent ) {
var v = oFREvent.target.result.split(',')[1]; // encoding is messed up here, so we fix it
v = atob(v);
var good_b64 = btoa(decodeURIComponent(escape(v)));
document.getElementById("uploadPreview").src = "data:image/png;base64," + good_b64;
};
fr.readAsDataURL(the_file);
完整的示例(包括垃圾code和控制台日志的): http://jsfiddle.net/tTYb8 /
另外,你可以使用 .readAsText
,它工作正常,而其更优雅..但由于某些原因的文本的不健全的权利;)
Alternatively, you can use .readAsText
, it works fine, and its more elegant.. but for some reason text does not sound right ;)
fr.onload = function ( oFREvent ) {
document.getElementById("uploadPreview").src = "data:image/png;base64,"
+ btoa(oFREvent.target.result);
};
fr.readAsText(the_file, "utf-8"); // its important to specify encoding here
完整的示例: http://jsfiddle.net/tTYb8/3/
这篇关于base64转换PNG数据的JavaScript文件对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!