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 toBlob
, then todata 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.