java url图片压缩
时间: 2023-11-24 11:07:50 浏览: 96
Java 中压缩图片可以使用 ImageIO 类,具体步骤如下:
1. 通过 URL 获取图片输入流
```java
URL url = new URL("http://example.com/image.jpg");
InputStream inputStream = url.openStream();
```
2. 使用 ImageIO 读取图片
```java
BufferedImage image = ImageIO.read(inputStream);
```
3. 创建压缩后的图片缓冲区
```java
int width = image.getWidth();
int height = image.getHeight();
BufferedImage compressedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
```
4. 获取压缩后的图像输出流
```java
OutputStream outputStream = new FileOutputStream("compressed_image.jpg");
```
5. 创建 JPEGImageEncoder 对象
```java
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(outputStream);
```
6. 设置压缩参数
```java
JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(compressedImage);
param.setQuality(0.5f, false); // 压缩质量为 50%
```
7. 压缩图片并输出
```java
encoder.setJPEGEncodeParam(param);
encoder.encode(compressedImage);
```
完整代码如下:
```java
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
public class ImageCompressor {
public static void main(String[] args) throws Exception {
URL url = new URL("http://example.com/image.jpg");
InputStream inputStream = url.openStream();
BufferedImage image = ImageIO.read(inputStream);
int width = image.getWidth();
int height = image.getHeight();
BufferedImage compressedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
OutputStream outputStream = new FileOutputStream("compressed_image.jpg");
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(outputStream);
JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(compressedImage);
param.setQuality(0.5f, false);
encoder.setJPEGEncodeParam(param);
encoder.encode(compressedImage);
}
}
```
阅读全文