1.背景
记录下,方便随时取用。
大部分互联网厂商对OCR接口,有图片大小的限制,现在大多数手机像素都不低,因此如果想对接OCR接口,无损的压缩图片是很有必要的。
图片过大,识别的也慢。
2.代码
压缩比例:scale
File img = new File(sourcePath);
BufferedImage templateImage = ImageIO.read(img);
//原始图片的长度和宽度
int height = templateImage.getHeight();
int width = templateImage.getWidth();
//通过比例压缩
float scale = 0.85f;
//通过固定长度压缩
//压缩之后的长度和宽度
int doWithHeight = (int) (scale * height);
int dowithWidth = (int) (scale * width);
BufferedImage finalImage =
new BufferedImage(dowithWidth, doWithHeight, BufferedImage.TYPE_INT_RGB);
finalImage
.getGraphics()
.drawImage(templateImage.getScaledInstance(dowithWidth, doWithHeight, java.awt.Image.SCALE_SMOOTH), 0, 0, null);
//图片输出路径,以及图片名
FileOutputStream fileOutputStream =
new FileOutputStream(basePath + appId + "/scale-" + img.getName());
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(fileOutputStream);
encoder.encode(finalImage);
fileOutputStream.close();