Java图像处理:从读取到处理

面向初学者的在线Python训练器

轻松学习Python,无需理论负担。在浏览器中直接解决带自动检查的实践任务,无需安装任何东西。

开始课程

Java图像处理:库与实战示例



Java提供了强大的内置工具用于处理位图图像。本文将介绍标准库javax.imageio、包java.awt.image以及流行的第三方库Thumbnailator。您将学习如何读取、保存、缩放、应用滤镜以及转换图像格式。



1. 基础:javax.imageio包与BufferedImage



内存中表示图像的关键类是BufferedImage。它允许您获取和修改像素,处理不同的色彩模型(RGB、ARGB)和数据类型。



从文件读取图像



import javax.imageio.ImageIO;import java.awt.image.BufferedImage;import java.io.File;import java.io.IOException;

public class ImageReadExample { public static void main(String[] args) { try { File inputFile = new File("input.jpg"); BufferedImage image = ImageIO.read(inputFile); System.out.println("宽度: " + image.getWidth()); System.out.println("高度: " + image.getHeight()); System.out.println("类型: " + image.getType()); } catch (IOException e) { e.printStackTrace(); } }}


将图像写入文件



File outputFile = new File("output.png");ImageIO.write(image, "png", outputFile); // 格式根据扩展名确定


支持的格式:JPEG、PNG、BMP、WBMP、GIF(仅读取)。完整列表可通过ImageIO.getReaderFormatNames()获取。



2. 使用Java 2D进行缩放和变换



java.awt.Graphics2D包允许您进行高质量的缩放、旋转、镜像和图像叠加。



保持比例的缩放



import java.awt.Graphics2D;import java.awt.RenderingHints;import java.awt.image.BufferedImage;

public class ImageResizer { public static BufferedImage resize(BufferedImage original, int targetWidth, int targetHeight) { BufferedImage resized = new BufferedImage(targetWidth, targetHeight, original.getType()); Graphics2D g2d = resized.createGraphics(); // 启用抗锯齿以获得更好的质量 g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2d.drawImage(original, 0, 0, targetWidth, targetHeight, null); g2d.dispose(); return resized; }}


将图像旋转90度



public static BufferedImage rotate(BufferedImage image, double angleDegrees) {    double radians = Math.toRadians(angleDegrees);    int w = image.getWidth();    int h = image.getHeight();        // 旋转后的新尺寸    int newW = (int) Math.abs(w * Math.cos(radians)) + (int) Math.abs(h * Math.sin(radians));    int newH = (int) Math.abs(h * Math.cos(radians)) + (int) Math.abs(w * Math.sin(radians));        BufferedImage rotated = new BufferedImage(newW, newH, BufferedImage.TYPE_INT_ARGB);    Graphics2D g2d = rotated.createGraphics();    g2d.translate((newW - w) / 2.0, (newH - h) / 2.0);    g2d.rotate(radians, w / 2.0, h / 2.0);    g2d.drawImage(image, 0, 0, null);    g2d.dispose();    return rotated;}


3. 应用滤镜:模糊、对比度、亮度



对于滤镜,请使用BufferedImageOp(来自java.awt.image包)。最有用的实现包括:



    \

推荐