Home > Web Front-end > JS Tutorial > body text

js generates thumbnails and then uploads them and redraws them using canvas_javascript skills

WBOY
Release: 2016-05-16 16:48:00
Original
1481 people have browsed it

Generally, when processing image uploads, the usual logic is to upload the source image to the server, and then use the server-side language to perform the scaling operation.

This mode can generally meet most needs, but when the image we need is only a thumbnail of the source image that meets the specified size, then using this mode will be a waste of the server. resources and bandwidth, so we consider generating a small image on the browser side before uploading it.

//The following is the source code

Copy the code The code is as follows:

function drawCanvasImage(obj,width, callback){

var $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();
/*console.log(_canvas);*/
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 function getFullPath is to get the address of the selected picture.

_canvas obtains the base64-encoded image encoding, which can be transferred to the backend and written into a file.
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!