Save converted binary code in local storage of browser - javascript

I have a php file "linkToThePhpFileHere.php". It creates a QR Code and returns something like that:
https://i.stack.imgur.com/y7zHA.png
That's how I display the code:
<div style="background-image: url(linkToThePhpFileHere.php);"></div>
But I want to store the content of "linkToThePhpFileHere.php" in an array in the local storage of the browser and I think, it's not a good idea to save the binary code there?
Is it possible to use Javascript/Jquery to load and convert the cotent of my file. It should look like this: https://i.stack.imgur.com/soYPr.png and be saved in a var:
var str = convertToSth($.get("linkToThePhpFileHere.php"));

var str = convertToSth($.get("linkToThePhpFileHere.php"));//this should be in base64
localStorage.setItem("imgData", str );
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);base64,/, "");
}
function getImage(imageUrl, callback) {
var img = document.createElement("img");
img.setAttribute('crossOrigin', 'anonymous');
img.src = imageUrl;
img.onload = function() {
var str = getBase64Image(img);
if (typeof callback == "function") callback(str);
}
}
getImage('https://upload.wikimedia.org/wikipedia/commons/f/f9/Phoenicopterus_ruber_in_S%C3%A3o_Paulo_Zoo.jpg',function(imgData){
localStorage.setItem("imgData1", str );
})
getImage('linkToThePhpFileHere.php',function(imgData){
localStorage.setItem("imgData1", str );
})

You can store data URI representation of image in localStorage
window.onload = () => {
if (localStorage.getItem("image") === null) {
fetch("linkToThePhpFileHere.php")
.then(response => reponse.blob())
.then(blob => {
const reader = new FileReader;
reader.onload = () {
localStorage.setItem("image", reader.result);
document.querySelector("div")
.style.backgroundImage = "url(" + reader.result + ");";
}
reader.readAsDataURL(blob)
})
} else {
document.querySelector("div")
.style.backgroundImage = "url(" + localStorage.getImage("image") + ")";
}
}

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
}
}

Why img.onload() function not working on ipad for exporting my chart data in pdf format?

I am trying to export my chart data consisting of image and data in a PDF. It works fine for me in laptop browser, but while I am trying to do the same in Ipad, the img.onload() function is not firing. I am not sure but I feel like it is due to the size of the image that is rendering in it. Can anybody help me with it? Can we change the pixels of the image that is being rendered?
The code is given below:-
function exportData(exportType) {
if (exportType) {
if (exportType == "pdf") {
alert("clicked pdf")
console.log("pdf export ....")
vm.toggleCanvas = !vm.toggleCanvas;
var canvas = "";
var ctxt = "";
// var img = "";
var sheets = "";
var svgURL = "";
canvas = document.getElementById('canvas');
$log.log($window.screen.width)
//resizing image for PDF
if ($window.screen.width >= 1500) {
canvas.width = $window.screen.width - 150;
} else {
canvas.width = $window.screen.width;
}
console.log("before canvas")
ctxt = canvas.getContext('2d');
sheets = document.styleSheets;
svgURL = generateSVGWithStyling('svg');
// var img = document.createElement('img');
var img = new Image();
console.log("after image")
console.log(img)
alert("imb")
img.src = 'data:image/svg+xml; charset=utf8, ' + encodeURIComponent(svgURL);
img.onload = function () {
debugger
console.log("in load")
alert("in load")
ctxt.drawImage(this, 0, 0);
vm.cnvasImg = "";
vm.cnvasImg = canvas.toDataURL();
var content = "";
console.log("on load")
subExportData(vm.cnvasImg, exportType);
}
console.log(img.src)
} else {
vm.cnvasImg = "nothing";
subExportData(vm.cnvasImg, exportType);
}
}
}
Any help would be apprciated.
Can you please try with passing the width, height properties to Image constructor Object.
var img = new Image(Width, Height);

Blob export not working in safari

I want to export the jpeg image from svg using blob. This working fine in chrome. But, my sample is not working safari browser(MAC).
Can you please tell how to resolve this? wheather blob is support in IOS or not?
while run this sample in ios thrown image load error.
Sample Link: http://jsfiddle.net/kyjs655r/363/
document.getElementById('export').onclick = function () {
var tag = document.getElementById('export');
tag.download = 'Sample' + "." + 'png';
tag.href = getCanvaElement().toDataURL();
}
function getCanvaElement() {
var svgText = document.getElementById("myViewer").outerHTML;
var svg = new Blob([svgText], { type: "image/svg+xml;charset=utf-8" });
var domURL = self.URL || self.webkitURL || self;
var url = domURL.createObjectURL(svg);
var element = document.createElement('canvas');
var ctx = element.getContext("2d");
var image = new Image;
image.onload = function () {
ctx.drawImage(this, 0, 0);
domURL.revokeObjectURL(url);
};
image.onerror = function () {
alert();
};
image.src = url;
return element;
}

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
}
}

Check image width and height before upload with Javascript

