I've got some problems about to fileinputjs.The images' src are blob.But i want to use images' src to do something.So i use readAsDataURL to get base64.But there are any problems about it 。
<script type="text/javascript">
$("#last").click(function(){
var blob=document.querySelector(".file-preview-image").src;
var reader = new FileReader(); //通过 FileReader 读取blob类型
reader.onload = function(){
this.result === dataURI; //base64编码
}
console.log(reader.readAsDataURL(blob));
})
</script>
Then there are Uncaught TypeError: Failed to execute 'readAsDataURL' on 'FileReader': parameter 1 is not of type 'Blob'.
A lot of misconception here.
your variable blob is not a Blob, but a string, the url of .file-preview-image.
FileReader can't do anything from this string. (Or at least not what you want).
in the onload callback of the FileReader, you are just checking if the result is equal to an undefined variable dataURI. That won't do anything.
you are trying to console.log the call to readAsDataURL which will be undefined since this method is asynchronous (you have to call console.log in the callback).
But since I guess that what you have is an object url (blob://), then your solution is either to get the real Blob object and pass it to a FileReader, or to draw this image on a canvas, and then call its toDataURL method to get a base64 encoded version.
If you can get the blob :
var dataURI;
var reader = new FileReader();
reader.onload = function(){
// here you'll call what to do with the base64 string result
dataURI = this.result;
console.log(dataURI);
};
reader.readAsDataURL(blob);
otherwise :
var dataURI;
var img = document.querySelector(".file-preview-image");
var canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
canvas.getContext('2d').drawImage(img, 0,0);
dataURI = canvas.toDataURL();
But note that for the later, you'll have to wait that your image actually has loaded before being able to draw it on the canvas.
Also, by default, it will convert your image to a png version. You can also pass image/jpegas the first parameter of toDataURL('image/jpeg') if the original image is in JPEG format.
If the image is an svg, then there would be an other solution using the <object> element, but except if you really need it, I'll leave it for an other answer.
Related
This is a continuation to my previous question but the issue is new and the solution from that question didn't help. This is a new question.
Here's the link to my previous question where I asked how to convert canvas to an image: javascript- unable to convert canvas to image data
And I'm hoping to get the base64 encoded string of the image which I can send to a PHP service via AJAX call and PHP service is gonna convert it to image and move it to a specified directory.
Function that converts canvas to image
function convertCanvasToImage(canvas)
{
var image = new Image();
image.src = canvas.toDataURL("image/png");
return image;
}
This is the form I created:
var url = 'url to php service';
var file = dataURL; //this is the image url that i'm sending
console.log(file);
var formdata = new FormData();
formdata.append("base64image", file);
formdata.append('csrf_test_name',csrf_token);
var ajax = new XMLHttpRequest();
ajax.addEventListener("load", function(event) {
uploadcomplete(event);
}, false);
ajax.open("POST", url);
ajax.send(formdata);
I tried console.log() the image that canvas returned and this is what I obtained:
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAoAAAAHgCAYAAAA10dzkAAAgAElEQVR4nGzbZ3Mba5au6fqvJ2JiTs/pPtVV20j0sOm9T3iARqI3IOi9SIoGHqATJe29q/v8jXs+QMWeHT0fnkgGyUgCiRfIi2ut9y9OqYGZ3yKqHWHlttFiCz1nE8Q+XuDiuSb5XEBccYgrDv6si5ZTMOZMzHkLMS6gFspI8TxiOEfkfCS0P1AM1lmcPaJYPcbyNvDDHUqVU5zdTaS1j4hFm3Erg5bxCK0KxXiWUm6OcLaAW46xCzZBNcAOF3FzK8TBIoG7QC7v4AUalqdRquVQZxeQa/PYc2vYc2uUnWUCuYovR+TMEoEVY8oOnhES2jlKVo2au0DZXiVSF/DciDDMUyjOEuerGGqJYm6VaG6DhBahOyW8eB4rrBGVl5BmZ5FmZ1HyLlrJZ37ep1jUyXseOdel7FWpBrMUgwXy3ixGJGLlZLRIxipoh...Hd7sRkseD2ebFF/Bj9btUYEnDzGHRy57XgcDiw2WyYDPdYzFp0dgvXBh0XeiPmYBit2YzBbufR4uDR4kBrd3BtNHHvs6ty3HJru+beoUXn0vPgNaD1Gbl1udFYbWhMFlU2E7du+zTmRWt75MGqw+axYvNYebRpMbmNaF0OzEE/+nQAXcrHpeBAk7BzJTm4zXg4Kdq4afq4nGS4fslyO85x1IizEbWwJzo5Lzu4bfk560Y5agY57SfYawS57sS4akfRFJxc5B1cl7XcVh85Gfo47HvYaFvY6ds5Hvg5GQY4bUY5rofQtAUumgk0XVXXozSXQxX+rnsSt20nmrqFG+URbdHMVSOGphbmrCNw1hG46Dg4aaoxP0c1B0dVD7sFO0cFG0cFG+fKNSeyhjPhBI10zmnqnPP0xRQAD1Pqs7CSV7VV3mCztM5Rbpnz8joXHSPXfQuXPQ9XAy9noxgXE4HT/8pz8X/L/D+QyAVhXuteXgAAAABJRU5ErkJggg==">
It has image tag. Maybe it's because of that; when I pass it to PHP service, it's not able to convert it. This is what it returned me when I debugged
object HTMLImageElement
I tried to convert the above mentioned image tag to base64 using a function like given below but it failed.
function encodeImageFileAsURL(cb) {
return function(){
var file = this.files[0];
var reader = new FileReader();
reader.onloadend = function () {
cb(reader.result);
}
reader.readAsDataURL(file);
}
}
Can anyone help me understand what i am missing here? Thanks a lot!
Reference:
https://davidwalsh.name/browser-camera
https://davidwalsh.name/convert-canvas-image
You already have a data URI at the src of the <img> element at variable image. Pass the value of the src of the <img> element to php, not the html <img> element.
var file = image.src; //this is the image url that i'm sending
I'm trying to base64 encode a local file. It's next to my .js file so there's no uploading going on. Solutions like this (using XMLHttpRequest) get a cross-site scripting error.
I'm trying something like this (which doesn't work but it might help explain my problem):
var file = 'file.jpg'
var reader = new FileReader();
reader.onload = function(e) {
var res = e.target.result;
console.log(res);
};
var f = reader.readAsDataURL(file);
Anyone have any experience doing this locally?
Solutions like this (using XMLHttpRequest) get a cross-site
scripting error.
If using chrome or chromium browser, you could launch with --allow-file-access-from-files flag set to allow request of resource from local filesystem using XMLHttpRequest() or canvas.toDataURL().
You can use <img> element, <canvas> element .toDataURL() to create data URL of local image file without using XMLHttpRequest()
var file = "file.jpg";
var img = new Image;
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
img.onload = function() {
canvas.width = this.naturalWidth;
canvas.height = this.naturalHeight;
ctx.drawImage(this, 0, 0);
var res = canvas.toDataURL("image/jpeg", 1); // set image `type` to `image/jpeg`
console.log(res);
}
img.src = file;
You could alternatively use XMLHttpRequest() as described at Convert local image to base64 string in Javascript.
See also How to print all the txt files inside a folder using java script .
For a details of difference of returned data URI from either approach see canvas2d toDataURL() different output on different browser
As described by #Kaiido at comment below
it will first decode it, at this stage it's still your file, then it
will paint it to the canvas (now it's just raw pixels) and finally it
will reencode it (it has nothing to do with your original file
anymore) check the dataURI strings... They're compeltely different and
even if you do the canvas operation from two different browsers,
you'll have different outputs, while FileReader will always give you
the same output, since it encode the file directly, it doesn't decode
it.
I have the same image and the same size of canvas, but the output is different. I want the same output, how should I do it?
var canvas = document.createElement('canvas'),
ctx = canvas.getContext('2d'),
img = new Image;
img.crossOrigin = 'Anonymous';
img.onload = function(){
canvas.height = img.height;
canvas.width = img.width;
ctx.drawImage(img, 0, 0);
var dataURL = canvas.toDataURL();
setBreakpoint(dataURL);
callback.call(this, dataURL);
canvas = null;
};
img.src = url;
Images drawn onto a canvas are decoded before being drawn, then reencoded when the toDataURL method is called.
This process will produce some variations in every browser (e.g some will be able to decode color-profiles embedded in the image while others won't), and even every machine (look at canvas fingerprinting and this post by #Oriol which concern images with transparency). Add to that that every browser will use different encoders/settings for a different tradeoff between speed, size and quality and you arrive at a situation where you can't expect two users to produce the same result from the same input image.
But since all you do with that canvas is to draw an image, you should rather use a FileReader and its method readAsDataURL(). For external files, you can still use it by first fetching the resource as a Blob.
This will work directly on the binary data of the file, encoding each byte to its base64 representation, and thus you will be sure to have the same result in every browser.
Here is a snippet which will test your browser's conversion against mine's.
fetch("https://dl.dropboxusercontent.com/s/4e90e48s5vtmfbd/aaa.png")
.then((resp) => resp.ok && resp.blob())
.then((blob) => {
const reader = new FileReader();
reader.onload = (evt) => {
if (reader.result === imageDataURL) {
console.log("same result");
}
else {
console.log("please post a comment stating which browser has such a bug");
}
};
reader.readAsDataURL(blob);
});
var imageDataURL = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAMAAAEzo7pQAAAACXBIWXMAAAsTAAALEwEAmpwYAAAKT2lDQ1BQaG90b3Nob3AgSUNDIHByb2ZpbGUAAHjanVNnVFPpFj333vRCS4iAlEtvUhUIIFJCi4AUkSYqIQkQSoghodkVUcERRUUEG8igiAOOjoCMFVEsDIoK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AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAPcxUCgAAABd0Uk5T/////////////////////////////wDmQOZeAAACLElEQVR42mIUY2BgYGJgeM3AxPBd4C0LAyfDPwAAAAD//2KEiL1+y8DEwCDMwMTA9pYBAAAA//8EwTEOABAUBbB6m8Qm3P9+8gerSdu2s84ijPJK6NwplKR8AAAA//8syrEKgCAABuHzt5Z0EAzf//1EEESEIG3Im77hTOJPQN4YZMA6lj2p10F950oREebt92x6A1GEnsJH1hysAAgCURS9DpYpQYuh//9AGaTAFi2sheSmt76cN5xvHshxJcMOQC/KPB0I2n3MhUuakJ77TB5QI+JCjRARAN2obRmo0bQKFloB/d2+bJDLDoJAEARrF4JZBImO+v/f5zgXZUENDw9EhOgcK53u1PwAzx+ggOoChCuXVaJwRlXpqsP15O0MrCzzun4kL2xycWPsQ9ql47hJ8KANssviEJp7NukbxW0L+dwh0h8jz8WKxtaHTr/glEVx/qCTvsHeYQPOG4I7Y4BgAPJ58uLepJHbasMwEAXHkhJVMgkNtv//A2XRtL7JEK/y0LqmrqEPfVuWw7B75teCv/rhQCQQqjHV0GZYjf4MNG1RtjVy0Sz9EYGaQEJr0CS6DaLLryGWrtemP+XO5+m63P0uEL3GTOaUkyN5hfmYinz325GMSDOmwtoZXMR7RqrvGwLqQhduvJ1Jn42B2xUV5boMGAvzozkqSm56UOrVDYMtw1Ggee9KJ0Wh1Isl7F1EkGpkUiA4Zs7yELXaiwCy4WRlr19U/7L5HAAZyaffhXaAFwAAAABJRU5ErkJggg=="
However for the ones using the canvas for real drawing, as we said above, you can't really have the same results between different UAs. Every method from drawing ones to export ones may produce different results and you would have to actually rewrite all these methods entirely in order to have the exact same results.
For the ones that really need this, a project like node-canvas could help, though it would obviously be a lot less performant than native implementations.
I have created an application using cropper.js for cropping an images. The application is working and the image is cropping, after that I am trying to send the cropped image as blob to the server side for storing,
As per the cropper.js documentation we can use canvas.toDataURL to get a Data URL, or use canvas.toBlob to get a blob and upload it to server with FormData. when I tried canvas.toDataURL() I am getting the base64 string, but actually I need to send the file as blob so I tried with canvas.toBlob() but I am getting Uncaught TypeError: canvas.toBlob is not a function in chrome and TypeError: Not enough arguments to HTMLCanvasElement.toBlob. in Firefox
Can anyone please tell me some solution for this
My code is like this
var canvas = $image.cropper("getCroppedCanvas", undefined);
var formData = new FormData();
formData.append('mainImage', $("#inputImage")[0].files[0]);
formData.append('croppedImage', canvas.toBlob());
The method toBlob is asynchronous and require two arguments, the callback function and image type (there is optional third parameter for quality):
void canvas.toBlob(callback, type, encoderOptions);
Example
if (typeof canvas.toBlob !== "undefined") {
canvas.toBlob(function(blob) {
// send the blob to server etc.
...
}, "image/jpeg", 0.75);
}
else if (typeof canvas.msToBlob !== "undefined") {
var blob = canvas.msToBlob()
// send blob
}
else {
// manually convert Data-URI to Blob (if no polyfill)
}
Not all browsers supports it (IE needs prefix, msToBlob, and it works differently than the standard) and Chrome needs a polyfill.
Update (to OP's edit, now removed) The main reason why the cropped image is larger is because the original is JPEG, the new is PNG. You can change this by using toDataURL:
var uri = canvas.toDataURL("image/jpeg", 0.7); // last=quality
before passing it to the manual data-uri to Blob. I would recommend using the polyfill as if the browser supports toBlob() it will be many times faster and use less memory overhead than going by encoding a data-uri.
The proper use: https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob
you have to pass the callback and use the blob object within callback. toBlob() does not returns the blob rather it accepts a callback which provides blob as parameter.
var canvas = document.getElementById("canvas");
canvas.toBlob(function(blob) {
var newImg = document.createElement("img"),
url = URL.createObjectURL(blob);
newImg.onload = function() {
// no longer need to read the blob so it's revoked
URL.revokeObjectURL(url);
};
newImg.src = url;
document.body.appendChild(newImg);
});
I'm looking for a way to draw an image to a canvas directly from the html5 FileReader api.
The usual method is to create a new image object, wait for onload and then draw it to the canvas with drawImage().
However for a specific case which I do not need to go into I would like to bypass the loading of the image data completely if at all possible.
Since the filereader api supports readAsArrayBuffer() I was wondering if there is any way I could take this arraybuffer and convert it into canvas imageData in order to use ctx.putImageData(array) to render the image.
Thanks in advance.
Loading the image is a neccessary step I think; at one end of the process you just have a binary blob which could be a JPEG or PNG (or BMP, any other mime type), while at the other you have an array containing raw pixel data. While you could technically code this conversion yourself, the fileReader.readAsDataURL and ctx.drawImage methods do this for you internally.
FWIW, his is how I draw an image to canvas.
// read binary data from file object
var fileRead = function(file){
var reader = new FileReader();
reader.onload = fileReadComplete;
reader.readAsDataURL(file);
};
// convert binary data to image object
var fileReadComplete = function(e){
var img = new Image();
img.src = e.target.result;
(function(){
if (img.complete){
ctx.drawImage(img);
}
else {
setTimeout(arguments.callee, 50);
}
})();
};