canvas - Javascript img to base64 don't load -
i develop photoshop extension sends images server.
edit: extensions in photoshop build html file define gui, js file same js file, it's can launch photoshop function , execute photoshop.
i need send images file system of user (from c:\path\to\images)
to encode images converted them dataurl (base64).
the problem occurs in first time convert images dataurl. in second time , so, manages convert images , fine. in first time image doesn't loaded.
i have folder images , want upload pictures there, used loop runs on photos , set them <img src=path>
, converts them based 64 via <canvas>
.
my code:
function convertlayerstobase64(imgheight, imgwidth){ var img = new image(); images = []; (var i=0; i<=imageslength; i++){ path = folder + "layer " + +".png"; img.src = path; var canvas = document.createelement("canvas"); canvas.height = imgheight; canvas.width = imgwidth; var ctx = canvas.getcontext("2d"); ctx.clearrect(0, 0, canvas.width, canvas.height); ctx.drawimage(img, 0, 0); var dataurl = canvas.todataurl(); images.push( dataurl ); } return images; }
i tried delay conversion delay:
function delay(time) { var d1 = new date(); var d2 = new date(); while (d2.valueof() < d1.valueof() + time) { d2 = new date(); } }
jquery when ready:
$(function(){ images.push(getbase64image()); });
img.complete
while(!img.complete) continue;
(in last example code stuck in loop)
to put function in:
img.onload = function(){ //the function here.. //when use method succeed convert //only last image. }
nothing worked.. tried everything, please tell me change , how fix that.
edit: it's seem me way load image it's when code
the function onload
asynchronous action. cannot return images
last statement within convertlayerstobase64
function. should either use promises
, or more simple approach use callback
function.
function convertlayerstobase64(imgheight, imgwidth, callback){ var images = []; (var = 0; <= imageslength; i++) { var img = new image(); img.onload = function() { var canvas = document.createelement("canvas"); canvas.height = imgheight; canvas.width = imgwidth; var ctx = canvas.getcontext("2d"); ctx.clearrect(0, 0, canvas.width, canvas.height); ctx.drawimage(this, 0, 0); var dataurl = canvas.todataurl(); images.push(dataurl); if(images.length === imageslength) { callback(images); } } path = folder + "layer " + +".png"; img.src = path; } }
you call like:
convertlayerstobase64(200, 200, function(images) { console.log('hii, got images', images); });
this without form of error check, or best practice guidelines, i'll leave implement that.
Comments
Post a Comment