最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

The easy way to convert an URL Image to Base64 or Blob in JavascriptJquery - Stack Overflow

programmeradmin3浏览0评论

I'm working on an offline mode for a simple application, and I'm using Indexeddb (PounchDB as a library), I need to convert an Image to Base64 or BLOB to be able to save it.

I have tried this code which works for only one Image (the Image provided) I don't know why it doesn't work for any other image:

function convertImgToBase64URL(url, callback, outputFormat){
    var img = new Image();
    img.crossOrigin = 'Anonymous';
    img.onload = function(){
        var canvas = document.createElement('CANVAS'),
        ctx = canvas.getContext('2d'), dataURL;
        canvas.height = img.height;
        canvas.width = img.width;
        ctx.drawImage(img, 0, 0);
        dataURL = canvas.toDataURL(outputFormat);
        callback(dataURL);
        canvas = null; 
    };
    img.src = url;
}
convertImgToBase64URL('.png', function(base64Img){
alert('it works');
      $('.output').find('img').attr('src', base64Img);  
   
});
<script src=".1.1/jquery.min.js"></script>
<div class="output"> <img> </div>

I'm working on an offline mode for a simple application, and I'm using Indexeddb (PounchDB as a library), I need to convert an Image to Base64 or BLOB to be able to save it.

I have tried this code which works for only one Image (the Image provided) I don't know why it doesn't work for any other image:

function convertImgToBase64URL(url, callback, outputFormat){
    var img = new Image();
    img.crossOrigin = 'Anonymous';
    img.onload = function(){
        var canvas = document.createElement('CANVAS'),
        ctx = canvas.getContext('2d'), dataURL;
        canvas.height = img.height;
        canvas.width = img.width;
        ctx.drawImage(img, 0, 0);
        dataURL = canvas.toDataURL(outputFormat);
        callback(dataURL);
        canvas = null; 
    };
    img.src = url;
}
convertImgToBase64URL('http://upload.wikimedia/wikipedia/mons/4/4a/Logo_2013_Google.png', function(base64Img){
alert('it works');
      $('.output').find('img').attr('src', base64Img);  
   
});
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="output"> <img> </div>

It works fine, but only with one Image, If I try any other Image it doesn't work

Share Improve this question asked Apr 13, 2015 at 13:42 Stranger B.Stranger B. 9,36422 gold badges75 silver badges111 bronze badges 4
  • Tried converting html img element to Blob , then to data URI ? – guest271314 Commented Apr 13, 2015 at 14:04
  • I need to convert Image URL to Base64 – Stranger B. Commented Apr 13, 2015 at 14:07
  • Yes. See post below ; see also stackoverflow./questions/2390232/… – guest271314 Commented Apr 13, 2015 at 14:22
  • @YasserB. Thanks for the sample code, helped me for a project.
发布评论

评论列表(0)

  1. 暂无评论