利用canvas压缩图片并上传

一 前言

最近负责的H5中,有个上传照片的功能,照片是上传到阿里云。大家可能知道,手机拍到照片一般都较大,而服务器限制了上传图片的大小(服务器好像是可以设置这个大小的),于是开始研究利用canvas压缩图片,当然你也可以利用插件。废话不多说,只要你仔细看完,保证你能成功。

二 代码

HTML:

<!--上传图片-->
<input type="file" name="fileToUpload" id="fileToUpload"/> <br />
<input type="text" name="compressValue" id="compressValue" style="display:none;" /><br/>
<!--<input type="button" id='uploadBtn' value="上传" /><br/>-->
<input type="hidden" id="canvasData" value="canvasHidden">

Jquery:

function processfile(file,compressValue) {
    var reader = new FileReader();
    reader.onload = function (event) {
        var blob = new Blob([event.target.result]);
        window.URL = window.URL || window.webkitURL;
        var blobURL = window.URL.createObjectURL(blob);
        var image = new Image();
        image.src = blobURL;
        image.onload = function() {
            var resized = resizeMe(image);
            compressValue.value = resized;
        }
    };
    reader.readAsArrayBuffer(file);
}

function resizeMe(img) {
    //压缩的大小
    /*var max_width = 1920;
    var max_height = 1080;*/
    //设置这两个参数改变压缩后的大小
    var max_width = 3920;
    var max_height = 3080;

    var canvas = document.createElement('canvas');
    var width = img.width;
    var height = img.height;
    if(width > height) {
        if(width > max_width) {
            height = Math.round(height *= max_width / width);
            width = max_width;
        }
    }else{
        if(height > max_height) {
            width = Math.round(width *= max_height / height);
            height = max_height;
        }
    }

    canvas.width = width;
    canvas.height = height;

    var ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0, width, height);
    //压缩率
    return canvas.toDataURL("image/jpeg",0.92);
}
点击事件

$('#xxx').on("click",function () {
    var preview = document.getElementById('compressValue').value;
    //preview就是压缩后的数据,是base64格式
    console.log("preview}"+preview);
    if(preview == "") {
        toastr.warning("请选择图片");
    } else {
        var formFile = new FormData();
        formFile.append("xxx", xxx);
        formFile.append("file", preview); //加入文件对象
        var data = formFile;
        var url = "。。。";

        AJAXPOSTIMG(url, data, function () {
               。。。
        })
    }
})

java后台

后台用String接受就行

Base64转成MultipartFile:

public static MultipartFile base64ToMultipart(String base64) {
   try {
      String[] baseStrs = base64.split(",");

      BASE64Decoder decoder = new BASE64Decoder();
      byte[] b = new byte[0];
      b = decoder.decodeBuffer(baseStrs[1]);

      for(int i = 0; i < b.length; ++i) {
         if (b[i] < 0) {
            b[i] += 256;
         }
      }

      return new BASE64DecodedMultipartFile(b, baseStrs[0]);
   } catch (IOException e) {
      e.printStackTrace();
      return null;
   }
}

Base64:


Base64格式中,逗号前面是头部,后面是数据,如果传到后台的Base64没有头部,会报 索引越界,详见工具类代码。

实测,将8兆多的图片压缩成73kb,当然图片会失真,可以适当调整上面两个参数。

三 分析

这里不是点击图片调用ajax,而是和其他信息一起提交(也不是表单)。前端将图片转成Base64格式,也就是传到后台的数据是Base64格式的,后台需要将Base64转成MultipartFile,再调用阿里云OSS有关api(基本是封装好的工具类中)。

到此Ok


原作者:https://blog.csdn.net/ityang521/article/details/70667037

若侵权,请及时留言告知,以作修改







猜你喜欢

转载自blog.csdn.net/u014425865/article/details/80444043