码迷,mamicode.com
首页 > Web开发 > 详细

js生成缩略图后上传并利用canvas重绘

时间:2015-07-28 17:49:24      阅读:121      评论:0      收藏:0      [点我收藏+]

标签:

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

------------------------------------------------------------------------------------

函数getFullPath为获取选中的图片的地址。

_canvas获取到的是base64编码的图片编码,将其传输到后端写入文件即可。

 

------------------------------------------------------------------------------------

js生成缩略图后上传并利用canvas重绘

标签:

原文地址:http://www.cnblogs.com/parning/p/4683111.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!