I have a JPS with a form in which a user can put an image:
<div class="photo">
<div>Photo (max 240x240 and 100 kb):</div>
<input type="file" name="photo" id="photoInput" onchange="checkPhoto(this)"/>
</div>
I have written this js:
function checkPhoto(target) {
if(target.files[0].type.indexOf("image") == -1) {
document.getElementById("photoLabel").innerHTML = "File not supported";
return false;
}
if(target.files[0].size > 102400) {
document.getElementById("photoLabel").innerHTML = "Image too big (max 100kb)";
return false;
}
document.getElementById("photoLabel").innerHTML = "";
return true;
}
which works fine to check file type and size. Now I want to check image width and height but I cannot do it.
I have tried with target.files[0].width but I get undefined. With other ways I get 0.
Any suggestions?
The file is just a file, you need to create an image like so:
var _URL = window.URL || window.webkitURL;
$("#file").change(function (e) {
var file, img;
if ((file = this.files[0])) {
img = new Image();
var objectUrl = _URL.createObjectURL(file);
img.onload = function () {
alert(this.width + " " + this.height);
_URL.revokeObjectURL(objectUrl);
};
img.src = objectUrl;
}
});
Demo: http://jsfiddle.net/4N6D9/1/
I take it you realize this is only supported in a few browsers. Mostly firefox and chrome, could be opera as well by now.
P.S. The URL.createObjectURL() method has been removed from the MediaStream interface. This method has been deprecated in 2013 and superseded by assigning streams to HTMLMediaElement.srcObject. The old method was removed because it is less safe, requiring a call to URL.revokeOjbectURL() to end the stream. Other user agents have either deprecated (Firefox) or removed (Safari) this feature feature.
For more information, please refer here.
In my view the perfect answer you must required is
var reader = new FileReader();
//Read the contents of Image File.
reader.readAsDataURL(fileUpload.files[0]);
reader.onload = function (e) {
//Initiate the JavaScript Image object.
var image = new Image();
//Set the Base64 string return from FileReader as source.
image.src = e.target.result;
//Validate the File Height and Width.
image.onload = function () {
var height = this.height;
var width = this.width;
if (height > 100 || width > 100) {
alert("Height and Width must not exceed 100px.");
return false;
}
alert("Uploaded image has valid Height and Width.");
return true;
};
};
I agree. Once it is uploaded to somewhere the user's browser can access then it is pretty easy to get the size. As you need to wait for the image to load you'll want to hook into the onload event for img.
Updated example:
// async/promise function for retrieving image dimensions for a URL
function imageSize(url) {
const img = document.createElement("img");
const promise = new Promise((resolve, reject) => {
img.onload = () => {
// Natural size is the actual image size regardless of rendering.
// The 'normal' `width`/`height` are for the **rendered** size.
const width = img.naturalWidth;
const height = img.naturalHeight;
// Resolve promise with the width and height
resolve({width, height});
};
// Reject promise on error
img.onerror = reject;
});
// Setting the source makes it start downloading and eventually call `onload`
img.src = url;
return promise;
}
// How to use in an async function
(async() => {
const imageUrl = 'http://your.website.com/userUploadedImage.jpg';
const imageDimensions = await imageSize(imageUrl);
console.info(imageDimensions); // {width: 1337, height: 42}
})();
Older example:
var width, height;
var img = document.createElement("img");
img.onload = function() {
// `naturalWidth`/`naturalHeight` aren't supported on <IE9. Fallback to normal width/height
// The natural size is the actual image size regardless of rendering.
// The 'normal' width/height are for the **rendered** size.
width = img.naturalWidth || img.width;
height = img.naturalHeight || img.height;
// Do something with the width and height
}
// Setting the source makes it start downloading and eventually call `onload`
img.src = "http://your.website.com/userUploadedImage.jpg";
This is the easiest way to check the size
let img = new Image()
img.src = window.URL.createObjectURL(event.target.files[0])
img.onload = () => {
alert(img.width + " " + img.height);
}
Check for specific size. Using 100 x 100 as example
let img = new Image()
img.src = window.URL.createObjectURL(event.target.files[0])
img.onload = () => {
if(img.width === 100 && img.height === 100){
alert(`Nice, image is the right size. It can be uploaded`)
// upload logic here
} else {
alert(`Sorry, this image doesn't look like the size we wanted. It's
${img.width} x ${img.height} but we require 100 x 100 size image.`);
}
}
Attach the function to the onchange method of the input type file /onchange="validateimg(this)"/
function validateimg(ctrl) {
var fileUpload = ctrl;
var regex = new RegExp("([a-zA-Z0-9\s_\\.\-:])+(.jpg|.png|.gif)$");
if (regex.test(fileUpload.value.toLowerCase())) {
if (typeof (fileUpload.files) != "undefined") {
var reader = new FileReader();
reader.readAsDataURL(fileUpload.files[0]);
reader.onload = function (e) {
var image = new Image();
image.src = e.target.result;
image.onload = function () {
var height = this.height;
var width = this.width;
if (height < 1100 || width < 750) {
alert("At least you can upload a 1100*750 photo size.");
return false;
}else{
alert("Uploaded image has valid Height and Width.");
return true;
}
};
}
} else {
alert("This browser does not support HTML5.");
return false;
}
} else {
alert("Please select a valid Image file.");
return false;
}
}
const ValidateImg = (file) =>{
let img = new Image()
img.src = window.URL.createObjectURL(file)
img.onload = () => {
if(img.width === 100 && img.height ===100){
alert("Correct size");
return true;
}
alert("Incorrect size");
return true;
}
}
I think this may be the simplest for uploads if you want to use it other functions.
async function getImageDimensions(file) {
let img = new Image();
img.src = URL.createObjectURL(file);
await img.decode();
let width = img.width;
let height = img.height;
return {
width,
height,
}
}
Use like
const {width, height } = await getImageDimensions(file)
Suppose you were storing an image for Tiger taken in Kenya. So you could use it like to upload to cloud storage and then store photo information.
const addImage = async (file, title, location) => {
const { width, height } = await getImageDimensions(file)
const url = await uploadToCloudStorage(file) // returns storage url
await addToDatabase(url, width, height, title, location)
}
function validateimg(ctrl) {
var fileUpload = $("#txtPostImg")[0];
var regex = new RegExp("([a-zA-Z0-9\s_\\.\-:])+(.jpg|.png|.gif)$");
if (regex.test(fileUpload.value.toLowerCase())) {
if (typeof (fileUpload.files) != "undefined") {
var reader = new FileReader();
reader.readAsDataURL(fileUpload.files[0]);
reader.onload = function (e) {
var image = new Image();
image.src = e.target.result;
image.onload = function () {
var height = this.height;
var width = this.width;
console.log(this);
if ((height >= 1024 || height <= 1100) && (width >= 750 || width <= 800)) {
alert("Height and Width must not exceed 1100*800.");
return false;
}
alert("Uploaded image has valid Height and Width.");
return true;
};
}
} else {
alert("This browser does not support HTML5.");
return false;
}
} else {
alert("Please select a valid Image file.");
return false;
}
}
You can do the steps for previewing the image without showing it which is supported on all browsers. Following js code shows you how to check the width and height :
var file = e.target.files[0];
if (/\.(jpe?g|png|gif)$/i.test(file.name)) {
var reader = new FileReader();
reader.addEventListener("load", function () {
var image = new Image();
image.src = this.result as string;
image.addEventListener('load', function () {
console.log(`height: ${this.height}, width: ${this.width}`);
});
}, false);
reader.readAsDataURL(file);
}
Based on Mozilla docs:
The readAsDataURL method is used to read the contents of the specified
Blob or File. When the read operation is finished, the readyState
becomes DONE, and the loadend is triggered. At that time, the result
attribute contains the data as a data: URL representing the file's
data as a base64 encoded string.
And the browser compatibility is listed too.
In my case, I needed to also prevent the form from being submited, so here is the solution that worked for me.
The preventDefault will stop the form action, then we check the size and dimensions of the image in the onload function.
If all good, we allow the submit.
As the submit button gets disabled if a user still tries to submit the form with an invalid image, I also had to re-able the submit button once a valid image is inputted.
const validateMaxImageFileSize = (e) => {
e.preventDefault();
const el = $("input[type='file']")[0];
if (el.files && el.files[0]) {
const file = el.files[0];
const maxFileSize = 5242880; // 5 MB
const maxWidth = 1920;
const maxHeight = 1080;
const img = new Image();
img.src = window.URL.createObjectURL(file);
img.onload = () => {
if (file.type.match('image.*') && file.size > maxFileSize) {
alert('The selected image file is too big. Please choose one that is smaller than 5 MB.');
} else if (file.type.match('image.*') && (img.width > maxWidth || img.height > maxHeight)) {
alert(`The selected image is too big. Please choose one with maximum dimensions of ${maxWidth}x${maxHeight}.`);
} else {
e.target.nodeName === 'INPUT'
? (e.target.form.querySelector("input[type='submit']").disabled = false)
: e.target.submit();
}
};
}
};
$('form.validate-image-size').on('submit', validateMaxImageFileSize);
$("form.validate-image-size input[type='file']").on('change', validateMaxImageFileSize);
function uploadfile(ctrl) {
var validate = validateimg(ctrl);
if (validate) {
if (window.FormData !== undefined) {
ShowLoading();
var fileUpload = $(ctrl).get(0);
var files = fileUpload.files;
var fileData = new FormData();
for (var i = 0; i < files.length; i++) {
fileData.append(files[i].name, files[i]);
}
fileData.append('username', 'Wishes');
$.ajax({
url: 'UploadWishesFiles',
type: "POST",
contentType: false,
processData: false,
data: fileData,
success: function(result) {
var id = $(ctrl).attr('id');
$('#' + id.replace('txt', 'hdn')).val(result);
$('#imgPictureEn').attr('src', '../Data/Wishes/' + result).show();
HideLoading();
},
error: function(err) {
alert(err.statusText);
HideLoading();
}
});
} else {
alert("FormData is not supported.");
}
}

Categories