java 本地图片指定长宽,保存并覆盖以前的图片 完整代码
时间: 2024-10-17 22:08:00 浏览: 22
在Java中,处理本地图片并指定其长度和宽度通常涉及到IO流、图像处理库(如Apache Commons Imaging Library 或 JavaFX Image等)以及文件操作。以下是一个简单的示例,展示如何使用`BufferedImage`对图片进行缩放然后保存到文件,这里假设你已经添加了Apache Commons Imaging依赖:
```java
import org.apache.commons.imaging.ImageIO;
import javax.imageio.ImageIO;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class ImageResizer {
public static void main(String[] args) {
try {
// 读取原图
File originalImage = new File("path_to_your_image.jpg");
BufferedImage original = ImageIO.read(originalImage);
// 指定新的尺寸,比如宽度500像素,高度按比例缩放
int targetWidth = 500;
double aspectRatio = (double) original.getWidth() / original.getHeight();
int targetHeight = (int) Math.round(targetWidth / aspectRatio);
// 创建一个新的BufferedImage,并设置缩放后的大小
BufferedImage resized = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_INT_RGB);
Graphics2D g = resized.createGraphics();
g.drawImage(original, 0, 0, targetWidth, targetHeight, null); // 使用AffineTransform进行平移缩放
// 保存新图片
String newPath = "new_path_to_save_resized_image.jpg";
ImageIO.write(resized, "jpg", new File(newPath));
System.out.println("Image resized and saved to " + newPath);
} catch (IOException e) {
System.out.println("Error reading or writing image: " + e.getMessage());
e.printStackTrace();
}
}
}
```
阅读全文