JAVA - 图片压缩上传

问题:  

     最近写项目的时候遇到一个这样的问题,在对接第三方接口的时候需要传输图片,比如身份证、营业执照、办公场所等....但是对方的接口又做了限制,最大只接收200k的图片。小编这时候就头疼了,现在的图片一般不都是几兆几兆的高清图吗,比如随便用手机拍个照片都是一两兆。然后小编翻阅了很多资料,最终觉得还是下面这种比较实用。

①图片上传:(方法返回值以及OSS上传,方法名都可以忽略)

   //图片两百K压缩上传
	public static ResponseResult uploadImg2O0KImg(String source, String folderName, String fileName, String envActive, MultipartFile multipartfile) throws Exception {
		if (multipartfile.getSize() > 50 * 1024 * 1024) {
			throw new Exception("上传图片大小不能超过10M!");
		}
		String filePath = envActive+"/"+source+"/"+folderName;
		//设置统一图片后缀名
		String suffixName;

		//获取图片文件名(不带扩展名的文件名)
		String prefixName = getFileNameWithoutEx(multipartfile.getOriginalFilename());

		//获取图片后缀名,判断如果是png的话就不进行格式转换,因为Thumbnails存在转png->jpg图片变红bug
		String suffixNameOrigin = getExtensionName(multipartfile.getOriginalFilename());

		if ("png".equals(suffixNameOrigin)) {
			suffixName = "png";
		} else {
			suffixName = "jpg";
		}
		BufferedImage image = ImageIO.read(multipartfile.getInputStream());
		BufferedImage output = Thumbnails.of(image).size(image.getWidth(), image.getHeight()).asBufferedImage();
		String base64Str =  imageToBase64(output);
                //循环判断是否大于200k[性能方面的话,可能有点差]
		while (base64Str.length() - base64Str.length() / 8 * 2 > 200000) {  //200k
			 output = Thumbnails.of(output).outputQuality(1f).scale(0.9f).asBufferedImage();
			 base64Str = imageToBase64(output);
		}
		BASE64Decoder decoder = new BASE64Decoder();
		byte[] bytes = decoder.decodeBuffer(base64Str);
		ByteArrayInputStream in = new ByteArrayInputStream(bytes);
			//设置图片存储在oss上的名字
	        if (fileName == null) {
			fileName = Long.toString(System.currentTimeMillis()) + "."+suffixName;
		} else {
			fileName = fileName + "."+suffixName;
		}
		//上传OSS
		OSSClient client = new OSSClient(endpoint, accessKeyId, accessKeySecret);

		client.putObject(bucketName, filePath+"/"+fileName, in);
		String path = "https://xinyifu-soho.oss-cn-shanghai.aliyuncs.com/"+filePath+"/"+fileName;

		return CommonResponseUtils.successResponse("上传成功",path);

	};

②图片转Base64

	public static String imageToBase64(BufferedImage bufferedImage) {
		BASE64Encoder encoder = new BASE64Encoder();
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		try {
			ImageIO.write(bufferedImage, "jpg", baos);
		} catch (IOException e) {
			e.fillInStackTrace();
		}
		return new String(encoder.encode((baos.toByteArray())));
	}

③文件名/文件后缀名

/**
	 * 获取文件扩展名
	 *
	 * @param filename 文件名
	 * @return
	 */
	public static String getExtensionName(String filename) {
		if ((filename != null) && (filename.length() > 0)) {
			int dot = filename.lastIndexOf('.');
			if ((dot > -1) && (dot < (filename.length() - 1))) {
				return filename.substring(dot + 1);
			}
		}
		return filename;
	}
	/**
	 * 获取不带扩展名的文件名
	 *
	 * @param filename 文件
	 * @return
	 */
	private static String getFileNameWithoutEx(String filename) {
		if ((filename != null) && (filename.length() > 0)) {
			int dot = filename.lastIndexOf('.');
			if ((dot > -1) && (dot < (filename.length()))) {
				return filename.substring(0, dot);
			}
		}
		return filename;
	}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值