js生成图片缩略图

现今大部分的网络应用在上传图片的时候都会同时保存几种尺寸的图片,专业术语也就是生成缩略图,而对于生成缩略图一般做法是通过后端语言php等来生成,但是为了给服务器减压,我们或许可以从前端来着手,先生成好不同尺寸的缩略图,传给后端,而后端只需要将前端传过来的图片进行存储就好了。

使用Canvas我们可以轻松生成各种尺寸的图片,具体实现如下:

function resizeImage(src,callback,w,h){
var canvas = document.createElement("canvas"),
ctx = canvas.getContext("2d"),
im = new Image();
w = w || 0,
h = h || 0;
im.onload = function(){
//为传入缩放尺寸用原尺寸
!w && (w = this.width);
!h && (h = this.height);
//以长宽最大值作为最终生成图片的依据
if(w !== this.width || h !== this.height){
var ratio;
if(w>h){
ratio = this.width / w;
h = this.height / ratio;
}else if(w===h){
if(this.width>this.height){
ratio = this.width / w;
h = this.height / ratio;
}else{
ratio = this.height / h;
w = this.width / ratio;
}
}else{
ratio = this.height / h;
w = this.width / ratio;
}
}
//以传入的长宽作为最终生成图片的尺寸
if(w>h){
var offset = (w - h) / 2;
canvas.width = canvas.height = w;
ctx.drawImage(im,0,offset,w,h);
}else if(w<h){
var offset = (h - w) / 2;
canvas.width = canvas.height = h;
ctx.drawImage(im,offset,0,w,h);
}else{
canvas.width = canvas.height = h;
ctx.drawImage(im,0,0,w,h);
}
callback(canvas.toDataURL("image/png"));
}
im.src = src;
}


  • 支付宝二维码 支付宝
  • 微信二维码 微信

本文地址: https://99zc.com/Study/30.html

版权声明:本文为原创文章,版权归  淡定个人博客 所有,欢迎分享本文,转载请保留出处!

相关文章
加载中~