java使用Graphics2D压缩图片
时间: 2023-11-02 14:05:23 浏览: 191
要使用Java的Graphics2D类压缩图片,你可以按照以下步骤:
1. 加载要压缩的图片,可以使用ImageIO类:
```java
BufferedImage originalImage = ImageIO.read(new File("path/to/image"));
```
2. 创建一个新的BufferedImage对象,设置它的宽度和高度为原始图像的一半,或者其他你想要的压缩比例:
```java
int originalWidth = originalImage.getWidth();
int originalHeight = originalImage.getHeight();
int newWidth = originalWidth / 2; // 压缩一半
int newHeight = originalHeight / 2; // 压缩一半
BufferedImage compressedImage = new BufferedImage(newWidth, newHeight, originalImage.getType());
```
3. 获取Graphics2D对象,用它来绘制压缩后的图像:
```java
Graphics2D g2d = compressedImage.createGraphics();
g2d.drawImage(originalImage, 0, 0, newWidth, newHeight, null);
g2d.dispose();
```
4. 最后,将压缩后的图像保存到文件或输出流中,可以使用ImageIO类:
```java
ImageIO.write(compressedImage, "jpg", new File("path/to/compressed/image.jpg"));
```
完整的代码:
```java
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
public class ImageCompressor {
public static void main(String[] args) throws Exception {
BufferedImage originalImage = ImageIO.read(new File("path/to/image"));
int originalWidth = originalImage.getWidth();
int originalHeight = originalImage.getHeight();
int newWidth = originalWidth / 2; // 压缩一半
int newHeight = originalHeight / 2; // 压缩一半
BufferedImage compressedImage = new BufferedImage(newWidth, newHeight, originalImage.getType());
Graphics2D g2d = compressedImage.createGraphics();
g2d.drawImage(originalImage, 0, 0, newWidth, newHeight, null);
g2d.dispose();
ImageIO.write(compressedImage, "jpg", new File("path/to/compressed/image.jpg"));
}
}
```
阅读全文