js压缩图片

<form action="test/img.do" method="post" enctype='multipart/form-data'>
        <input type="file" name="file" id="file"/>
        <img src="" id="img" width="50px" height="50px"/>
        <input type="submit" value="上传">
        <input type="button" value="上" οnclick="sc()"> 
    </form>

function sc() {
        var url = $("img").attr("src");
        console.log(url);
        $.ajax({
            type: "post",
            url: "test/img.do",
            data:{ "str":url },    //传入已封装的参数
            dataType: "json",
            timeout: 10000,
            success: function(result) {
                console.log(123);
            }
        });
    }

 var oInput = document.getElementById ( 'file' )
    var oImg = document.getElementById("img");
    oInput.onchange = function(){
        var fileData = oInput.files[ 0 ];
        base64(fileData,function(base64Data){
            //base64Data:处理成功返回的图片base64
            oImg.setAttribute("src",base64Data);
        });
    }

    function base64(file,backData){
        /*
         * file:input上传图片
         * backData:处理完成回调函数
         * */
        var reader = new FileReader();
        var image = new Image();
        var canvas = createCanvas();
        var ctx = canvas.getContext("2d");
        reader.onload = function(){ // 文件加载完处理
            var result = this.result;
            image.onload = function(){ // 图片加载完处理
                var imgScale = imgScaleW(1000,this.width,this.height);
                canvas.width = imgScale.width;
                canvas.height = imgScale.height;
                ctx.drawImage(image,0,0,imgScale.width,imgScale.height);
                var dataURL = canvas.toDataURL('image/jpeg'); // 图片base64
                ctx.clearRect(0,0,imgScale.width,imgScale.height); // 清除画布
                backData (dataURL); //dataURL:处理成功返回的图片base64
            }
            image.src = result;
        };
        reader.readAsDataURL(file);
    }

    function createCanvas(){ // 创建画布
        var canvas = document.getElementById('canvas');
        if(!canvas){
            var canvasTag = document.createElement('canvas');
            canvasTag.setAttribute('id','canvas');
            canvasTag.setAttribute('style','display:none;');//隐藏画布
            document.body.appendChild(canvasTag);
            canvas = document.getElementById('canvas');
        }
        return canvas;
    }

    function imgScaleW(maxWidth,width,height){
        /* maxWidth:宽度或者高度最大值
         * width:宽度
         * height:高度
         * */
        var imgScale = {};
        var w = 0;
        var h = 0;
        if(width <= maxWidth && height <= maxWidth){ // 如果图片宽高都小于限制的最大值,不用缩放
            imgScale = {
                width:width,
                height:height
            }
        }else{
            if(width >= height){ // 如果图片宽大于高
                w = maxWidth;
                h = Math.ceil(maxWidth * height / width);
            }else{     // 如果图片高大于宽
                h = maxWidth;
                w = Math.ceil(maxWidth * width / height);
            }
            imgScale = {
                width:w,
                height:h
            }
        }
        return imgScale;
    }

 

@RequestMapping("/img.do")
    @ResponseBody
    //HttpServletRequest request
    public void insertBrand(String str) {
//        String str = request.getParameter("str");
        // 通过base64来转化图片
        str = str.replaceAll("data:image/jpeg;base64,", "");      
        BASE64Decoder decoder = new BASE64Decoder();
        // Base64解码      
        byte[] imageByte = null;
        try {
            imageByte = decoder.decodeBuffer(str);      
            for (int i = 0; i < imageByte.length; ++i) {      
                if (imageByte[i] < 0) {// 调整异常数据      
                    imageByte[i] += 256;      
                }      
            }      
        } catch (Exception e) {
             e.printStackTrace(); 
        }   
        
        
        // 生成文件名
        String files = new SimpleDateFormat("yyyyMMddHHmmssSSS")
                .format(new Date())
                + (new Random().nextInt(9000) % (9000 - 1000 + 1) + 1000)
                + ".png";
        // 生成文件路径
        String filename = url + files;     
        try {
            // 生成文件         
            File imageFile = new File(filename);
            imageFile.createNewFile();
               if(!imageFile.exists()){
                   imageFile.createNewFile();
                }
                OutputStream imageStream = new FileOutputStream(imageFile);
                imageStream.write(imageByte);
                imageStream.flush();
                imageStream.close();                    
        } catch (Exception e) {         
            e.printStackTrace();
        }
    };

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值