java 如何在不修改原始内容的情况下,进行填充至目标尺寸
时间: 2024-03-01 07:52:30 浏览: 37
在Java中可以使用ImageIO类和BufferedImage类实现在不修改原始内容的情况下进行填充至目标尺寸。
具体步骤如下:
1. 读取原始图片
```java
File file = new File("original.jpg");
BufferedImage originalImage = ImageIO.read(file);
```
2. 创建目标尺寸的图片
```java
int targetWidth = 800; // 目标宽度
int targetHeight = 600; // 目标高度
BufferedImage targetImage = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_INT_RGB);
```
3. 填充原始内容至目标尺寸
```java
Graphics2D g = targetImage.createGraphics();
g.setBackground(Color.WHITE); // 设置背景色为白色
g.clearRect(0, 0, targetWidth, targetHeight); // 清空画布
int x = (targetWidth - originalImage.getWidth()) / 2; // 计算X轴偏移量
int y = (targetHeight - originalImage.getHeight()) / 2; // 计算Y轴偏移量
g.drawImage(originalImage, x, y, null); // 填充原始内容
g.dispose();
```
4. 将目标尺寸的图片保存到文件
```java
File output = new File("target.jpg");
ImageIO.write(targetImage, "jpg", output);
```
这样就可以实现在不修改原始内容的情况下,将图片填充至目标尺寸。