这个确实牛逼。是我在网上找的,我复制过来的。附上原文链接https://luoyahu.iteye.com/blog/1312043
但是,一些老的Java代码在JDK1.7下编译会报错,比如这个:程序包com.sun.image.codec.jpeg不存在。
[javac] D:\work\mpa\hyjc2\src\hyjc\image\ImageUtil.java:87: 错误: 找不到符号
因为都使用统一的ImageIO进行图像格式文件的读写,没有必要使用过时的实现类JPEGImageEncoder类。所以我在原文的基础上改了一下。
【先说一下我的应用背景:我是将一张1024*575的手写签名图片缩小到高度是60(试了两个接口,这个最清晰),再调用接口识别这个手写签名 也就很容易了(要识别这个手写签名就要缩小到这么大小才行)】
import javax.swing.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.Kernel;
import java.awt.image.ConvolveOp;
/**
* 改变图片尺寸
* @param originalFile原图片
* @param resizedFile缩小后图片路径
* @param newWidth缩小后图片高度
* @param quality
* @throws IOException
*/
public static void resize(File originalFile, String resizedFile,
int newWidth, float quality) throws IOException {
if (quality > 1) {
throw new IllegalArgumentException(
"Quality has to be between 0 and 1");
}
ImageIcon ii = new ImageIcon(originalFile.getCanonicalPath());
Image i = ii.getImage();
Image resizedImage = null;
int iWidth = i.getWidth(null);
int iHeight = i.getHeight(null);
if (iWidth > iHeight) {
resizedImage = i.getScaledInstance(newWidth, (newWidth * iHeight)
/ iWidth, Image.SCALE_SMOOTH);
} else {
resizedImage = i.getScaledInstance((newWidth * iWidth) / iHeight,
newWidth, Image.SCALE_SMOOTH);
}
// This code ensures that all the pixels in the image are loaded.
Image temp = new ImageIcon(resizedImage).getImage();
// Create the buffered image.
BufferedImage bufferedImage = new BufferedImage(temp.getWidth(null),
temp.getHeight(null), BufferedImage.TYPE_INT_RGB);
// Copy image to buffered image.
Graphics g = bufferedImage.createGraphics();
// Clear background and paint the image.
g.setColor(Color.white);
g.fillRect(0, 0, temp.getWidth(null), temp.getHeight(null));
g.drawImage(temp, 0, 0, null);
g.dispose();
// Soften.
float softenFactor = 0.05f;
float[] softenArray = { 0, softenFactor, 0, softenFactor, 1 - (softenFactor * 4), softenFactor, 0, softenFactor, 0 };
Kernel kernel = new Kernel(3, 3, softenArray);
ConvolveOp cOp = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);
bufferedImage = cOp.filter(bufferedImage, null);
String formatName = resizedFile.substring(resizedFile.lastIndexOf(".") + 1);
ImageIO.write(bufferedImage, formatName, new File(resizedFile));
}
调用,如:
resize(originalImage, new File("c:\\1207-0.jpg"),150, 0.7f);
resize(originalImage, new File("c:\\1207-1.jpg"),150, 1f);