First part of my application loads picture with file chooser from my file system and draws image to canvas. I take that canvas and convert it to data URL and also save it in my database.
var imgData = canvas.toDataURL("image/jpg");
factory.saveData(imgData); // execute some java code
Here is the problem. I can't redraw that image, my javascript:
var pic = new Image();
pic.onload = function() {
ctx.drawImage(pic, 0, 0); // ctx = canvas.getContext("2d")
};
// This data url is copy/pasted from database for simplicity
pic.src = "data:image/png;base64,iVBOR..........ElFTkSuQmCC";
Onload function is called but I just get transparent image.
Probably has something to do with the fact that getDataFromDatabase() is asynchronous so you're returning a promise object to pic.src instead of the data url. Fix this by using a then call on getDataFromDatabase and using the result on pic.src like this:
var pic = new Image();
var pic.onload = function() {
ctx.drawImage(pic, 0, 0);
};
getDataFromDatabase().then(dataUrl => {
pic.src = dataUrl;
});
Here's a full example of this in action. I draw to a canvas, store the canvas data as a base64 data url into a variable, save it into a mock DB using closures, then reload the data from a simulated asynchronous function call by using a promise.
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
// Initialize canvas to a random image
const imageUrl = 'https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-logo.svg?v=a010291124bf';
const initialImage = new Image();
initialImage.src = imageUrl;
initialImage.onload = function() {
ctx.drawImage(initialImage, 0, 0);
}
// Convert canvas to base64 data url
const imageData = canvas.toDataURL('image/png');
const getDataFromDatabase = saveData(imageData);
// Clear the canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Redraw the image
const pic = new Image();
getDataFromDatabase().then(data => {
pic.src = data;
});
pic.onload = function() {
ctx.drawImage(pic, 0, 0);
}
function saveData(image) {
return function getDataFromDatabase() {
return new Promise(resolve => {
resolve(image);
});
}
}
<canvas id="myCanvas">
</canvas>
Edit: It shouldn't really matter where you get the image data from. If the data is not malformed, it should draw to the canvas. Here's an example identical to the way you're loading image data (from a hardcoded data url):
const imageData = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAOEAAADhCAMAAAAJbSJIAAAAwFBMVEX/pQD/////owD/oQD/pgD/9+r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TjEBi0Y87AJyL0EHPciwkArxN6iLmdizDbXj/ycJ1QNeo51ahg06qhchCqasPO49LvASZpfCJC1Ym57icrgVWyo4DJCIOy1FkjEQJKOeFZx4SEameeK2cKtBG1zOsNhGrVzZFKBY1ajvg2QlXfrvOib8ByI8rA3ETo11jJByJa16+u83yEanWYA5UK6DnpFGQnVPXHWdaMYNXYDqqyEXojdZSpTgVtGRU1FEWomm6GzgbMpkwjlIvQvyQuo9UfYHndlRBBqDbdQRazEdlTnpINPISq3p+n3o0A5TrXWXguQr8o8EpevUoaH7IryRd5EYQeY0lLbah6L/rmqtZwE6G3/j8MUhmroHw9JyyHKpjQvz9lIfAqigg+2A1ZjDSxhKrReh1LHauAZm9bLgUjiNC/XexdHqPHN+3dxnc7oX+n1tOPIkOxAlq5tJv3Uif0GAv1D9GMgNDLpHvL/DuKCELVv+ehZN94vRaOB8ga9RNXf4kXQYS+NL4HlxcDcNGBtdu0BeGpQglVtdCe/97dAunhzZZJK54nFKGEnlTbtb/jiFtJrtEhbbD5MxGKp4on9KTQeHrf7JTwhR1xcAhmm9pTj6tWWLxIIFT3F8y8D1/sq7f7QVCgxx6P3F/9pgjNGRY5hL7oZrfpTObFtRZziMRa/8wnTrNakEPnizzCvRi6rpv9dukhJJ+lrWN6fxWnNenyfz1KPpfipf7sAAAAAElFTkSuQmCC';
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
const image = new Image();
image.onload = function() {
ctx.drawImage(image, 0, 0);
}
image.src = imageData;
<canvas id="myCanvas">
</canvas>
I suggest you check your image data using a base64 image decoder to see if your image data is malformed or not. If your data url is valid, then something else I can suggest is ensuring your canvas width and height are equal to or greater than the image's width and height or else it'll be hidden (if the image you're supplying has empty space / padding).
Related
I'm creating a maze application with Canvas and having a token traverse the maze from start to finish.
I completed the maze generation and am trying to generate a token at grid (0,0). I've created a button to select a token and throwing a debugger at the end does show that the icon is created in the right position, but it is not persisting after I continue. I've tried adding the image.onload to the drawImage function, but it is still not working.
This was what I originally had that rendered the image on Canvas while in debugger
function selectIcon(){
let body = document.querySelector("body")
let image = document.createElement("img")
image.src = "image.jpg"
body.prepend(image)
// debugger
}
function clickHandler(){
document.addEventListener("click", (e) => {
button = e.target
console.log(button)
if(button.matches(".choose-token")){
renderIconToCanvas()
}
})
}
function renderIconToCanvas(){
const myCanvas = document.querySelector("canvas")
myCanvas.setAttribute("id", "maze-canvas")
const image = new Image;
image.src = "maze/image.jpg"
let ctx = myCanvas.getContext("2d");
ctx.drawImage(image, 0, 0);
}
All of the solutions that I've read say to add image.onload to the drawImage, but when I put it in, my image no longer renders in debugger.
function renderIconToCanvas(){
const myCanvas = document.querySelector("canvas")
myCanvas.setAttribute("id", "maze-canvas")
const image = new Image;
image.src = "maze/image.jpg"
image.onload = function (){
let ctx = myCanvas.getContext("2d");
ctx.drawImage(image, 0, 0);
}
}
Is there something else that I might be missing? Another way that I tried:
let canvas = document.querySelector("canvas")
let ctx = canvas.getContext("2d");
const image = new Image(20,20);
image.src = "./image.jpg"
function draw(ctx, image){
if (!image.complete){
setTimeout(function(){
draw(ctx, image);
}, 50);
return
}
ctx.drawImage(image, 0, 0, this.width, this.height);
}
draw(ctx, image)
I am loading jpg image in python on the server. Then I am loading the same jpg image with javascript on the client. Finally, I am trying to compare it with the python output. But loaded data are different so images do not match. Where do I have a mistake?
Python code
from keras.preprocessing.image import load_img
from keras.preprocessing.image import img_to_array
filename = './rcl.jpg'
original = load_img(filename)
numpy_image = img_to_array(original)
print(numpy_image)
JS code
import * as tf from '#tensorflow/tfjs';
photo() {
var can = document.createElement('canvas');
var ctx = can.getContext("2d");
var img = new Image();
img.onload = function() {
ctx.drawImage(img, 0, 0);
};
img.crossOrigin = "anonymous";
img.src = './rcl.jpg';
var tensor = tf.fromPixels(can).toFloat();
tensor.print()
}
You are drawing the image on a canvas before rendering the canvas as a tensor. Drawing on a canvas can alter the shape of the initial image. For instance, unless specified otherwise - which is the case with your code - the canvas is created with a width of 300 px and a height of 150 px. Therefore the resulting shape of the tensor will be more or less something like the following [150, 300, 3].
1- Using Canvas
Canvas are suited to resize an image as one can draw on the canvas all or part of the initial image. In that case, one needs to resize the canvas.
const canvas = document.create('canvas')
// canvas has initial width: 300px and height: 150px
canvas.width = image.width
canvas.height = image.heigth
// canvas is set to redraw the initial image
const ctx = canvas.getContext('2d')
ctx.drawImage(image, 0, 0) // to draw the entire image
One word of caution though: all the above piece should be executed after the image has finished loading using the event handler onload as the following
const im = new Image()
im.crossOrigin = 'anonymous'
im.src = 'url'
// document.body.appendChild(im) (optional if the image should be displayed)
im.onload = () => {
const canvas = document.create('canvas')
canvas.width = image.width
canvas.height = image.heigth
const ctx = canvas.getContext('2d')
ctx.drawImage(image, 0, 0)
}
or using async/await
function load(url){
return new Promise((resolve, reject) => {
const im = new Image()
im.crossOrigin = 'anonymous'
im.src = 'url'
im.onload = () => {
resolve(im)
}
})
}
// use the load function inside an async function
(async() => {
const image = await load(url)
const canvas = document.create('canvas')
canvas.width = image.width
canvas.height = image.heigth
const ctx = canvas.getContext('2d')
ctx.drawImage(image, 0, 0)
})()
2- Using fromPixel on the image directly
If the image is not to be resized, you can directly render the image as a tensor using fromPixel on the image itself
I have an image for example
"img/Myimage.jpg"
I would like to convert it to the Uint8ClampedArray format (as shown in the image).
For what? I am using a library that after a long process converts the images to this format, but I have others images that I need to convert them on my own to this same format. how can I do it? Excuse my ignorance
var frames = animator.frames;
var res_c = document.getElementById("result");
var res_ctx = res_c.getContext('2d');
for (var x = 0; x < frames.length; x++) {
//***frames are ImageData (Uint8ClampedArray)***
res_ctx.putImageData(frames[x],0,0);
console.log(frames[x])
gif.addFrame(res_c,{copy:true,delay: 120});
}
I need convert my images in ImageData (Uint8ClampedArray) for add others frames
You can use Image constructor, CanvasRenderingContext2D.drawImage() and CanvasRenderingContext2D.getImageData() to create an ImageData object from an image file.
const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");
const width = 300;
const height = 311;
const image = new Image;
image.src = /* Blob URL, "/path/to/image/served/with/cors/headers" */;
image.onload = () => {
ctx.drawImage(image, 0, 0);
imageData = ctx.getImageData(0, 0, 300, 311);
console.log(imageData);
}
An async/await solution using the canvas draw-extract method, takes one paramter as a source string (can pass image.src if you already have an image):
/** #param {string} source */
async function imageDataFromSource (source) {
const image = Object.assign(new Image(), { src: source });
await new Promise(resolve => image.addEventListener('load', () => resolve()));
const context = Object.assign(document.createElement('canvas'), {
width: image.width,
height: image.height
}).getContext('2d');
context.imageSmoothingEnabled = false;
context.drawImage(image, 0, 0);
return context.getImageData(0, 0, image.width, image.height);
}
Example:
// image source
const source = 'https://raw.githubusercontent.com/Rovoska/undertale/master/sprites/images/spr_maincharad_3.png';
// async wrapper
async epic () {
// log data to console
console.log(await imageDataFromSource(source));
}
// do the epic
epic();
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/bAIQAAwICCAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICggICAgKCQoICAsNCggNCAgKCAEDBAQGBQYKBgYKDg4KDhANEBAQDw0NDg4NDQ0NDQ8NDQ0NDQ0NDQ0NDQ0NDQ0PDQ0NDQ0NDQ0NDQ0ODQ0NDQ0N/8AAEQgAjACMAwERAAIRAQMRAf/EAB4AAAEEAwEBAQAAAAAAAAAAAAABAggJBQYHBAMK/8QASBAAAgECBAMEBgQKBwkBAAAAAQIDBBEABRIhBggTBwkiMRRBUVSU0xgjMkIVFhkkUlVWYYHSF1NicZGj1CUzNENylbG0wXX/xAAcAQEAAQUBAQAAAAAAAAAAAAAAAwEEBQYHAgj/xAA+EQACAQIDBAMMCQUBAQAAAAAAAQIDBAURIQYSMVETQWEHFRYXIlNxgZGSsdEUMjNUYqGiweEjQlJy8EMk/9oADAMBAAIRAxEAPwC1IHAC4AMAGADABgAwAYAMAGADABgAwAYAMAGADABgBMAF8ALgAwAYAMAah2k9rmWZPAanNK6moYR5PUSqhc/oxp9uV/7Eas37sARkzTvaeDI3CJV1s416TJFl9QEC2J6n1qxOUBsuyFrkWUi5AHbuxjmw4e4gFspzSnqZbEmmYtBVgA2LGlqFinKA/fCFPLxG4uB1sHAHyqqtUVndgqKCzMxCqqjcszGwAA3JJAAwBGLjzvMODMvkaJ82FVIrFWWhgnqlBW4J60cfo7C4tdZTe4IuLkAfPsx7zHg/NJUhTMvQ5nAKpmML0ik/oekPelD3IAUzjU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upZY54JWm9EiiljbUrLFTaXIuAGSWeRHGpWUqxGAJrgWwAYAMALfAADgBCMAPwAhOAE1YACMAJgAwAoOAFIwA3ADUjA8ha5vt7fb/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;
}
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.