I'm trying to fix Canvas Resize (Downscale) Image, I got jsfiddle http://jsfiddle.net/EWupT/ for image resizing. i have html input field when user upload instantly image show on input field, When adding resize code on my exiting code i got an error. any help greatly appreciated.
My JS:
$(document).ready(function() {
var readURL = function(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
canvas.width=300;
canvas.height=234;
ctx.drawImage(reader, 0, 0, 300, 234);
$('.profile-pic').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$(".file-upload").on('change', function(){
readURL(this);
});
$(".upload-button").on('click', function() {
$(".file-upload").click();
});
});
My HTML:
<div class="upload-button" id="imageresize"><img class="profile-pic" src="../images/add-image.png" /></div>
<input id="formFile" id="avatar-2" class="file-upload" type="file" name="my_file" accept="image/*">
I got this error:
Uncaught TypeError: Failed to execute 'drawImage' on 'CanvasRenderingContext2D': The provided value is not of type '(CSSImageValue or HTMLCanvasElement or HTMLImageElement or HTMLVideoElement or ImageBitmap or OffscreenCanvas or SVGImageElement or VideoFrame)'.
at FileReader.reader.onload
Added filereader.onload function, inside we can use resize code.
Updated code:
$(".upload-button").on('click', function() {
$(".file-upload").click();
});
var fileReader = new FileReader();
fileReader.onload = function(event) {
var image = new Image();
image.onload = function() {
var canvas = document.createElement("canvas");
var context = canvas.getContext("2d");
canvas.width = 500;
canvas.height = 380;
//canvas.height=image.height/1;
$('#upload-preview').width(500); //pixels
var hRatio = canvas.width / image.width;
var vRatio = canvas.height / image.height;
var ratio = Math.min(hRatio, vRatio);
context.drawImage(image, 0, 0, image.width, image.height, 0, 0,
image.width * ratio, image.height * ratio
);
document.getElementById("upload-preview").src = canvas.toDataURL();
}
image.src = event.target.result;
};
var uploadImage = function() {
var uploadImage = document.getElementById("upload-Image");
if (uploadImage.files.length === 0) {
return;
}
var uploadFile = document.getElementById("upload-Image").files[0];
fileReader.readAsDataURL(uploadFile);
}
Since you are using the new Image() function and generating a HTMLImageElement object dynamically, add img.src after the onload function like so:
img = new Image();
img.onload = function(){
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
canvas.width=300
canvas.height=234
ctx.drawImage(img, 0, 0, 300, 234);
document.body.appendChild(canvas);
};
img.src = 'http://i.imgur.com/SHo6Fub.jpg';
<img src="http://i.imgur.com/SHo6Fub.jpg" width="300" height="234">