Js generates thumbnails after uploading and using canvas redraw

  • 2020-03-30 03:00:37
  • OfStack

Generally in the processing of image upload, the usual logic is to upload the source image to the server side, and then by the server side language to scale the size of the operation.

This mode can generally meet most of the requirements, but when the image we need is only a thumbnail of the source image of the specified size, it will be a waste of server resources and bandwidth to use this mode, so we consider to generate a small image in the browser before uploading.

// the following is the source code
 
function drawCanvasImage(obj,width, callback){ 

var $canvas = $('<canvas></canvas>'), 
canvas = $canvas[0], 
context = canvas.getContext('2d'); 

var img = new Image(); 

img.onload = function(){ 
if(width){ 
if(width > img.width){ 
var target_w = img.width; 
var target_h = img.height; 
}else{ 
var target_w = width; 
var target_h = parseInt(target_w/img.width*img.height); 
} 
}else{ 
var target_w = img.width; 
var target_h = img.height; 
} 
$canvas[0].width = target_w; 
$canvas[0].height = target_h; 

context.drawImage(img,0,0,target_w,target_h); 

_canvas = canvas.toDataURL(); 
 
callback(obj,_canvas); 
} 
img.src = getFullPath(obj); 

} 

function getFullPath(obj) 
{ 
if(obj) 
{ 
//ie 
if (window.navigator.userAgent.indexOf("MSIE")>=1) 
{ 
obj.select(); 
return document.selection.createRange().text; 
} 
//firefox 
else if(window.navigator.userAgent.indexOf("Firefox")>=1 || $.browser.opera || $.browser.mozilla) 
{ 
if(obj.files && window.URL.createObjectURL) 
{ 
return window.URL.createObjectURL(obj.files[0]); 
} 
return obj.value; 
}else if($.browser.safari){ 
if(window.webkitURL.createObjectURL && obj.files){ 
return window.webkitURL.createObjectURL(obj.files[0]); 
} 
return obj.value; 
} 
return obj.value; 
} 
} 

The getFullPath function gets the address of the selected image.

_canvas gets the base64-encoded image encoding, which can be transferred to the back-end and written to a file.

Related articles: