开发者

Getting urldata from an image as a blob

So this is what i want to do:

I have an image blob and i need that converted to image data url.

So this is my problem:

<script> 
 document.body.onpaste = function(e) {
var items = e.clipboardData.items;
for (var i = 0; i < items.length; ++i) {
  if (items[i].kind == 'file' && items[i].type == 'image/png') {
    var blob = items[i].getAsFile();
    var reader = new FileReader();
    document.write(reader.readAsDataURL(blob));
  }
}
 };
</script>

This returns an 'undefined'.

So my question is

How would开发者_运维问答 i get the data url from that file. My knowledge from javascript is VERY limited and there isn't very much to go on regarding html5 stuff.

Any and all help is much appreciated.


Figured it out myself, it seems the reason I'm getting undefined is because the image isn't loaded when you call reader.readAsDataURL(blob). I fixed this with:

reader.onload = function (event) {
  document.write(event.target.result);
};


You just need to Base64 encode the data and display it like this:

<img src="data:image/png;base64,[encoded data]">

http://en.wikipedia.org/wiki/Data_URI_scheme#HTML

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