移动端图片方向旋转和图片等比例压缩

问题

移动端选择照片上传,经常遇到这两个问题:照片方向错误,需要旋转,照片尺寸过大,需要压缩后像后台传输。

解决方法

针对这两个常见的问题,整理为以下函数:

/**
 * 旋转并等比例压缩
 * @param img
 * @param canvas
 * @param orientation 引入exif.js,可以通过 orientation = EXIF.getTag(this, 'Orientation'); 获得,或者相似方法获得
 * @param maxWidth
 * @param maxHeight
 */
function rotateByOrientationAndCompressImg(img, canvas, orientation, maxWidth, maxHeight) {
    switch (orientation) {
        case 3:
            rotateByDegreeAndCompressImg(img, canvas, 180, maxWidth, maxHeight);
            break;
        case 6:
            rotateByDegreeAndCompressImg(img, canvas, 90, maxWidth, maxHeight);
            break;
        case 8:
            rotateByDegreeAndCompressImg(img, canvas, 270, maxWidth, maxHeight);
            break;
        default:
            rotateByDegreeAndCompressImg(img, canvas, 0, maxWidth, maxHeight);
    }
}

/**
 * 旋转并等比例压缩
 * @param img 是 new Image() 类型
 * @param canvas 画布
 * @param degree 顺时针旋转的度数,单位是°,允许为 0(不旋转),90,180,270 共4种值
 * @param maxWidth 压缩后最大宽度,为null则不压缩
 * @param maxHeight 压缩后最大高度,为null则不压缩
 */
function rotateByDegreeAndCompressImg(img, canvas, degree, maxWidth, maxHeight) {
    var ctx = canvas.getContext('2d');
    /* 原来的宽和高 */
    var width = img.width;
    var height = img.height;
    /* 压缩后的宽和高 */
    var cWidth = width;
    var cHeight = height;
    if (maxWidth != null) {
        if (cWidth > maxWidth) {
            cHeight = parseInt(cHeight * maxWidth / cWidth);
            cWidth = maxWidth;
        }
    }
    if (maxHeight != null) {
        if (cHeight > maxHeight) {
            cWidth = parseInt(cWidth * maxHeight / cHeight);
            cHeight = maxHeight;
        }
    }
    switch (degree) {
        default:
        case 0:
            canvas.width = cWidth;
            canvas.height = cHeight;
            ctx.drawImage(img, 0, 0, cWidth, cHeight);
            break;
        case 90:
            canvas.width = cHeight;
            canvas.height = cWidth;
            ctx.rotate(90 * Math.PI / 180);
            ctx.drawImage(img, 0, -cHeight, cWidth, cHeight);
            break;
        case 180:
            canvas.width = cWidth;
            canvas.height = cHeight;
            ctx.rotate(180 * Math.PI / 180);
            ctx.drawImage(img, -cWidth, -cHeight, cWidth, cHeight);
            break;
        case 270:
            canvas.width = cHeight;
            canvas.height = cWidth;
            ctx.rotate(270 * Math.PI / 180);
            ctx.drawImage(img, -cWidth, 0, cWidth, cHeight);
            break;
    }
}

具体的使用示例见:
https://github.com/gaoice/js-utils/blob/master/rotate-compress-img/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值