使用canvas实现图片压缩上传

就不描述了,直接贴代码。有需要的朋友可以直接拿


js 部分:

// 参数,最大高度
var MAX_HEIGHT = 200;
// 渲染
function render(src) {
    // 创建一个 Image 对象
    var image = new Image();
    // 绑定 load 事件处理器,加载完成后执行
    image.onload = function () {
        // 获取 canvas DOM 对象
         var canvas = document.createElement( "canvas" );
        // 如果高度超标
        if (image.height > MAX_HEIGHT) {
            // 宽度等比例缩放 *=
            image.width *= MAX_HEIGHT / image.height;
            image.height = MAX_HEIGHT;
        }
        // 获取 canvas的 2d 环境对象,
        // 可以理解Context是管理员,canvas是房子
        var ctx = canvas.getContext( "2d" );
        // canvas清屏
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        // 重置canvas宽高
        canvas.width = image.width;
        canvas.height = image.height;
        // 将图像绘制到canvas上
        ctx.drawImage(image, 0, 0, image.width, image.height);
        // !!! 注意,image 没有加入到 dom之中
//        document.getElementById('img').src = canvas.toDataURL("image/png");
        var blob = dataURLtoBlob(canvas.toDataURL( "image/png" ));
        var fd = new FormData();
        fd.append( "image" , blob, "image.png" );
        imgCompressUpload(canvas.toDataURL( "image/png" ));
       
    };
    // 设置src属性,浏览器会自动加载。
    // 记住必须先绑定事件,才能设置src属性,否则会出同步问题。
    image.src = src;
};
// 加载 图像文件(url路径)
function loadImage(src) {
    // 过滤掉 非 image 类型的文件
    if (!src.type.match( /image.*/ )) {
        if (window.console) {
            console.log( "选择的文件类型不是图片: " , src.type);
        } else {
            window.confirm( "只能选择图片文件" );
        }
        return ;
    }
    // 创建 FileReader 对象 并调用 render 函数来完成渲染.
    var reader = new FileReader();
    // 绑定load事件自动回调函数
    reader.onload = function (e) {
        // 调用前面的 render 函数
        render(e.target.result);
    };
    // 读取文件内容
    reader.readAsDataURL(src);
};
function loadImageFile() {
  if (document.getElementById( "file" ).files.length === 0) { return ; }
  var oFile = document.getElementById( "file" ).files[0];
  loadImage(oFile)
}
function dataURLtoBlob(dataurl) {
    var arr = dataurl.split( ',' ), mime = arr[0].match( /:(.*?);/ )[1],
        bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
    while (n--){
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], {type:mime});
}
function imgCompressUpload(formData){
    $.ajax({
        url: ctxJs+ "/mob/yezhu/voice/voUservoice/uploadBase64.json" ,
        data: {base64Data: formData},
        type: "post" ,
        dataType: "json" ,
        success: function (data){
            data = JSON.parse(data);
             if (data.status == "true" ){
                 var imgSrc=data.data;
                 var imgStart= "" ;
                 var inpStart= "" ;
                $( "#imgList" ).append(imgStart+ctxJs+imgSrc+imgEnd+inpStart+imgSrc+inpEnd);
                $( "#imgList img" ).css( "height" , $( "#imgList img" ).width());
            } else {
                
            }
            console.log(data);
        },
        error: function (e){
            console.log(e);
        }
    })
}


java后台部门,楼主后台用的是StringMVC

@RequestMapping (value= "/uploadBase64" ,method=RequestMethod. POST )
    @ResponseBody public ResponseEntity base64UpLoad( @RequestParam String base64Data, HttpServletRequest                                                                                      
     request, HttpServletResponse response){ 
        try
            String dataPrix = "" ;
            String data = "" ;
            if (base64Data == null || "" .equals(base64Data)){
                throw new Exception( "上传失败,上传图片数据为空" );
            } else {
                String [] d = base64Data.split( "base64," );
                if (d != null && d. length == 2){
                    dataPrix = d[0];
                    data = d[1];
                } else {
                    throw new Exception( "上传失败,数据不合法" );
                }
            }
            String suffix = "" ;
            if ( "data:image/jpeg;" .equalsIgnoreCase(dataPrix)){ //data:image/jpeg;base64,base64编码的jpeg图片数据
                suffix = ".jpg" ;
            } else if ( "data:image/x-icon;" .equalsIgnoreCase(dataPrix)){ //data:image/x-icon;base64,base64编码的icon图片数据
                suffix = ".ico" ;
            } else if ( "data:image/gif;" .equalsIgnoreCase(dataPrix)){ //data:image/gif;base64,base64编码的gif图片数据
                suffix = ".gif" ;
            } else if ( "data:image/png;" .equalsIgnoreCase(dataPrix)){ //data:image/png;base64,base64编码的png图片数据
                suffix = ".png" ;
            } else {
                throw new Exception( "上传图片格式不合法" );
            }
           
            File fImg = buildYuLanFolder(request);
            File fileUploadurl = new File(fImg.getCanonicalPath() + "/"
                    + Math.random() + suffix);
                    
             //进行解密
             byte [] result = Base64.decodeBase64(data);
            FileCopyUtils.copy(result, fileUploadurl);
            
            String strURL = fileUploadurl.getCanonicalPath();
            System. out .println(strURL);
            strURL = strURL.substring(request.getSession()
                    .getServletContext().getRealPath( "/" ).length() - 1);
            strURL = strURL.replace( "\\" , "/" ); // 转换正反斜杠
            System. out .println( "" + strURL);
            
             return renderData( true , "ok" , strURL);
        } catch (Exception e) {
            System. out .print(e.getMessage());
             return renderMsg( false , "ng" );
        } 
       
    }


你可能感兴趣的:(js和css)