控制器的方法public ResultMap fileUpload(@RequestParam("file") MultipartFile file) { String pictureName = DateUtil.getAllTime(); //获取压缩后的图片名称,随机生成 String smallerPictureName = UUID.randomUUID().toString(); try {//未压缩前的上传路径 String fileSavePath = getFileUploadPath() + "/image/" + pictureName + ".jpg"; File tempFile = new File(fileSavePath); file.transferTo(tempFile); //压缩后的路径 String smallFileSavePath = getFileUploadPath()+"/image/"+smallerPictureName+".jpg"; //获取文件大小 KB long size = file.getSize()/1024; //判断文件大小对图片质量进行压缩,尺寸不变,范围0.01~1.0,值越低压缩效率越高。图片低于600K不进行压缩 if(size>=7380){ Thumbnails.of(fileSavePath).scale(1f).outputQuality(0.01f).toFile(smallFileSavePath); tempFile.delete(); return getResultMap(SUCCESS_CODE,smallerPictureName); }else if(size>=4096&&size<7380){ Thumbnails.of(fileSavePath).scale(1f).outputQuality(0.2f).toFile(smallFileSavePath); tempFile.delete(); return getResultMap(SUCCESS_CODE,smallerPictureName); }else if(size>=1024&&size<4096){ Thumbnails.of(fileSavePath).scale(1f).outputQuality(0.3f).toFile(smallFileSavePath); tempFile.delete(); return getResultMap(SUCCESS_CODE,smallerPictureName); }else if(size>=600&&size<1024){ Thumbnails.of(fileSavePath).scale(1f).outputQuality(1f).toFile(smallFileSavePath); tempFile.delete(); return getResultMap(SUCCESS_CODE,smallerPictureName); }else{return getResultMap(SUCCESS_CODE,pictureName); } } catch (Exception e) {return getResultMap(ERROR_CODE,"图片上传失败,请稍后重试,或联系管理员"); }}HTML页面
layui.use(['form','layer','upload'], function(){var $ = layui.$, form = layui.form, upload = layui.upload, layer = layui.layer; // 上传缩略图 upload.render({elem: '.thumbBox', data: {typePicture: $('#typePicture').val(), sortPicture: $('#sortPicture').val()}, url: '/kaptcha/fileUpload', before: function(obj){//预读本地文件,如果是多文件,则会遍历。(不支持ie8/9) layer.load(); obj.preview(function(index, file, result){ $('.thumbImg').attr('src', result); }); }, done: function(res){// alert("图片上传成功吗,保存后生效"); layer.closeAll('loading'); $("#pictureId").val(res.data); $('.thumbBox').css("background","#fff"); if(res.code != 0){alert(res.data); } } });HTML页面是我目前所用的,可能会有许多不足,多多见谅!我只是一个小白
转载于:https://www.cnblogs.com/caiwx/p/11325724.html
相关资源:java后台图片压缩
转载请注明原文地址: https://mac.8miu.com/read-52688.html