JavaScript How to get an image width and height from an XMLHttpRequest - javascript

I'm switching an implementation of a cross-site request for an image converted to base 64 from Canvas to XMLHttpRequest and FileReader, so that it can be used inside of web workers. And I want to know if there's a way to get the image width and height from the get-go.
The new function
var convertFileToDataURLviaFileReader = function (url, callback) {
var xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.onload = function () {
var reader = new FileReader();
reader.onloadend = function () {
callback(reader.result);
}
reader.readAsDataURL(xhr.response);
};
// Our workaround for the Amazon CORS issue
// Replace HTTPs URL with HTTP
xhr.open('GET', url.replace(/^https:\/\//i, 'http://'));
xhr.send();
}
Our old Function
var convertImgToDataURLviaCanvas = function(url, callback, outputFormat) {
var img = new Image();
img.crossOrigin = 'Anonymous';
img.onload = function () {
var canvas = document.createElement('CANVAS');
var ctx = canvas.getContext('2d');
var dataURL;
canvas.height = this.height;
canvas.width = this.width;
ctx.drawImage(this, 0, 0);
dataURL = canvas.toDataURL(outputFormat);
var allInfo = {
data: dataURL,
width: this.width,
height: this.height
}
// Add height and width to callback
callback(allInfo);
canvas = null;
};
// Our workaround for the Amazon CORS issue
// Replace HTTPs URL with HTTP
img.src = url.replace(/^https:\/\//i, 'http://');
}
In the old function I can just get the height and width with canvas, and I do so inside of the var allInfo. Is there an equivalent for FileReader or some way to get the width and height inside of the new function?
To clarify, I am switching to the XMLHttpRequest because Web Workers don't have access to the DOM, so Canvas can't be used.

Have a look at this code, it's just a quick rework of this example https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL
Is your reader.result a string in base 64 encoding ?
<form>
<input type="file" onchange="previewFile()"><br>
<img src="" alt="Image preview..."><!-- height and width are not set -->
</form>
<script>
var previewFile = () => {
"use strict";
let file = document.querySelector("input[type=file]").files[0];
let fileReader = new FileReader();
let preview = document.querySelector("img")
fileReader.addEventListener("load", () => {
preview.src = fileReader.result;
// here preview.height and preview.width are accessible
// if height and width are not set in the img element in the html
});
if (file) {
fileReader.readAsDataURL(file);
}
};
</script>

Related

Convert Image uri into Base64 [duplicate]

Using an Image File, I am getting the url of an image, that needs be to send to a webservice. From there the image has to be saved locally on my system.
The code I am using:
var imagepath = $("#imageid").val();// from this getting the path of the selected image
that var st = imagepath.replace(data:image/png or jpg; base64"/"");
How to convert the image url to BASE64?
HTML
<img id="imageid" src="https://www.google.de/images/srpr/logo11w.png">
JavaScript
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\/?[A-z]*;base64,/);
}
var base64 = getBase64Image(document.getElementById("imageid"));
Special thanks to #Md. Hasan Mahmud for providing an improved regex that works with any image mime type in my comments!
This method requires the canvas element, which is perfectly supported.
The MDN reference of HTMLCanvasElement.toDataURL().
And the official W3C documentation.
View this answer: https://stackoverflow.com/a/20285053/5065874 by #HaNdTriX
Basically, he implemented this function:
function toDataUrl(url, callback) {
var xhr = new XMLHttpRequest();
xhr.onload = function() {
var reader = new FileReader();
reader.onloadend = function() {
callback(reader.result);
}
reader.readAsDataURL(xhr.response);
};
xhr.open('GET', url);
xhr.responseType = 'blob';
xhr.send();
}
And in your case, you can use it like this:
toDataUrl(imagepath, function(myBase64) {
console.log(myBase64); // myBase64 is the base64 string
});
In todays JavaScript, this will work as well..
const getBase64FromUrl = async (url) => {
const data = await fetch(url);
const blob = await data.blob();
return new Promise((resolve) => {
const reader = new FileReader();
reader.readAsDataURL(blob);
reader.onloadend = () => {
const base64data = reader.result;
resolve(base64data);
}
});
}
getBase64FromUrl('https://lh3.googleusercontent.com/i7cTyGnCwLIJhT1t2YpLW-zHt8ZKalgQiqfrYnZQl975-ygD_0mOXaYZMzekfKW_ydHRutDbNzeqpWoLkFR4Yx2Z2bgNj2XskKJrfw8').then(console.log)
This is your html-
<img id="imageid" src="">
<canvas id="imgCanvas" />
Javascript should be-
var can = document.getElementById("imgCanvas");
var img = document.getElementById("imageid");
var ctx = can.getContext("2d");
ctx.drawImage(img, 10, 10);
var encodedBase = can.toDataURL();
'encodedBase' Contains Base64 Encoding of Image.
You Can Used This :
function ViewImage(){
function getBase64(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result);
reader.onerror = error => reject(error);
});
}
var file = document.querySelector('input[type="file"]').files[0];
getBase64(file).then(data =>$("#ImageBase46").val(data));
}
Add To Your Input onchange=ViewImage();
I try using the top answer, but it occur Uncaught DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.
I found this is because of cross domain problems, the solution is
function convert(oldImag, callback) {
var img = new Image();
img.onload = function(){
callback(img)
}
img.setAttribute('crossorigin', 'anonymous');
img.src = oldImag.src;
}
function getBase64Image(img,callback) {
convert(img, function(newImg){
var canvas = document.createElement("canvas");
canvas.width = newImg.width;
canvas.height = newImg.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(newImg, 0, 0);
var base64=canvas.toDataURL("image/png");
callback(base64)
})
}
getBase64Image(document.getElementById("imageid"),function(base64){
// base64 in here.
console.log(base64)
});
<input id="inputFileToLoad" type="file" onchange="encodeImageFileAsURL();" />
<div id="imgTest"></div>
<script type='text/javascript'>
function encodeImageFileAsURL() {
var filesSelected = document.getElementById("inputFileToLoad").files;
if (filesSelected.length > 0) {
var fileToLoad = filesSelected[0];
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent) {
var srcData = fileLoadedEvent.target.result; // <--- data: base64
var newImage = document.createElement('img');
newImage.src = srcData;
document.getElementById("imgTest").innerHTML = newImage.outerHTML;
alert("Converted Base64 version is " + document.getElementById("imgTest").innerHTML);
console.log("Converted Base64 version is " + document.getElementById("imgTest").innerHTML);
}
fileReader.readAsDataURL(fileToLoad);
}
}
</script>
let baseImage = new Image;
baseImage.setAttribute('crossOrigin', 'anonymous');
baseImage.src = your image url
var canvas = document.createElement("canvas");
canvas.width = baseImage.width;
canvas.height = baseImage.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(baseImage, 0, 0);
var dataURL = canvas.toDataURL("image/png");
Additional information about "CORS enabled images": MDN Documentation
imageToBase64 = (URL) => {
let image;
image = new Image();
image.crossOrigin = 'Anonymous';
image.addEventListener('load', function() {
let canvas = document.createElement('canvas');
let context = canvas.getContext('2d');
canvas.width = image.width;
canvas.height = image.height;
context.drawImage(image, 0, 0);
try {
localStorage.setItem('saved-image-example', canvas.toDataURL('image/png'));
} catch (err) {
console.error(err)
}
});
image.src = URL;
};
imageToBase64('image URL')
Here's the Typescript version of Abubakar Ahmad's answer
function imageTo64(
url: string,
callback: (path64: string | ArrayBuffer) => void
): void {
const xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.responseType = 'blob';
xhr.send();
xhr.onload = (): void => {
const reader = new FileReader();
reader.readAsDataURL(xhr.response);
reader.onloadend = (): void => callback(reader.result);
}
}
Just wanted to chime in and post how I did it. This is basically #Haialaluf's approach but a bit shorter:
const imageUrlToBase64 = async (url) => {
const data = await fetch(url)
const blob = await data.blob();
const reader = new FileReader();
reader.readAsDataURL(blob);
reader.onload = () => {
const base64data = reader.result;
return base64data
}
}

