I would like to validate an image on the client-side, checking the dimensions against predefined criteria.
This should help you understand how this can be done.
var img = new Image();
var base64Image = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQBAMAAADt3eJSAAAAJ1BMVEUAAACAgIDo6Ojq6urt7e3v7+/x8fH09PT29vb4+Pj6+vr9/f3///8nK8D7AAAAAXRSTlMAQObYZgAAAFZJREFUCB0FwcERAUEUBcCe8d1lIJSVyYZCKPIRidObi61VitENoLUTSGsPeC0lsOmSZB1K2OfQ5ZrbHLq8n9ahxP2Yjy4XS4YSh/gqcY6fEphKAAAA/p/UJlqT/uIiAAAAAElFTkSuQmCC';
img.onload = function(){
document.getElementById('imgData').innerHTML = "Widht: "+img.width+" Height:"+img.height;
};
img.src = base64Image;
<div id='imgData'></div>
Related
I have a div where users can drag and drop an image and then, using FileReader, I get the base64 of the image. Works fine.
dropper.ondrop = function (e) {
e.preventDefault();
var file = e.dataTransfer.files[0];
var reader = new FileReader();
reader.readAsDataURL(file);
};
My issue is if I have a browser window open and drag and drop an image from the browser I get the error:
Failed to execute 'readAsDataURL' on 'FileReader':
parameter 1 is not of type 'Blob'.
Now, is there any turnaround to get the base64 of an image dragged from the browser window?
Ultimately, is there is a way to get the image URL and then the actual base64 with a server side curl request?
Any idea?
You can use e.dataTransfer.getData('url') to tell whether there's a URL available. Like this:
var url = e.dataTransfer.getData('url');
if(url){
console.log('Url');
console.log(url);
}else{
console.log('File');
var file = e.dataTransfer.files[0];
var reader = new FileReader();
reader.readAsDataURL(file);
}
Then, having the URL, you can load an img element and use draw it on a canvas to grab the base64 representation. Like this:
var img = document.createElement('img');
img.crossOrigin = 'anonymous';
img.onload = function(){
var canvas = document.createElement('canvas');
canvas.width = this.width;
canvas.height = this.height;
var context = canvas.getContext('2d');
context.drawImage(this, 0, 0);
console.log(canvas.toDataURL());
};
img.src = url;
This would be the "final" product:
var dropper = document.querySelector('div');
dropper.ondragover = function(e) {
e.preventDefault();
}
dropper.ondrop = function (e) {
e.preventDefault();
var url = e.dataTransfer.getData('url');
if(url){
console.log('Url');
console.log(url);
var img = document.createElement('img');
img.crossOrigin = 'anonymous';
img.onload = function(){
var canvas = document.createElement('canvas');
canvas.width = this.width;
canvas.height = this.height;
var context = canvas.getContext('2d');
context.drawImage(this, 0, 0);
console.log(canvas.toDataURL());
};
img.src = url;
}else{
console.log('File');
var file = e.dataTransfer.files[0];
var reader = new FileReader();
reader.readAsDataURL(file);
}
};
div{
border:1px solid red;
height:240px;
width:100%;
}
<div>Drop here</div>
Also available here: https://jsfiddle.net/8u6Lprrb/1/
The first parameter comes through with the "http://" or "https://" protocol instead of the expected "file://" protocol. and thats why you cant read it with the HTML5 FILE API, so you may want to download and save the file first before trying to read the contents.
on the other hand, you can update an img tag's src attribute with the retrieved url and skip the readDataAsUrl() portion to hotlink the image.
When i try to add the image in the URL to a PDF file the image comes completley black.
But when I click the download pdf button again the image gets added to the PDF.Only
when I do it the first time, the image comes as black.
function getBase64Image(url) {
alert(url);
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var img = new Image();
img.src = url;
img.style.height ="181px";
img.style.width ="183px";
//img.crossOrigin ="Anonymous";
context.drawImage(img,0,0);
var dataURL = canvas.toDataURL("image/jpeg");
alert(dataURL);
document.body.appendChild(img);
var doc = new jsPDF('landscape');
doc.addImage(img,'JPEG',0,0,50,50);
doc.save('Saved.pdf');
}
getBase64Image("http://localhost:64931/jspdf/download.png");
What happens when you change your code like this:
A changed JPEG to PNG, that worked for me.
function getBase64Image(url) {
alert(url);
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var img = new Image();
img.src = url;
img.style.height ="181px";
img.style.width ="183px";
//img.crossOrigin ="Anonymous";
context.drawImage(img,0,0);
var dataURL = canvas.toDataURL("image/png");
alert(dataURL);
document.body.appendChild(img);
var doc = new jsPDF('landscape');
doc.addImage(img,'PNG',0,0,50,50);
doc.save('Saved.pdf');
}
getBase64Image("http://localhost:64931/jspdf/download.png");
I was facing the same issue yesterday, and writing this answer incase someone finds it useful
What I was trying to achieve?
I was converting the doc (pdf) into a blob and then opening it in a print dialogue, but the image was black.
var blob = new Blob([doc.output()], { type: "application/pdf" });
This is how I was trying to convert it into a blob.
but this resulted in a black image
Solution
jsPDF allows us to add arguments in the output function.
[](jsPDF output api)
adding type as bloburl works for me, as i was opening a print dialogue using the blob url
let iframe = document.createElement("iframe"); //load content in an iframe to print later
document.body.appendChild(iframe);
//* print dialogue
iframe.style.display = "none";
iframe.src = blobURL;
console.log(blobURL) // same blobURL that was received from jsPDF
iframe.onload = function () {
setTimeout(function () {
iframe.focus();
iframe.contentWindow.print(); // opens a print dialogue box
}, 1);
};
Using JavaScript, I want to convert an img tag like this:
<img width="11" height="14" src="http://mysite/file.gif" alt="File Icon">
Into one with a dataurl like this:
<img width="11" height="14" src="data:image/gif;base64,R0lGODlhCwAOAMQfAP////7+/vj4+Hh4eHd3d/v7+/Dw8HV1dfLy8ubm5vX19e3t7fr6+nl5edra2nZ2dnx8fMHBwYODg/b29np6eujo6JGRkeHh4eTk5LCwsN3d3dfX13Jycp2dnevr6////yH5BAEAAB8ALAAAAAALAA4AAAVq4NFw1DNAX/o9imAsBtKpxKRd1+YEWUoIiUoiEWEAApIDMLGoRCyWiKThenkwDgeGMiggDLEXQkDoThCKNLpQDgjeAsY7MHgECgx8YR8oHwNHfwADBACGh4EDA4iGAYAEBAcQIg0Dk gcEIQA7" alt="File Icon">
Is this possible?
Here's how to get the data url of an image with fetch:
(async function() {
let blob = await fetch("https://example.com/image.png").then(r => r.blob());
let dataUrl = await new Promise(resolve => {
let reader = new FileReader();
reader.onload = () => resolve(reader.result);
reader.readAsDataURL(blob);
});
// now do something with `dataUrl`
})();
First, load the image into a canvas
var canvas = document.createElement("canvas");
context = canvas.getContext('2d');
make_base();
function make_base()
{
base_image = new Image();
base_image.src = 'img/base.png';
base_image.onload = function(){
context.drawImage(base_image, 100, 100);
}
}
Make sure to update the context.drawImage(base_image, 100, 100); to values appropriate for your application.
Source: https://stackoverflow.com/a/6011402/3969707
Then convert the canvas to data.
var jpegUrl = canvas.toDataURL("image/jpeg");
var pngUrl = canvas.toDataURL(); // PNG is the default
Source: https://stackoverflow.com/a/15685877/3969707
I'd solve this problem with a temporary canvas element with the same size of the image loaded:
function imageToUri(url, callback) {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
var base_image = new Image();
base_image.src = url;
base_image.onload = function() {
canvas.width = base_image.width;
canvas.height = base_image.height;
ctx.drawImage(base_image, 0, 0);
callback(canvas.toDataURL('image/png'));
canvas.remove();
}
}
imageToUri('./assets/some_image.png', function(uri) {
console.log(uri);
});
This really isn't something you may want to do in JavaScript as it requires the image be parsed in JavaScript which is very slow. You would be loading the image and then putting the output of the function into the img tag, which doesn't save bandwidth, decrease complexity, or improve security.
Your best bet is to do this server-side. I've used this to great success in the past for generating pages which need to have absolutely no linked/referenced external resources. You can, for jsPDF, then use raw JavaScript or jQuery to get the data of an image to pass into the PDF creation process.
This will work everywhere and not rely on resorting to canvas which doesn't have full mobile browser support.
I have the following code :
function createImage(source) {
var pastedImage = new Image();
pastedImage.onload = function() {
document.write('<br><br><br>Image: <img src="'+pastedImage.src+'" height="700" width="700"/>');
}
pastedImage.src = source;
}
Here I am displaying the image through html image tag which I wrote in document.write and provide appropriate height and width to image.
My question is can it possible to displaying image into the canvas instead of html img tag? So that I can drag and crop that image as I want?
But how can I display it in canvas?
Further I want to implement save that image using PHP but for now let me know about previous issue.
Try This
var ctx = document.getElementById('canvas').getContext('2d');
var img = new Image(); // Create new img element
img.onload = function(){
// execute drawImage statements here This is essential as it waits till image is loaded before drawing it.
ctx.drawImage(img , 0, 0);
};
img.src = 'myImage.png'; // Set source path
Make sure the image is hosted in same domain as your site. Read this for Javascript Security Restrictions Same Origin Policy.
E.g. If your site is http://example.com/
then the Image should be hosted on http://example.com/../myImage.png
if you try http://facebook.com/..image/ or something then it will throw security error.
Use
CanvasRenderingContext2D.drawImage.
function createImage(source) {
var ctx = document.getElementById('canvas').getContext('2d');
var pastedImage = new Image();
pastedImage.onload = function(){
ctx.drawImage(pastedImage, 0, 0);
};
pastedImage = source;
}
Also MDN seems to be have nice examples.
Is there any way I could load an image via javascript and then have a callback fire when it is finished?
Thanks for any ideas.
Have you tried this?
var img = new Image();
img.onload = function(){ alert('loaded'); };
img.src = '/some/image.jpg';
UPDATE
sure you can set the background-image of an element with this. Use the onload event to do whatever you like!
// change background to image - only after image completely loaded
function setBackroundImage(node, imageUrl) {
var img = new Image();
img.onload = function() {
node.style.backgroundImage = imageUrl;
}
img.src = imageUrl;
}
setBackroundImage(document.getElementById('foobar'), '/some/image.jpg');
Here is the sample code to handle image load:
var img = document.createElement('img')
img.src = 'https://www.google.com/intl/en_com/images/srpr/logo3w.png'
$(img).load(function(){ alert('Image loaded')})
$('#container').append(img)