在本文中,我将向您展示如何在 Java 中更改图像的大小。
ImageIO 提供了在 Java 中读取和写入图像的功能,并支持图像处理。同时,我还会介绍如何使用 JDeli 图像库进行图像缩放。
如何使用 ImageIO 缩放图像
- 创建指向原始图像的文件句柄、输入流或 URL。
- 使用 ImageIO 将图像读取为
BufferedImage对象。 - 创建一个新的
BufferedImage,设置为调整后的尺寸。 - 创建一个变换对象。
- 应用变换。
以下是使用 ImageIO 缩放图像的 Java 代码:
File imageFile = new File("C:\path\to\pdf\image.tif");
BufferedImage image = ImageIO.read(imageFile);
final int w = image.getWidth();
final int h = image.getHeight();
BufferedImage scaledImage = new BufferedImage((w * 2), (h * 2), BufferedImage.TYPE_INT_ARGB);
final AffineTransform at = AffineTransform.getScaleInstance(2.0, 2.0);
final AffineTransformOp ato = new AffineTransformOp(at, AffineTransformOp.TYPE_BICUBIC);
scaledImage = ato.filter(image, scaledImage);
如何使用 JDeli 缩放图像
- 将 JDeli 添加到项目的类路径或模块路径中(在此处下载试用版的 jar 文件)。
- 创建一个文件或输入流来指向原始图像。也可以使用包含图像数据的字节数组(
byte[])。 - 将图像读取为
BufferedImage对象。 - 创建一个变换操作对象。
- 应用变换。
以下是使用 JDeli 缩放图像的 Java 代码:
File imageFile = new File("C:\path\to\pdf\exampleImage.tif");
BufferedImage image = JDeli.read(imageFile);
ImageProcessingOperations operations = new ImageProcessingOperations();
operations.scale(scalingFactor);
image = JDeli.process(ImageProcessingOperations operations, BufferedImage image);
通过以上方法,您可以在 Java 中方便地调整图像大小,无论是使用原生的 ImageIO 还是功能更强大的 JDeli 图像库。