converting canvas to blob using cropper js - javascript

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

Related

How to load an HTML5 Canvas with an image from an image-service?

My web app calls a Web API service, which returns an image. The service returns nothing but an image. Calling the service is little different because there is a function in the routing code that adds the required auth-code and such. Anyway, my point is, I don't have the full URL and even if I did, I wouldn't want to pass it into code in plain-text. So what I have is a response, and that response is an image.
getThumb(filename: string) {
return this.http.get('/Picture/' + filename).subscribe(response => {
return response;
});
}
What I need to do is draw that image on to a canvas. From what I've seen on the internet so far, it looks like I want to create an image element, then assign that element src a URL, then I can add it to the canvas. It's the src part that's perplexing me. All the samples I see are either loading the image from a local filesystem or predefined URL, or from a base64 string, etc. I can't figure out how to just load an image I have as a response from a service. I'm sure I'm overthinking it.
Does anyone have some sample code to illustrate this?
e.g Something like this:
var img = new Image(); // Create new img element
img.src = ... ; // Set source to image
You could convert the image to Base64. In my example, you request the image and convert it to a blob using response.blob(). Once it's a blob, use fileReader.readAsDataURL to get the Base64.
const fileReader = new FileReader();
fetch("image-resource").then((response) => {
if(response.ok) {
return response.blob();
}
}).then((blob) => {
fileReader.readAsDataURL(blob);
fileReader.onloadend = () => {
console.log(fileReader.result);
}
});
References:
readAsDataURL
Blob

JS: how can I base64 encode a local file without XMLHttpRequest?

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.

putting an image into chrome.storage extension

I'm currently writing a Chrome extension that needs to save some images into chrome.storage memory. I'm currently making an array of objects:
var AnImage = new Image()
AnImage.src = http://image.image/imageurl.png
var ObjectToSave = { ...,
graph_img : AnImage,
... }
...
AnArray[x] = ObjectToSave
I output with a simple append
document.getElementById("AnElement").appendChild(ObjectToSave.graph_img)
But when I load it from storage and try to append it again, it returns an error
Error in response to storage.get: TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'.
When I output it through console.log() it evaluates what has been retrieved as an object, but not anything I can recognise. I'm currently using chrome.storage.sync
Is there a way of doing this? There seems to be little help in the way of storing images, and of what exists is old and talks about encoding with base64 for the older storage API. But when I did my initial research there were people claiming that base64 encoding was no longer necessary
After more looking, I found out about the FileReader object that provides a more elegant way over using the canvas method. And as this is chrome specific compatibility is ensured.
function ImageLoader( url ){
var imgxhr = new XMLHttpRequest();
imgxhr.open( "GET", url + "?" + new Date().getTime() );
imgxhr.responseType = "blob";
imgxhr.onload = function (){
if ( imgxhr.status===200 ){
reader.readAsDataURL(imgxhr.response);
}
};
var reader = new FileReader();
reader.onloadend = function () {
document.getElementById( "image" ).src = reader.result;
chrome.storage.local.set( { Image : reader.result } );
};
imgxhr.send();
}
Using chrome.storage.local is needed as it is highly likely that the storage size limit for chrome.storage.sync will be exceeded.
As Marc Guiselin and wOxxOm mentioned in the comments, chrome.storage will serialize the data first, to save image, you could:
Save the image src. chrome.storage.sync.set({ src: img.src });
Save the image dataURL.

html image blob to base64

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.

Is it possible to convert FileReader readAsArrayBuffer data into html5 canvas compatible imageData

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);
}
})();
};

Categories