Java操作长方形图片补全不失真成正方形图片

Java操作长方形图片补全不失真成正方形图片

BufferedImage image = ImageIO.read(new FileInputStream(new File("C:\\Users\\Administrator\\Desktop\\1.jpg")));
//判断宽高最大的一个值
int max=Math.max(image.getHeight(), image.getWidth());
BufferedImage outImage =  new BufferedImage(max, max,BufferedImage.TYPE_INT_RGB);
Graphics2D graphics2D = outImage.createGraphics();
outImage = graphics2D.getDeviceConfiguration().createCompatibleImage(max, max, Transparency.TRANSLUCENT);
		graphics2D.dispose();
graphics2D = outImage.createGraphics();
//原图高度
int oldheight = image.getHeight();
//原图宽度
int oldwidth = image.getWidth();
// 设置图片居中显示
graphics2D.drawImage(image, (max - oldwidth) / 2,(max - oldheight) / 2, null);
graphics2D.dispose();
//生成新的图片
ImageIO.write(outImage, "png", new File("C:\\Users\\Administrator\\Desktop\\9.png"));

你可能感兴趣的:(Java操作长方形图片补全不失真成正方形图片)