How to make client side image resize function reusable

HTML Template
<html>
<form>
Image to resize: <input type="file" id="getImage"><br><br>
</form>
<img src="." id="image">
<html>
Java Script
<script>
document.getElementById('getImage').onchange = imageResize(60,60);
var imageResize = function (Width, Height) {
//-- GET FILE FROM FORM
var selectedFile = this.files[0];
//-- GET BASE 64
File.prototype.convertToBase64 = function (callback) {
var reader = new FileReader();
reader.onload = function (e) {
callback(e.target.result);
};
reader.readAsDataURL(this);
};
selectedFile.convertToBase64(function (base64) {
//-- MAKE IMAGE
var img = document.createElement('img');
img.src = base64;
//-- PUSH INTO CANVAS
img.onload = function () {
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
canvas.width = Width; // If i change Width & Height to numbers it works!!
canvas.height = Height;
ctx.drawImage(this, 0, 0, Width, Height);
//-- SHOW IMAGE ON PAGE
document.getElementById("image").src = canvas.toDataURL();
};
});
};
</script>
Just above I'm setting the canvas width and height to 60x60 but i cant use the variables I've passed in without getting an error, and I cant figure out why. the error is
Uncaught TypeError: Cannot read property 'files' of undefined
here you should attach the event listener to input element.but instead you attached to img element
and you also want to access the files inside the event listener,so you should pass this reference to the listener
and the way you are attaching the event is not right.
your are doing this document.getElementById('getImage').onchange = imageResize(60,60);
this is wrong as it will execute the imageResize() and assigns the result to on change event.
actually you should attach reference of the function like below
document.getElementById('getImage').onchange = imageResize;
i edited your code a little.
try this snippet.
var imageResize = function(Width, Height, files) {
var selectedFile = files[0];
File.prototype.convertToBase64 = function(callback) {
var reader = new FileReader();
reader.onload = function(e) {
callback(e.target.result);
};
reader.readAsDataURL(this);
};
selectedFile.convertToBase64(function(base64) {
var img = document.createElement('img');
img.src = base64;
img.onload = function() {
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
canvas.width = Width;
canvas.height = Height;
ctx.drawImage(this, 0, 0, Width, Height);
document.getElementById("image").src = canvas.toDataURL();
};
});
};
var file = document.getElementById('getImage');
file.onchange = function() {
imageResize(160, 160, this.files);
};
<form>
Image to resize:
<input type="file" id="getImage">
<br>
<br>
</form>
<img src="." id="image">

