核心代码
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class A {
public static BufferedImage resize(int faceWidth, BufferedImage srcImg) throws IOException {
int imgWidth = 0;
if (faceWidth > 70 && faceWidth < 120) {
imgWidth = faceWidth * 7 / 8;
} else if (faceWidth > 60 && faceWidth < 70) {
imgWidth = faceWidth * 11 / 10;
} else if (faceWidth < 60) {
imgWidth = faceWidth * 6 / 5;
} else {
imgWidth = faceWidth * 4 / 5;
}
int imgHeight = imgWidth * srcImg.getHeight() / srcImg.getWidth();
BufferedImage resizedImg = new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_INT_RGB);
Graphics2D resizedG = resizedImg.createGraphics();
resizedImg = resizedG.getDeviceConfiguration().createCompatibleImage(imgWidth, imgHeight, Transparency.TRANSLUCENT);
resizedG.dispose();
resizedG = resizedImg.createGraphics();
Image from = srcImg.getScaledInstance(imgWidth, imgHeight, srcImg.SCALE_AREA_AVERAGING);
resizedG.drawImage(from, 0, 0, null);
resizedG.dispose();
return resizedImg;
}
public static void main(String[] args) {
try {
//读入图片
BufferedImage image = (BufferedImage) ImageIO.read(new File("C:\\Users\\Administrator\\Desktop\\zjb.png"));
//处理图片
BufferedImage resize = resize(1769, image);
//输出图片
File outputfile = new File("C:\\Users\\Administrator\\Desktop\\zjb_deal.png");
ImageIO.write(resize, "png", outputfile);
} catch (IOException e) {
e.printStackTrace();
}
}
}