I'm trying to resize an image which comes from a Quill editor.
I used this links as guides:
https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/drawImage
Resize image with javascript canvas (smoothly)
This is my code:
async handleImageAdded(file, Editor, cursorLocation, resetUploader) {
// Resizing
var img = document.createElement("img");
img.src = URL.createObjectURL(file);
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, 200, 200);
var newFile = await new Promise(resolve => canvas.toBlob(resolve));
document.getElementById("preview").src = URL.createObjectURL(newFile); //check
//Sending data to server
Expected behaviour: will display a resized version of the image which was sent in a file variable. (if I switch newFile to file, everything works just as expected)
Current behaviour: a white rectangle 300x150px
Could you please help me to find what am I missing?
The reason was the absence of image.onload event handler.
This worked for me:
async handleImageAdded(file, Editor, cursorLocation, resetUploader) {
// Resizing
var img = document.createElement("img");
img.src = URL.createObjectURL(file);
var newFile;
const promise = new Promise(resolve => {
img.onload = function (event) {
// Dynamically create a canvas element
var canvas = document.createElement("canvas");
// var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
// Actual resizing
ctx.drawImage(img, 0, 0, img.width * 0.5, img.height * 0.5);
canvas.toBlob(blob => {
newFile = blob;
console.log(newFile)
resolve();
});
// Show resized image in preview element
//var dataurl = canvas.toDataURL(file.type);
//document.getElementById("preview").src = dataurl;
}
})
await promise;
//var newFile = await new Promise(resolve => canvas.toBlob(resolve));
document.getElementById("preview").src = URL.createObjectURL(newFile); //check
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
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/u0P//fj/2I////z/+/H/qQ//2KD/u07/2pz/9+j/vlj/0X3/0Iz/rAD/5Lv/3p//7Mj/9OD/8Nb/68v/367/897/9uj/58H/7tL/sTD/1pX/xWz/xWL/tDf/3Kf/zX7/rx//ynb/sjr/3Kz/uEj/ty7/syH/wF7/4bb/rif/wFD/48D/vD//y4T/xXX/1Zr/xFj/0oP/t1H/xXv/y4X/qh//3rT/zXD/wGj/vkikmGS4AAARK0lEQVR4nNWdeWOiPBPAYYIiULUVq3jjbT27PffdPt1+/2/1Al6JBCQxAXb+tAr5NclkjmSiqLLFMHRdN/vtx9JeKo+Tdq/fNHVfDEP6+xWJzzbMbrM/+RwV1xoKC1j26nlYa/ebXVOX2ApZhGan/+tp+mMHLAAKRbyPwf+zXRy+/2o5BUktkULY7D29lmeaz0ZDC5F6X7SLb091x5TQGOGEemvyZzPQksERmDArv7nbqugGCSZsfG4WVsSoTEAJ2u73dCu2J0USNkvLL40X70SpfC2+6wJVjzBC8/EFWIdmZFci+7spah0RQ2j2v72ZJ4DuRInQ87YrpCcFEBqd7UgsXyA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m9pTj6tWWLxIIFT3F8y8D1/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).
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 have an image like this
<img id='my_img' src='www.someimage.com'>
And I have created this function to take the IMG node and convert it to a canvas and the base 64 data
function getBase64Image(img) {
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
var dataURL = canvas.toDataURL("image/png");
return dataURL.replace(/^data:image\/(png|jpg|jpeg|pdf);base64,/, "");
}
The function is called like
getBase64Image(document.getElementById("my_img"));
But when I send a image, it just returns an image that is cliped, it only returns the top left corner of the image here is what it returns for this image
iVBORw0KGgoAAAANSUhEUgAAAHgAAABgCAYAAADW4bYkAAASd0lEQVR4Xu2dCXgUVbbH/9XVne4mAUJYwuIAsgiDjo5KEMKWsPjYQUTG94QnME9BlhF0UIgiCAg4DAiIjEF2cGEfUFCGsIgyKLjNhEWBRE1ITAIJ2Xurrn7vVOc2N0Ulqfjsb7qZyvf1V9W13L51fvd/zrmnKt2Cz+fzgftTvQX/nq3LssyfYqyHsAUEHjABpJcgCCCIbEn9p+20jR3DtoXwtRldA6AAVoMlyzCYVS150IYlQ9cCCmCmVl6ltE2SpIByvV4v6EXbtZRMajf+Qs8CgizLSgxmiuQhejweBSq9CLYWZHauATj04FKPFMC8IgkiA+t2u5V1gssv6RgaELQ0AIcmWNYrwev1BgAzuASUXg6HAwSZlvQiyC6XS3HRTOnqrDu0L/ffr3cBwMwNM4gEtrS0FNevX0d+fj5KSkqQmpqqrLNYzZT/72e20LhiPWGxEmCCSsollTqdThQUFODKlStIT09HcnIy2rdvj1GjRin7f+k/Nj37pdv9/7T3r+oTgfs5nlGrv4IkSYqLJrAEmOCVl5crLpngkmo3b96MVatWoUmTJsr+6jrAkjWTyXRTfGYjjnWeH4FVXZDWsdXNwbUKM1qQqxr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aKwQbg8IGry0XTT9slJCQEkqycnBxDwWHEuEYFM8DsZgMp2JgHhw9hXYATExMrKdgAfAsCZgomF20AvsUA9+nTJzAPNgCHD1zdSVbfvn0DLjo7O9tQcBgxrjEG0zSJB5yVlWUAvlUB22w2ZGZmGtOkWw0wTZVYLZoUPHjwYOOJjjCBrMtFk5tmD76Tgg3AYUJXzxMdBHfAgAEBwBkZGRg0aJCh4DBhrEvBBuAwoanRTV2A6feCWQw2FBxesGsETAkWuWR2u/D77783YnAYMdYFmEqT7JksA3AY0f2/rv4vUC/Zt+yEWrkAAAAASUVORK5CYII=
And this is the image
Why is the image that is returned being clipped?
I think that promises are useful in situations like these:
function getBase64Image(url) {
var promise = new Promise(function(resolve, reject) {
var img = new Image();
// To prevent: "Uncaught SecurityError: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported."
img.crossOrigin = "Anonymous";
img.onload = function() {
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
var dataURL = canvas.toDataURL("image/png");
resolve(dataURL.replace(/^data:image\/(png|jpg|jpeg|pdf);base64,/, ""));
};
img.src = url;
});
return promise;
};
// CORS (Cross-Origin Resource Sharing) is enabled for Facebook images; but that's not true for
// all images out there!
var url = "https://scontent.xx.fbcdn.net/hphotos-xfp1/v/t1.0-9/12294845_10153267425828951_7985428593018522641_n.jpg?oh=2bb55736fce035311c3d60a1ca559426&oe=57210504";
var promise = getBase64Image(url);
promise.then(function (dataURL) {
console.log(dataURL);
});
https://jsfiddle.net/5tjov243/2/
Resources:
https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image
https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_settings_attributes
Make sure you are doing this after the image is fully loaded, and I don't know why you are doing the regex at the end, it works fine for me without it.
img.onload = function() {
res = getBase64Image(img);
document.getElementById('result').src = res;
};
http://jsfiddle.net/z0phwzea/1/
Of course you will need to try the fiddle out on your own computer as it won't work with an external resource.