Java图像处理:库、工具与代码示例
Java为图形处理提供了强大的内置工具,以及丰富的第三方库生态系统。本文将介绍在Java中加载、处理、转换和保存图像的主要方法——从标准类javax.imageio和java.awt到简化开发工作的流行库。
1. 标准工具:javax.imageio 和 java.awt.image
Java中基本的位图图像处理基于javax.imageio包(加载/保存)和java.awt.image包(像素处理)。核心类是BufferedImage,它将图像存储在内存中。
加载和保存图像
import javax.imageio.ImageIO;import java.awt.image.BufferedImage;import java.io.File;import java.io.IOException;
public class ImageExample { public static void main(String[] args) throws IOException { // 从文件加载图像 BufferedImage image = ImageIO.read(new File("input.jpg")); System.out.println("宽度: " + image.getWidth() + ", 高度: " + image.getHeight());
// 保存为其他格式 ImageIO.write(image, "png", new File("output.png")); }}ImageIO支持的格式包括:JPEG、PNG、BMP、WBMP、GIF(仅读取)。要扩展格式列表,请使用ImageIO插件(例如TwelveMonkeys)。
调整大小(手动方式)
import java.awt.Graphics2D;import java.awt.RenderingHints;import java.awt.image.BufferedImage;
public static BufferedImage resize(BufferedImage original, int newWidth, int newHeight) { BufferedImage resized = new BufferedImage(newWidth, newHeight, original.getType()); Graphics2D g2d = resized.createGraphics(); g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g2d.drawImage(original, 0, 0, newWidth, newHeight, null); g2d.dispose(); return resized;}2. Java 2D API:绘图与滤镜
Graphics2D类不仅可以缩放,还可以应用效果、旋转、裁剪图像,以及添加文本和几何图形。
添加水印
public static BufferedImage addWatermark(BufferedImage source, String text) { BufferedImage result = new BufferedImage(source.getWidth(), source.getHeight(), source.getType()); Graphics2D g2d = result.createGraphics(); g2d.drawImage(source, 0, 0, null); g2d.setColor(new Color(255, 255, 255, 128)); g2d.setFont(new Font("Arial", Font.BOLD, 40)); g2d.drawString(text, 20, source.getHeight() - 20); g2d.dispose(); return result;}应用颜色滤镜(棕褐色)
public static BufferedImage applySepia(BufferedImage img) { int width = img.getWidth(); int height = img.getHeight(); BufferedImage sepia = new BufferedImage(width, height, img.getType());
for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { int rgb = img.getRGB(x, y); int r = (rgb >> 16) & 0xFF; int g = (rgb >> 8) & 0xFF; int b = rgb & 0xFF;
int newR = (int) (0.393 * r + 0.769 * g + 0.189 * b); int newG = (int) (0.349 * r + 0.686 * g + 0.168 * b); int newB = (int) (0.272 * r + 0.534 * g + 0.131 * b);
newR = Math.min(255, newR); newG = Math.min(255, newG); newB = Math.min(255, newB);
int newPixel = (0xFF << 24) | (newR << 16) | (newG << 8) | newB; sepia.setRGB(x, y, newPixel); } } return sepia;}