3

Task:

My task is to create a thumbnail generator using JavaScript without additional frameworks or server side. A user drops an image to a dropzone and a thumbnail is generated and displayed onto the screen. When you click on a thumbnail the full version of image should appear in the next tab.

Current solution:

I have used an invisible canvas element to draw the full and resized version of the image and I am saving them by using canvas.toDataURL() and attach this base64 encoding to the img and a tags.

Problem:

The problem I am facing is related to the file size of the image I can drop. Currently when I upload the image that exceeds 2 Megabytes the thumbnail is generated correctly but if I want to display the full size image Chrome or Firefox crash due to base64 length limit.

Question:

Is there any workaround to bypass base64 lenght limit?

1 Answers1

4

Yes.

You should use HTMLCanvasElement.toBlob to create Blob object, and then URL.createObjectURL to create temporary URL that can be used to display image via or for downloading image.

Also take a look at MDN articles like 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"/>

Please note that since canvas.toBlob accepts callback, and calling window.open from callback (rather than click event) will cause window to be blocked (read more here and here).

To bypass this you can create a blob beforehand, so when click occurs you can display image instantly.

Community
  • 1
  • 1
Sanya_Zol
  • 488
  • 3
  • 9