Canvas drawImage is not accepting width and height

Image is getting created in full original size, even last two arguments 150, 150 are height and width context.drawImage(img, 0, 0, 150, 150); in the code below:
function (file) { //uploaded files are always images
var reader = new FileReader(); //FileReader for uploading files from local stroge.
reader.onload = function () {
var links = document.createElement('a'); //link when image is clicked
var img = document.createElement('img');
img.src = reader.result; //src = url from uploaded file
img.className = 'images'; //css -> .images { margin-top: 30px; padding: 30px; }
img.onload = function () { //repaint image to 150 - 150 size with canvas, because setting width and height on image itself would just resize the image but I want to create new image with new size
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
context.drawImage(img, 0, 0, 150, 150) //draw image with canvas
}
links.href = reader.result; // url from local storage needed when image is clicked -
links.target = "_blank"; // open new blank page with original image
links.appendChild(img); // image is appended to <a>
document.body.appendChild(links); // <a> is appended to body, that body contains image thumbnail with a link linked to the image source
}
if (file) {
reader.readAsDataURL(file); // read uploaded files url
}
}
img.onload does not making any sense here. result is the same even when I remove it.
You are not drawing back the cropped image to your <img> tag... you will have to create two image Objects, let's call the first originalImage, and the second one croppedImage.
The one you will append to the document is croppedImageand originalImage will just stay in the cache.
When originalImage has loaded, you will paint it to a canvas, and then set croppedImage to the result of the canvas' toDataURL() method.
var read = function() {
var file = this.files[0];
var reader = new FileReader();
reader.onload = function() {
var links = document.createElement('a');
// this will be the appended image
var croppedImage = new Image();
// do your DOM stuff
croppedImage.className = 'images';
links.href = reader.result;
links.target = "_blank";
links.appendChild(croppedImage);
document.body.appendChild(links);
// create a buffer image object
var originalImage = new Image();
// set its load handler
originalImage.onload = function() {
// create a canvas
var canvas = document.createElement('canvas');
// set canvas width/height
canvas.width = canvas.height = 150;
var context = canvas.getContext('2d');
// draw the buffered image to the canvas at required dimension
context.drawImage(originalImage, 0, 0, 150, 150);
// set the appended to doc image's src to the result of the cropping operation
croppedImage.src = canvas.toDataURL();
}
originalImage.src = reader.result;
}
if (file) {
reader.readAsDataURL(file);
}
};
upload.onchange = read;
.images {
margin-top: 30px;
padding: 30px;
}
<input type="file" id="upload" />
You could also have used only a single image object, but this would have required to reset the onload event in the onload event, to avoid an infinite loop, which is a little bit less clear :
var read = function() {
var file = this.files[0];
var reader = new FileReader();
reader.onload = function() {
var links = document.createElement('a');
var img = new Image();
img.className = 'images';
links.href = reader.result;
links.target = "_blank";
links.appendChild(img);
document.body.appendChild(links);
img.onload = function() {
//reset the onload event so it does fire in a loop
img.onload = function(){return;};
var canvas = document.createElement('canvas');
canvas.width = canvas.height = 150;
var context = canvas.getContext('2d');
context.drawImage(this, 0, 0, 150, 150);
this.src = canvas.toDataURL();
}
img.src = reader.result;
}
if (file) {
reader.readAsDataURL(file);
}
};
upload.onchange = read;
.images {
margin-top: 30px;
padding: 30px;
}
<input type="file" id="upload" />
var reader = new FileReader();
reader.onload = function () {
var links = document.createElement('a');
var img = new Image();
img.src = reader.result;
img.className = 'images';
img.onload = function () {
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
context.drawImage(this, 0, 0, 150, 150);
this.src = canvas.toDataURL(); // convert the canvas back to the image
links.appendChild(this); // append the updated image to the document
}
links.href = reader.result;
links.target = "_blank";
document.body.appendChild(links);
}
if (file) {
reader.readAsDataURL(file); //reads the data as a URL
}

