Drag and drop JavaScript thumbnail thumbnails. Browser crash due to base64 limit exceeded

A task:

My task is to create a sketch generator using JavaScript without any additional frameworks or server side. The user throws an image into the drop zone and a thumbnail is generated and displayed on the screen. When you click on a thumbnail, the full version of the image should appear in the next tab.

Current solution:

I used an invisible canvas element to draw the full and resized version of the image and I save them with canvas.toDataURL()

and attach this base64 encoding to img and a .

Problem

The problem I am facing is related to the file size of the image that I can delete. Currently, when I upload an image larger than 2 megabytes, the thumbnail is generated correctly, but if I want to display a full size shot of Chrome or Firefox due to the base64 length limitation.

Question

Is there a way to bypass the base64 bypass?

+3


source to share


1 answer


Yes.

You have to use HTMLCanvasElement.toBlob to create the Blob and then URL.createObjectURL to create a temporary url that can be used to display the image using or to load the image.

Also take a look at MDN articles such as Using Object URLs to Display Images



window.URL = window.URL || window.webkitURL;

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext("2d");
ctx.fillStyle = "#FFFFFF";
ctx.font="12px Verdana";
ctx.fillStyle = "#000000";
ctx.fillText("jpeg with",0,10);
ctx.fillText("quality 20 used",0,25);
ctx.fillText("intentionally",0,40);
ctx.moveTo(0,50);
ctx.lineTo(100,100);
ctx.stroke();
canvas.toBlob(function(blob){
	var img = document.createElement('img');
	var url = URL.createObjectURL(blob);
	img.src = url;
	img.onload = function(){
		URL.revokeObjectURL(url);
	}
	document.body.appendChild(img);
}, "image/jpeg", 0.20);
      

<p>may not work on stackoverflow, try jsfiddle in this case</p>
<canvas id="canvas" width="100" height="100"/>
      

Run codeHide result


Note that since canvas.toBlob

accepting a callback and calling window.open

from a callback (not a click) will block the window (more details here and here ).

To get around this, you can create a blob ahead of time, so when you click, you can display the image instantly.

+4


source







All Articles