java url图片压缩
时间: 2023-08-25 08:07:43 浏览: 55
可以使用Java中的ImageIO和BufferedImage类来进行图片压缩。以下是一个示例代码:
```java
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class ImageCompressor {
public static void main(String[] args) throws IOException {
File input = new File("input.jpg"); // 输入图片文件
File output = new File("output.jpg"); // 输出图片文件
BufferedImage image = ImageIO.read(input);
int width = image.getWidth();
int height = image.getHeight();
// 压缩比例
double ratio = 0.5;
// 计算压缩后的宽度和高度
int newWidth = (int) (width * ratio);
int newHeight = (int) (height * ratio);
// 创建一个新的缩放后的图片
BufferedImage newImage = new BufferedImage(newWidth, newHeight, image.getType());
// 使用Graphics2D对象进行缩放
Graphics2D g = newImage.createGraphics();
g.drawImage(image, 0, 0, newWidth, newHeight, null);
g.dispose();
// 将缩放后的图片保存到输出文件中
ImageIO.write(newImage, "jpg", output);
}
}
```
该示例将输入图片按照0.5的比例进行压缩,并将结果保存为输出图片文件。可以根据需要修改压缩比例和输出文件类型。