Javascript img to base64 don't load - javascript

I develop Photoshop extension that sends images to the server.
Edit: Extensions in photoshop build from html file that define the GUI, js file that basically is the same as any js file, but it's can also launch photoshop function and it is execute from photoshop.
I need to send the images from the file system of the user (from C:\path\to\images)
To encode the images I converted them to dataURL (base64).
The problem occurs in the first time that I convert the images to dataURL. But in the second time and so, it manages to convert the images and everything is fine. In the first time the image doesn't loaded.
I have a folder where the images are and I want to upload the pictures from there, I used a loop that runs on photos and set them into <img src=path> to and then it converts them based 64 via <canvas>.
My code:
function convertLayersToBase64(imgHeight, imgWidth){
var img = new Image();
images = [];
for (var i=0; i<=imagesLength; i++){
path = folder + "layer " + i +".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 to delay the conversion by 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 the last example the code stuck in loop)
To put the function in:
img.onload = function(){
//the function here..
//when I use this method it succeed to convert
//only the last image.
}
Nothing worked..
I tried everything, please tell me what to change and how to fix that.
Edit: It's seem to me that the only way to load an image it's when the code

The function onload is an asynchronous action. You cannot just return images as the last statement within your convertLayersToBase64 function. You should either use promises, or a more simple approach would be to use a callback function.
function convertLayersToBase64(imgHeight, imgWidth, callback){
var images = [];
for (var i = 0; i <= 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 " + i +".png";
img.src = path;
}
}
You would call this like:
convertLayersToBase64(200, 200, function(images) {
console.log('hii, i got images', images);
});
This is obviously without any form of error check, or even best practice guidelines, but I'll leave it up to you to implement that.

Related

Can't seem to get an old image off the canvas

I'm importing an image (that has to come in portrait) onto a canvas object, rotating it (because it's actually landscape) and running some OCR on the base64 from the canvas. That all works fine. However when I put a new image onto the canvas, the old one is retained and never replaced. I've tried clearRect, even gone to the extent of creating a new dom element each time and destroying it when I have everything I need (which is still in the code below) but I just cannot get the first image to clear.
Here's the relevant bit of the code
function onSuccess(imageURI) {
//CREATE NEW CANVAS ELEMENT
g = document.createElement('canvas');
g.setAttribute("id", "thePic");
g.style.overflow = "visible";
document.body.appendChild(g);
const canvas = document.getElementById('thePic'),
context = canvas.getContext('2d');
make_base();
function make_base()
{
base_image = new Image();
base_image.src = imageURI;
base_image.onload = function(){
const uriheight = base_image.naturalHeight;
const uriwidth = base_image.naturalWidth;
console.log(uriwidth + " " + uriheight);
context.canvas.width = uriheight;
context.canvas.height = uriheight;
context.drawImage(base_image, 0, 0);
//ROTATE THE IMAGE 90
context.clearRect(0,0,canvas.width,canvas.height);
context.save();
context.translate(canvas.width/2,canvas.height/2);
context.rotate(90*Math.PI/180);
context.drawImage(base_image,-base_image.width/1.2,-base_image.width/1.2);
context.restore();
var theCanvas = document.getElementById('thePic');
var rotImg = theCanvas.toDataURL();
var rotImg = rotImg.substring(21);
textocr.recText(4, rotImg, onSuccess, onFail);
function onSuccess(recognizedText) {
var recdata = recognizedText.lines.linetext;
var blockData = recognizedText.blocks.blocktext;
context.clearRect(0, 0, 10000,10000);
base_image = "";
rotImg = "";
document.getElementById('thePic').outerHTML = "";
document.getElementById('cgh').innerHTML = "";
}
}
}
Any advice much appreciated.
So it turned out to not be the canvas at all, it was image caching in a previous function that give the image to the canvas.
Thanks to everyone who took the time to have a squiz.

jsPDF addImage not working

I am using jsPDF to create a PDF by looping through some HTML code to find the values it needs. I am able to get the values just fine, but when I try to insert the header_img it does not work. I have found many solutions on Google but the one I am working with now is the only one that does not throw an error.
This is the code being used to get take the url that is provided via the loop, convert it to a DataURL, and then insert the image into the PDF. It does not give me any errors, but all that is in the PDF is the black border and no image. Any ideas?
function getDataUri(url, cb) {
var image = new Image();
image.setAttribute('crossOrigin', 'anonymous'); //getting images from external domain
image.onload = function () {
console.log(url);
var canvas = document.createElement('canvas');
canvas.width = this.naturalWidth;
canvas.height = this.naturalHeight;
//next three lines for white background in case png has a transparent background
var ctx = canvas.getContext('2d');
ctx.fillStyle = '#fff'; /// set white fill style
ctx.fillRect(0, 0, canvas.width, canvas.height);
canvas.getContext('2d').drawImage(this, 0, 0);
cb(canvas.toDataURL('image/jpeg'));
};
image.src = url;
}
var pdf = new jsPDF('p', 'in', 'letter');
var left_margin = .5;
var top_margin =.5;
var height = 2.313;
var width = 3.25;
var header_img_height = 1;
//Draw border
pdf.setLineWidth(1/92);
pdf.setDrawColor(0, 0, 0);
pdf.rect(left_margin, top_margin, width, height);
//example image
var header_img = 'http://www.quotehd.com/imagequotes/authors24/jeff-olsen-quote-two-clicks-and-its-broke.jpg';
let logo = null;
//callback to get DataURL
getDataUri(header_img, function(dataUri) {
logo = dataUri;
console.log("logo=" + logo);
//Add image to PDF
pdf.addImage(logo, 'JPEG', left_margin, top_margin, header_img_height, width);
});
pdf.output('save', 'test.pdf');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.4.1/jspdf.debug.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I ended up solving the issue by writing a PHP script that would convert the image to Base64.
$img_src = urldecode($_GET['url']);
$img_str = base64_encode(file_get_contents($img_src));
echo 'data:' . getimagesize($img_src)['mime'] . ';base64,' . $img_str;
Then using jQuery, I passed the url to the PHP script and got the Base64 data in return:
function getBase64(url) {
var out = '';
$.ajax({
url: 'get-dataurl.php?url=' + encodeURI(url),
async: false,
dataTye: 'text',
success: function(data) {
out = data;
}
});
return out;
}
Certainly was not ideal, but it works.
You can encode the image to base64, you would use this tool or any similar and replace it on your code.

Is there any way to draw the corrupted images in the canvas?

I am trying to draw an image in the canvas. The image that I'm using is got as base64 string from the server. For testing purpose, I have saved the image to the disk both at the client and the server while debugging. The image is saved fine. While drawing in the canvas, the image is not rendered in Chrome and Firefox. But it works fine in IE 11.Is there any way to make the images draw in all the browsers.
var base64String = "data:image/png;base64,SUkqANZ1AQAAEbQhURQh0dUQ6mh0dHQ62ao6GIEQkpodHSEOqKiHXodDqaoh1NOqKaOjo6HU0dUQ6mqIdeh16dSUJQqJCmh0hUR0OvQ6HU0OqIdenXodTQ69DqidTVEdOpodIXIdDr1RDokXIdeh0OuQ6HXodDr0Oh16HQ6oh16HQ6mh1NDqioi6XS0OqKidcnXp16HTr0OqIdHQ69Dodch1PHX469D1EOvQ6HU0OqIdch0hUQ2h0dF0DVEOqI6HS2tgiHQ65Do6Qh1NDqiQqIdHU0OhiOhCHU0dOqL0OpqiHXodDpe0XR0OvQ6QqIdHVE69DqaHXpOADuamqIujo6IR1t1RHVEhHR0dBqiOi6OkI6BobS8IQgRF1RHSEDR0dA0hNypCEOqIhAilqtlCS1uEDSEDQmhpURCmh0XR1sYqI6Bo6og0NI6QkJCLoGhpSLpCGJCEJCQjoQh0dIVEdBEDRmACU.." //only few of the string is shared
function drwImage(base64String) {
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
var img = new Image();
img.onload=function(){
context.drawImage(img, 0, 0, 1, 1);
}
img.src = base64String;
}
Thanks for your help in advance.
Seems something related to the serialized image, as you can see in the snippet below, it works on Chrome, I used an online encoder.
As you can read here the datauri is almost supported at all.
var base64String = "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/4QAqRXhpZgAASUkqAAgAAAABADEBAgAHAAAAGgAAAAAAAABHb29nbGUAAP/bAIQAAwICCAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICggICAgKCQoICAsNCggNCAgKCAEDBAQGBQYKBgYKDg4KD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X9GkhMelS+kOAHUkkhQGctPepZ9kxip8yJzrL1suiofTXRJsLw1hDNJpFyEqRLq2USReYA1PvDOb2Hi3M6OSiWZMuoaQJBHOipL6RUaZKx2VWcDdYoNmIIp9Q2e5Asz7rTsKbJ+F4KiYEVWcOMykU/cgdAlGlrC16cCY3F9U7C5sLATDwA04AwHGPHtDl8Rmr6ymoolBYyVU8UCADzN5GUG1x5X8x7cAUW945xHw1XZ62YcO1YqGq1ZszWOGWOnFWmkCeCSREWT0hCTL0wV6iF9TGVtIEou6D5syxPCtdISbSVGTMxvYKGlqqEHzAVQ9VED5D0gXFo1wBagMAJgAIwA5cABwA3AD8AIRgBNWAPPXUKSo0ciLJG6lXR1Do6sLMrKwKspGxBBBGAIK8y/dL5LmokqMmK5LXG7dNFLZbK3sanG9NfyDUxCLe/RfywBAvgju4M+j4lyzJ81opI6SpqdU9bAWlo5KOnXrVXTqY7dN3iUxIsohk6kieHfAF8FLSqiqiKFRQFVVFgqqAqqAPIAAAfuwB9r4A5TzU55mVLw7nFRlCu2YxUUr0vTUPKrC2uSJCj9SWOLXIiaWLMqgC5GAKB8t7OuJOIqsulJm2bVTOUeZ46icq12JWSeX6uEKQ20joqnbbAEney3udOJazQ2Yz0WUxNYsrv6bUrf1dGnPRJHrBql88ATZ7Au6lyHJKqnr5KrMK6upZY54JWm9EiiljbUrLFTaXIuAGSWeRHGpWUqxGAJrgWwAYAMALfAADgBCMAPwAhOAE1YACMAJgAwAoOAFIwA3ADUjA8ha5vt7fb/HAD8AF8AGnACYAMAAwApwAA4AdgBrYATACkYACMAFsAFsAGADTgBCMAGADAC2wAmADAAMAOwAAYAXACEYAXADWwAmAFbAC2wAWwAuAG2wAHAAcADYATABgAwA62ADAH//Z" //only few of the string is shared
drwImage(base64String);
function drwImage(b) {
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
var img = new Image();
img.onload = function() {
console.log('load')
context.drawImage(img, 0, 0, 1, 1);
document.body.appendChild(img);
}
img.onerror = function() {
console.log('error')
}
img.src = b;
}

Unable to load an Image into Canvas and get base64 encoding for that image

I am trying to generate a PDF from HTML using jspdf plugin. I am stuck with loading Images into PDF. There is a function addImage() in plugin which takes base64 encoding of an image, but converting an image to base64 is not working.
I have used below two ways
//Create canvas, draw image in context and get the data url
imgToDataURL = function (img, outputFormat){
var canvas = document.createElement('canvas');
canvas.width = 20;
canvas.height = 20;
var c = canvas.getContext('2d');
c.height = img.height;
c.width=img.width;
c.drawImage(img, 0, 0);
c.save();
var dataurl = canvas.toDataURL(outputFormat);
return dataurl;
}
var img = new Image();
img.crossOrigin = 'Anonymous';
img.src = "image path"
img.height= 60;
img.width=60;
var dataURL = this.imgToDataURL(img,"image/jpeg");
renderer.pdf.addImage(dataURL, 'png',x+padding,y + this.internal.getLineHeight(),imageWidth,imageHeight);
This is printing wrong dataURL I am getting a white image. If I hard code the base64 code i.e return a hardcoded dataURL then addImage works fine. So the issue is with canvas.toDataURL which is giving me wrong output
this is the 2nd way
convertImgToBase64URL = function (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 = this.height;
canvas.width = this.width;
ctx.drawImage(this, 0, 0);
dataURL = canvas.toDataURL(outputFormat);
callback(dataURL);
canvas = null;
};
img.src = url;
}
this.convertImgToBase64URL("Image Path",function(base64){
renderer.pdf.addImage(base64, 'PNG', 20, 20,48,48);
})
I have run this inside a javascript and the onload function is not even running I am not sure what is my mistake is.
Please suggest me what mistake I am doing in either way
In the first you missed assigning an onload function to your image. For that reason, the moment you try to create the dataURL, the image might not be loaded yet, ergo, the blank image. You could try changing the last few lines to this:
...
img.width=60;
img.onload = function () {
var dataURL = this.imgToDataURL(img,"image/jpeg");
renderer.pdf.addImage(dataURL, 'png',x+padding,y + this.internal.getLineHeight(),imageWidth,imageHeight);
}
img.src = "image path";
As for the second one, there seems to be a problem with the convertImgToBase64URL() which accepts 3 parameters, but you are passing 2. In you example, outputFormat parameter is undefined.

Making masks with Canvas globalCompositeOperation for jigsaw puzzle game backend

I'm trying to make a backend for publishing simple jigsaw-puzzle games. The game uses 12 premade shapes as masks for making the 12 puzzle pieces. I found the excellent Canvas global CompositeOperation tutorial, and tested it.
The application I'm making is using ajax to send each finished piece to the serverside .php-script. The user loads an image (600x400) using SSE and the app moves the original image inside tempCanvas according to the values of the arrays arr_x and arr_y It's supposed to happen in a for-loop:
function drawPieces(){
var canvas = document.getElementById("myCanvas");
var context =canvas.getContext("2d");
var tempCanvas = document.getElementById("tempCanvas");
var tempContext = tempCanvas.getContext("2d");
var img_mask = new Image();
var w;
var h;
var cvd0,cvd1,cvd2,cvd3,cvd4,cvd5,cvd6,cvd7,cvd8,cvd9,cvd10,cvd11;
var arr_data = [cvd0,cvd1,cvd2,cvd3,cvd4,cvd5,cvd6,cvd7,cvd8,cvd9,cvd10,cvd11];
var arr_x = [0,-136,-289,-414,0,-115,-270,-415,0,-118,-288,-415];
var arr_y = [0,0,0,0,-113,-111,-111,-124,-244,-256,-243,-241];
var img_bg = new Image(600, 400);
for (var i = 0; i<arr_x.length; i++) {
img_bg = original;
// get the mask
img_mask.src = "img/mask"+i+".png";
w = img_mask.width;
h = img_mask.height;
console.log("w = ", img_mask.width, " h = ", img_mask.height);
tempCanvas.width = w;
tempCanvas.height = h;
// Her lages maska
tempContext.drawImage(img_mask,0,0);
tempContext.globalCompositeOperation = 'source-in';
tempContext.drawImage(img_bg,arr_x[i],arr_y[i]);
myCanvas.width = w;
myCanvas.height = h;
// Draws tempCanvas on to myCanvas
console.log("tempCanvas: ", tempCanvas, " img_mask.src = ", img_mask.src);
context.drawImage(tempCanvas, 0, 0);
arr_data[i] = myCanvas;
sendData(arr_data[i], [i]);
};
}
Sending the image data to the server:
function sendData(cvd, index){
var imageData = cvd.toDataURL("image/png");
var ajax = new XMLHttpRequest();
ajax.open("POST", "testsave.php", false);
// ajax.onreadystatechange=function(){
// console.log("index = ", index)
// };
ajax.setRequestHeader('Content-Type', 'application/upload');
ajax.send(imageData+"<split>"+index);
};
I got a button to start drawPieces. But I get a number of issues. Firefox throws an error:
InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable: context.drawImage(tempCanvas, 0, 0);
But if I click the button again the loop is run and I get 12 pieces in my folder. (Using xammp for now). But the pieces are cut wrong! The app doesn't seem to load the correct mask each time the loop runs.
So I tested it without using a loop by having 12 different functions where each function is calling the next one. It worked with one function, but started messing up the masks when I added more:
function drawPiece0(){
img_bg = original;
img_mask.src = "img/mask0.png";
tempCanvas.width = 185;
tempCanvas.height = 145;
// Her lages maska
tempContext.drawImage(img_mask,0,0);
tempContext.globalCompositeOperation = 'source-in';
tempContext.drawImage(img_bg,0,0);
myCanvas.width = 185;
myCanvas.height = 145;
// Tegner tempCanvas over på myCanvas
context.drawImage(tempCanvas, 0, 0);
cvd0 = myCanvas;
sendData(cvd0, 0);
// drawPiece1();
};
Something is absolutely wrong in my setup, but I can't figure out what it is. Someone help me please!
By the way, here is my .php-script too:
<?php
if (isset($GLOBALS["HTTP_RAW_POST_DATA"]))
{
// Get the data
$imageData=$GLOBALS['HTTP_RAW_POST_DATA'];
$parts = explode("<split>", $imageData);
$imageData = $parts[0];
$index= $parts[1];
// Remove the headers (data:,) part.
// A real application should use them according to needs such as to check image type
$filteredData=substr($imageData, strpos($imageData, ",")+1);
// Need to decode before saving since the data we received is already base64 encoded
$unencodedData=base64_decode($filteredData);
// Save file.
$fp = fopen( "pieces/".$index.".png", "wb" );
fwrite( $fp, $unencodedData);
fclose( $fp );
}
?>
Problem
The problem is that image loading is asynchronous which means they load in the background while your code is continuing.
That means the images won't be ready (loaded and decoded) when you try to use them with drawImage resulting in the error. The error is indirect here though as w and h do not get valid values for the canvas which means canvas will be 0 width and 0 height which will trigger the actual error when attempted drawn.
The reason why it "works" the second time is because an image exists in the browser's cache and may be able to provide the image before it's used.
Another problem is that in your loop you are overwriting the image variable so only the last image will be used when loaded.
Solution
The solution is to make or use an image loader before you start the loop. It's easy to make one but for simplicity I will use the YAIL loader in this example (disclaimer: author ibid) but any kind of loader will do as long as you use a callback for the images:
function drawPieces(){
var canvas = document.getElementById("myCanvas");
var context =canvas.getContext("2d");
var tempCanvas = document.getElementById("tempCanvas");
var tempContext = tempCanvas.getContext("2d");
var img_mask;
var w;
var h;
var cvd0,cvd1,cvd2,cvd3,cvd4,cvd5,cvd6,cvd7,cvd8,cvd9,cvd10,cvd11;
var arr_data = [cvd0,cvd1,cvd2,cvd3,cvd4,cvd5,cvd6,cvd7,cvd8,cvd9,cvd10,cvd11];
var arr_x = [0,-136,-289,-414,0,-115,-270,-415,0,-118,-288,-415];
var arr_y = [0,0,0,0,-113,-111,-111,-124,-244,-256,-243,-241];
var img_bg;
// using some image(s) loader
var loader = new YAIL({done: draw});
for (var i = 0; i<arr_x.length; i++)
loader.add("img/mask"+i+".png");
loader.load(); // start loading images
// this is called when images has loaded
function draw(e) {
for (var i = 0; i<arr_x.length; i++) {
//img_bg = original; ??
// get the mask
var img_mask = e.images[i]; // loaded images in an array
w = img_mask.width; // now you will have a valid
h = img_mask.height; // dimension here
console.log("w = ", img_mask.width, " h = ", img_mask.height);
tempCanvas.width = w;
tempCanvas.height = h;
// Her lages maska
tempContext.drawImage(img_mask,0,0);
tempContext.globalCompositeOperation = 'source-in';
tempContext.drawImage(img_bg,arr_x[i],arr_y[i]);
myCanvas.width = w;
myCanvas.height = h;
// Draws tempCanvas on to myCanvas
console.log("tempCanvas: ", tempCanvas, " img_mask.src = ", img_mask.src);
context.drawImage(tempCanvas, 0, 0);
arr_data[i] = myCanvas;
sendData(arr_data[i], [i]);
}
};
}
Note: loading images will make your code asynchronous in nature. If the code depends on some other function right after the pieces has been drawn then you must invoke that function from within the inner one after the loop has finished.
Hope this helps. If the pieces still doesn't show correctly please set up a fiddle with the images uploaded to f.ex. imgur.com so we can dig deeper into the problem.
Hope this helps!

Categories

Resources