在Java中可以使用javax.imageio包中的类来压缩图片大小而不改变图片分辨率。下面是一个压缩图片大小的示例代码:
import java.awt.Graphics2D; import java.awt.RenderingHints; 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 originalImage = ImageIO.read(new File(inputImagePath)); int originalWidth = originalImage.getWidth(); int originalHeight = originalImage.getHeight(); // 创建一个新的图像对象,并指定压缩后的宽高 BufferedImage resizedImage = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB); Graphics2D g = resizedImage.createGraphics(); // 使用抗锯齿渲染 g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); // 绘制压缩后的图像 g.drawImage(originalImage, 0, 0, newWidth, newHeight, 0, 0, originalWidth, originalHeight, null); g.dispose(); // 将压缩后的图像保存到指定路径 ImageIO.write(resizedImage, "jpg", new File(outputImagePath)); System.out.println("图片压缩成功!"); } catch (IOException ex) { System.out.println("图片压缩失败:" + ex.getMessage()); } } }
在这个示例代码中,我们首先指定了原始图片路径(inputImagePath)和压缩后图片的路径(outputImagePath),以及压缩后的宽度(newWidth)和高度(newHeight)。
然后,我们使用ImageIO类的read
方法读取原始图片,并获取原始图片的宽度和高度。
接下来,我们创建一个新的BufferedImage对象,并指定宽度和高度为压缩后的尺寸。
然后,我们使用Graphics2D对象的drawImage
方法将原始图片绘制到新的BufferedImage对象上,指定绘制的区域为压缩后的尺寸。
最后,我们使用ImageIO类的write
方法将压缩后的图像保存到指定路径。
注意,在这个示例代码中,我们使用了抗锯齿渲染(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR
),以保持压缩后的图像质量。你也可以根据需要选择其他的渲染方式。
此外,你还可以根据实际情况对压缩后的图像进行其他处理,比如调整亮度、对比度等。