Convert image from url to Base64

Using an Image File, I am getting the url of an image, that needs be to send to a webservice. From there the image has to be saved locally on my system.
The code I am using:
var imagepath = $("#imageid").val();// from this getting the path of the selected image
that var st = imagepath.replace(data:image/png or jpg; base64"/"");
How to convert the image url to BASE64?
HTML
<img id="imageid" src="https://www.google.de/images/srpr/logo11w.png">
JavaScript
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\/?[A-z]*;base64,/);
}
var base64 = getBase64Image(document.getElementById("imageid"));
Special thanks to #Md. Hasan Mahmud for providing an improved regex that works with any image mime type in my comments!
This method requires the canvas element, which is perfectly supported.
The MDN reference of HTMLCanvasElement.toDataURL().
And the official W3C documentation.
View this answer: https://stackoverflow.com/a/20285053/5065874 by #HaNdTriX
Basically, he implemented this function:
function toDataUrl(url, callback) {
var xhr = new XMLHttpRequest();
xhr.onload = function() {
var reader = new FileReader();
reader.onloadend = function() {
callback(reader.result);
}
reader.readAsDataURL(xhr.response);
};
xhr.open('GET', url);
xhr.responseType = 'blob';
xhr.send();
}
And in your case, you can use it like this:
toDataUrl(imagepath, function(myBase64) {
console.log(myBase64); // myBase64 is the base64 string
});
In todays JavaScript, this will work as well..
const getBase64FromUrl = async (url) => {
const data = await fetch(url);
const blob = await data.blob();
return new Promise((resolve) => {
const reader = new FileReader();
reader.readAsDataURL(blob);
reader.onloadend = () => {
const base64data = reader.result;
resolve(base64data);
}
});
}
getBase64FromUrl('https://lh3.googleusercontent.com/i7cTyGnCwLIJhT1t2YpLW-zHt8ZKalgQiqfrYnZQl975-ygD_0mOXaYZMzekfKW_ydHRutDbNzeqpWoLkFR4Yx2Z2bgNj2XskKJrfw8').then(console.log)
This is your html-
<img id="imageid" src="">
<canvas id="imgCanvas" />
Javascript should be-
var can = document.getElementById("imgCanvas");
var img = document.getElementById("imageid");
var ctx = can.getContext("2d");
ctx.drawImage(img, 10, 10);
var encodedBase = can.toDataURL();
'encodedBase' Contains Base64 Encoding of Image.
You Can Used This :
function ViewImage(){
function getBase64(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result);
reader.onerror = error => reject(error);
});
}
var file = document.querySelector('input[type="file"]').files[0];
getBase64(file).then(data =>$("#ImageBase46").val(data));
}
Add To Your Input onchange=ViewImage();
I try using the top answer, but it occur Uncaught DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.
I found this is because of cross domain problems, the solution is
function convert(oldImag, callback) {
var img = new Image();
img.onload = function(){
callback(img)
}
img.setAttribute('crossorigin', 'anonymous');
img.src = oldImag.src;
}
function getBase64Image(img,callback) {
convert(img, function(newImg){
var canvas = document.createElement("canvas");
canvas.width = newImg.width;
canvas.height = newImg.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(newImg, 0, 0);
var base64=canvas.toDataURL("image/png");
callback(base64)
})
}
getBase64Image(document.getElementById("imageid"),function(base64){
// base64 in here.
console.log(base64)
});
<input id="inputFileToLoad" type="file" onchange="encodeImageFileAsURL();" />
<div id="imgTest"></div>
<script type='text/javascript'>
function encodeImageFileAsURL() {
var filesSelected = document.getElementById("inputFileToLoad").files;
if (filesSelected.length > 0) {
var fileToLoad = filesSelected[0];
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent) {
var srcData = fileLoadedEvent.target.result; // <--- data: base64
var newImage = document.createElement('img');
newImage.src = srcData;
document.getElementById("imgTest").innerHTML = newImage.outerHTML;
alert("Converted Base64 version is " + document.getElementById("imgTest").innerHTML);
console.log("Converted Base64 version is " + document.getElementById("imgTest").innerHTML);
}
fileReader.readAsDataURL(fileToLoad);
}
}
</script>
let baseImage = new Image;
baseImage.setAttribute('crossOrigin', 'anonymous');
baseImage.src = your image url
var canvas = document.createElement("canvas");
canvas.width = baseImage.width;
canvas.height = baseImage.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(baseImage, 0, 0);
var dataURL = canvas.toDataURL("image/png");
Additional information about "CORS enabled images": MDN Documentation
imageToBase64 = (URL) => {
let image;
image = new Image();
image.crossOrigin = 'Anonymous';
image.addEventListener('load', function() {
let canvas = document.createElement('canvas');
let context = canvas.getContext('2d');
canvas.width = image.width;
canvas.height = image.height;
context.drawImage(image, 0, 0);
try {
localStorage.setItem('saved-image-example', canvas.toDataURL('image/png'));
} catch (err) {
console.error(err)
}
});
image.src = URL;
};
imageToBase64('image URL')
Here's the Typescript version of Abubakar Ahmad's answer
function imageTo64(
url: string,
callback: (path64: string | ArrayBuffer) => void
): void {
const xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.responseType = 'blob';
xhr.send();
xhr.onload = (): void => {
const reader = new FileReader();
reader.readAsDataURL(xhr.response);
reader.onloadend = (): void => callback(reader.result);
}
}
Just wanted to chime in and post how I did it. This is basically #Haialaluf's approach but a bit shorter:
const imageUrlToBase64 = async (url) => {
const data = await fetch(url)
const blob = await data.blob();
const reader = new FileReader();
reader.readAsDataURL(blob);
reader.onload = () => {
const base64data = reader.result;
return base64data
}
}

