java上传图片的时候压缩图片和生成缩略图

1.引入上传js

<script type="text/javascript" src="/js/lib/ajaxfileupload.js"></script>

2.html内容

<input type="file" id="file" name="file" class="file"  style="opacity: 0;widht:100px;height:100px"  accept="image/*"  onchange ="uploadFile(this,'file');">
<input type="hidden" id="save_img" value=""/>

3.后台Java

//获取配置文件中的根目录
public static String getFolder() {
		if ("\\".equals(System.getProperties().getProperty("file.separator"))) {
			// windows操作系统
			String dir = ConfigUtil.getInstance().getProperty("dir.window");
			return dir;
		} else {
			// Linux/Unix操作系统
			String dir = ConfigUtil.getInstance().getProperty("dir.linux");
			return dir;
		}
	}

	//创建目录
	public static void createDirectory(String directory) {
		try {
			File f = new File(directory);
			if (!f.isDirectory()) {
				f.mkdirs();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	//上传图片
	public static String uploadFileAndCallback(MultipartFile file, Integer isThumbnails) {
		try {
			String filename = file.getOriginalFilename();
			String extName=".jpg";
			if(filename.indexOf(".")>-1){
				extName = filename.substring(filename.lastIndexOf(".")).toLowerCase();
			}
			long ctime = System.currentTimeMillis();
			String lastFileName = ctime + extName;
			String tnLastFileNmae = ctime + "_tn" + extName;
			// String lastFileName = UUID.randomUUID().toString() + extName;
			// 绝对路径
			String absPath = FileUtil.getFolder();
			// 相对路径路径
			String relPath = ConfigUtil.getInstance().getProperty("dir.file")
					+ DateUtil.dateToStr(new Date(), "yyyyMMdd/");
			// 判断目录是否存在,不存在创建
			FileUtil.createDirectory(absPath + relPath);
			log.info("file===" + file.getContentType());
			// 下载文件

			byte[] bytes = commpressPicCycle(file.getBytes(), 500, 0.8);
			FileCopyUtils.copy(bytes, new File(absPath + relPath + lastFileName));
			log.info("file===" + absPath + relPath + tnLastFileNmae);
			if(isThumbnails!=null && isThumbnails>0){
				// 生产缩略图
				Thumbnails.of(new File(absPath + relPath + lastFileName)).scale(0.3f).toFile(absPath + relPath + tnLastFileNmae);
				log.info("file===" + absPath + relPath + tnLastFileNmae);
				return relPath + tnLastFileNmae;
			}
			return relPath + lastFileName;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}

	}
// 压缩图片
	private static byte[] commpressPicCycle(byte[] bytes, long desFileSize, double accuracy) throws IOException {
		// File srcFileJPG = new File(desPath);
		long srcFileSizeJPG = bytes.length;
		// 判断大小,如果小于500kb,不压缩;如果大于等于500kb,压缩
		if (srcFileSizeJPG <= desFileSize * 1024) {
			return bytes;
		}
		// 计算宽高
		BufferedImage bim = ImageIO.read(new ByteArrayInputStream(bytes));
		int srcWdith = bim.getWidth();
		int srcHeigth = bim.getHeight();
		int desWidth = new BigDecimal(srcWdith).multiply(
				new BigDecimal(accuracy)).intValue();
		int desHeight = new BigDecimal(srcHeigth).multiply(
				new BigDecimal(accuracy)).intValue();

		ByteArrayOutputStream baos = new ByteArrayOutputStream(); //字节输出流(写入到内存)
		Thumbnails.of(new ByteArrayInputStream(bytes)).size(desWidth, desHeight).outputQuality(accuracy).toOutputStream(baos);
		return commpressPicCycle(baos.toByteArray(), desFileSize, accuracy);
	}

4.js内容

function uploadFile(obj, id) {
        var _url="/uploadImg.do";
        $.ajaxFileUpload({
            url : _url,
            secureuri : false,// 一般设置为false
            fileElementId : id,
            data:{fileId:id},
            dataType : 'json',// 返回值类型 一般设置为json
            success : function(data) // 服务器成功响应处理函数
            {
                console.log(data);
                $(".head_img").attr("src",data.desc);
                $("#save_img").val(data.desc);
            },
            error : function(data)// 服务器响应失败处理函数
            {
                console.log("服务器异常");
            }
        });
        return false;
    }
    //获取域名地址
	function getContextPath(){
        var pathName = document.location.pathname;
        var index = pathName.substr(1).indexOf("/");
        var result = pathName.substr(0,index+1);
            return '';
    }
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值