java压缩图片至指定大小
时间: 2023-11-12 22:19:44 浏览: 50
要将Java中的图像压缩到指定大小,可以使用Java的ImageIO和ImageWriter类。以下是一个示例代码,可以将图像压缩到指定大小:
```java
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriter;
import javax.imageio.stream.FileImageOutputStream;
import javax.imageio.stream.ImageOutputStream;
public class ImageIOExample {
public static void main(String[] args) throws Exception {
File input = new File("input.png");
BufferedImage image = ImageIO.read(input);
// 限制图像的宽度和高度
int maxWidth = 800;
int maxHeight = 600;
int width = image.getWidth();
int height = image.getHeight();
if (width > maxWidth || height > maxHeight) {
float ratio = Math.min((float)maxWidth / width, (float)maxHeight / height);
width = (int)(width * ratio);
height = (int)(height * ratio);
BufferedImage resized = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = resized.createGraphics();
g2d.drawImage(image, 0, 0, width, height, null);
g2d.dispose();
image = resized;
}
// 压缩图像
File output = new File("output.png");
ImageWriter writer = ImageIO.getImageWritersByFormatName("png").next();
ImageOutputStream ios = new FileImageOutputStream(output);
writer.setOutput(ios);
writer.write(null, new javax.imageio.IIOImage(image, null, null), null);
ios.close();
writer.dispose();
}
}
```
在这个例子中,我们首先读取一个名为 "input.png" 的图像文件,并将其限制在800x600的大小范围内。如果图像的宽度或高度超过了限制,则缩小图像以适应限制。然后,我们将图像压缩为PNG格式,并将其保存在名为 "output.png" 的文件中。这个例子中的压缩质量是默认的,您可以根据需要更改压缩质量。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)