How can I draw an image from the HTML5 File API on Canvas?

I would like to draw an image opened with the HTML5 File API on a canvas.
In the handleFiles(e) method, I can access the File with e.target.files[0] but I can't draw that image directly using drawImage. How do I draw an image from the File API on HTML5 canvas?
Here is the code I have used:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<script>
window.onload = function() {
var input = document.getElementById('input');
input.addEventListener('change', handleFiles);
}
function handleFiles(e) {
var ctx = document.getElementById('canvas').getContext('2d');
ctx.drawImage(e.target.files[0], 20,20);
alert('the image is drawn');
}
</script>
</head>
<body>
<h1>Test</h1>
<input type="file" id="input"/>
<canvas width="400" height="300" id="canvas"/>
</body>
</html>
You have a File instance which is not an image.
To get an image, use new Image(). The src needs to be an URL referencing to the selected File. You can use URL.createObjectURL to get an URL referencing to a Blob (a File is also a Blob): http://jsfiddle.net/t7mv6/86/.
var ctx = document.getElementById('canvas').getContext('2d');
var img = new Image;
img.onload = function() {
ctx.drawImage(img, 20,20);
alert('the image is drawn');
}
img.src = URL.createObjectURL(e.target.files[0]);
Note: be sure to revoke the object url when you are done with it otherwise you'll leak memory. If you're not doing anything too crazy, you can just stick a URL.revokeObjectURL(img.src) in the img.onload function.
References:
https://developer.mozilla.org/en/DOM/File
http://html5demos.com/file-api
Live Example
function handleFiles(e) {
var ctx = document.getElementById('canvas').getContext('2d');
var url = URL.createObjectURL(e.target.files[0]);
var img = new Image();
img.onload = function() {
ctx.drawImage(img, 20, 20);
}
img.src = url;
}
window.URL.createObjectUrldocs
You could also use the FileReader instead to create the object URL.
The FileReader has slightly better browser support.
The FileReader approach works in FF6 / Chrome. I'm not certain whether setting Img.src to a Blob is valid and cross-browser though.
Creating object urls is the correct way to do it.
Edit:
As mentioned in the commment window.URL support whilst offline seems unavailable in FF6/Chrome.
Here is a complete example (Fiddle) using FileReader (which has better browser support as mentioned by Raynos). In this example I also scale Canvas to fit the image.
In real life example you might scale the image to some maximum so that your form will not blow up ;-). Here is an example with scaling (Fiddle).
var URL = window.webkitURL || window.URL;
window.onload = function() {
var input = document.getElementById('input');
input.addEventListener('change', handleFiles, false);
// set original canvas dimensions as max
var canvas = document.getElementById('canvas');
canvas.dataMaxWidth = canvas.width;
canvas.dataMaxHeight = canvas.height;
}
function handleFiles(e) {
var ctx = document.getElementById('canvas').getContext('2d');
var reader = new FileReader();
var file = e.target.files[0];
// load to image to get it's width/height
var img = new Image();
img.onload = function() {
// setup scaled dimensions
var scaled = getScaledDim(img, ctx.canvas.dataMaxWidth, ctx.canvas.dataMaxHeight);
// scale canvas to image
ctx.canvas.width = scaled.width;
ctx.canvas.height = scaled.height;
// draw image
ctx.drawImage(img, 0, 0
, ctx.canvas.width, ctx.canvas.height
);
}
// this is to setup loading the image
reader.onloadend = function () {
img.src = reader.result;
}
// this is to read the file
reader.readAsDataURL(file);
}
// returns scaled dimensions object
function getScaledDim(img, maxWidth, maxHeight) {
var scaled = {
ratio: img.width / img.height,
width: img.width,
height: img.height
}
if (scaled.width > maxWidth) {
scaled.width = maxWidth;
scaled.height = scaled.width / scaled.ratio;
}
if (scaled.height > maxHeight) {
scaled.height = maxHeight;
scaled.width = scaled.height / scaled.ratio;
}
return scaled;
}
canvas {
border:1px solid black
}
<input type="file" id="input"/>
<div>
<canvas width="400" height="300" id="canvas"/>
</div>

Categories