Java如何压缩照片为指定像素大小
你可以使用Java的图像处理库来压缩照片为指定像素大小。下面是一个示例代码:
import java.awt.Graphics2D;
import java.awt.Image;
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) {
String inputImagePath = "input.jpg";
String outputImagePath = "output.jpg";
int newWidth = 800;
int newHeight = 600;
try {
BufferedImage inputImage = ImageIO.read(new File(inputImagePath));
BufferedImage outputImage = new BufferedImage(newWidth, newHeight, inputImage.getType());
Graphics2D graphics2D = outputImage.createGraphics();
graphics2D.drawImage(inputImage, 0, 0, newWidth, newHeight, null);
graphics2D.dispose();
ImageIO.write(outputImage, "jpg", new File(outputImagePath));
System.out.println("Image compressed successfully!");
} catch (IOException ex) {
System.out.println("Error while compressing image.");
ex.printStackTrace();
}
}
}
你需要将inputImagePath变量替换为你要压缩的照片路径,outputImagePath变量替换为压缩后的照片路径,newWidth和newHeight变量替换为你想要的像素大小。这个示例将会将照片压缩为800x600像素大小。压缩后的照片将会保存在outputImagePath指定的路径中
原文地址: http://www.cveoy.top/t/topic/iMjB 著作权归作者所有。请勿转载和采集!