压缩图片并转换为BASE64编码字符串

调用全国人口信息社会应用平台的人像比对服务,请求参数之一“公民人像BASE64编码字符串”,限制大小为30KB;

使用谷歌处理图片的开源工具(thumbnailator),可以对图片进行缩放,旋转,压缩,剪裁,添加水印,转换格式等;

jar包链接:https://pan.baidu.com/s/1NN65j0mEqkwKCryB8T8csw   提取码:n24d 

图片压缩转码示例:

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import net.coobird.thumbnailator.Thumbnails;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import sun.misc.BASE64Encoder;

public class BASE64Util {

	private static final Log logger = LogFactory.getLog(BASE64Util.class);

	private static final double accuracy = 0.95d;

	public static void main(String[] args) {
		compressPicForScale("", 30);
	}

	/**
	 * 根据指定大小压缩图片
	 * 
	 * @param imagePath
	 *            源图片地址
	 * @param fileSize
	 *            指定图片大小,单位kb
	 * @return 压缩质量后的图片BASE64转码字符串
	 */

	public static String compressPicForScale(String imagePath, long fileSize) {
		BASE64Encoder encoder = new BASE64Encoder();

		byte[] data = null;
		try {
			InputStream in = new FileInputStream(imagePath);
			data = new byte[in.available()];
			in.read(data);
			in.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

		System.out.println("原始数据大小=======" + data.length);

		if (data.length < fileSize * 1024) {
			return encoder.encode(data);
		}

		try {
			while (data.length > fileSize * 1024) {
				ByteArrayInputStream inputStream = new ByteArrayInputStream(data);
				ByteArrayOutputStream outputStream = new ByteArrayOutputStream(data.length);
				/**
				 * Thumbnails.of(InputStream... inputStreams) 从流读入源;
				 * .scale(double scale) 按比例缩放,0~1缩小,1原比例,>1放大;
				 * .scale(doublescaleWidth, double scaleHeight) 长宽各自设置比例,会拉伸;
				 * .outputQuality(double quality) 质量0.0<=quality<=1.0;
				 * .toOutputStream(OutputStream os) 无返回,写入outputStream里;
				 * 
				 */
				Thumbnails.of(inputStream).scale(accuracy)
						.outputQuality(accuracy).toOutputStream(outputStream);
				data = outputStream.toByteArray();
			}
		} catch (Exception e) {
			logger.error("图片压缩失败=======", e);
		}

		System.out.println("压缩后数据大小=======" + data.length);

		return encoder.encode(data);
	}

}

 

你可能感兴趣的:(压缩图片并转换为BASE64编码字符串)