本文目录导读:

我来为您提供一个全面的Java图片处理案例,涵盖常见的图片操作。
基础图片处理工具类
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;
/**
* 图片处理工具类
*/
public class ImageProcessor {
/**
* 读取图片文件
*/
public static BufferedImage readImage(File file) throws IOException {
return ImageIO.read(file);
}
/**
* 读取网络图片
*/
public static BufferedImage readImageFromUrl(String url) throws IOException {
return ImageIO.read(new URL(url));
}
/**
* 保存图片
*/
public static void saveImage(BufferedImage image, File outputFile, String format) throws IOException {
if (!outputFile.getParentFile().exists()) {
outputFile.getParentFile().mkdirs();
}
ImageIO.write(image, format, outputFile);
}
}
图片缩放功能
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
/**
* 图片缩放处理
*/
public class ImageResizer {
/**
* 按比例缩放图片
*/
public static BufferedImage scaleByRatio(BufferedImage source, double ratio) {
int newWidth = (int) (source.getWidth() * ratio);
int newHeight = (int) (source.getHeight() * ratio);
return scale(source, newWidth, newHeight);
}
/**
* 缩放到指定宽度和高度
*/
public static BufferedImage scale(BufferedImage source, int targetWidth, int targetHeight) {
BufferedImage scaledImage = new BufferedImage(targetWidth, targetHeight,
BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = scaledImage.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(source, 0, 0, targetWidth, targetHeight, null);
g2d.dispose();
return scaledImage;
}
/**
* 等比例缩放并保持纵横比
*/
public static BufferedImage scaleToFit(BufferedImage source, int maxWidth, int maxHeight) {
int width = source.getWidth();
int height = source.getHeight();
double ratioX = (double) maxWidth / width;
double ratioY = (double) maxHeight / height;
double ratio = Math.min(ratioX, ratioY);
return scaleByRatio(source, ratio);
}
/**
* 缩略图生成
*/
public static BufferedImage createThumbnail(BufferedImage source, int thumbnailSize) {
return scaleToFit(source, thumbnailSize, thumbnailSize);
}
}
图片裁剪功能
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
/**
* 图片裁剪处理
*/
public class ImageCropper {
/**
* 普通裁剪
*/
public static BufferedImage crop(BufferedImage source, int x, int y, int width, int height) {
// 边界检查
int maxX = Math.min(x + width, source.getWidth());
int maxY = Math.min(y + height, source.getHeight());
width = maxX - x;
height = maxY - y;
if (width <= 0 || height <= 0) {
throw new IllegalArgumentException("Invalid crop dimensions");
}
BufferedImage cropped = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = cropped.createGraphics();
g2d.drawImage(source, 0, 0, width, height, x, y, maxX, maxY, null);
g2d.dispose();
return cropped;
}
/**
* 中心裁剪
*/
public static BufferedImage centerCrop(BufferedImage source, int targetWidth, int targetHeight) {
int x = Math.max(0, (source.getWidth() - targetWidth) / 2);
int y = Math.max(0, (source.getHeight() - targetHeight) / 2);
return crop(source, x, y, targetWidth, targetHeight);
}
/**
* 智能裁剪(人脸检测示例)
*/
public static BufferedImage smartCrop(BufferedImage source, int targetWidth, int targetHeight) {
// 简化版智能裁剪,实际应用中会结合人脸识别等技术
// 此处以图像中心为焦点,后续可扩展为真正的人脸检测
// 计算裁剪区域,保持一定比例
int cropWidth = Math.min(targetWidth, source.getWidth());
int cropHeight = Math.min(targetHeight, source.getHeight());
return centerCrop(source, cropWidth, cropHeight);
}
}
图片旋转功能
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Transparency;
import java.awt.image.BufferedImage;
/**
* 图片旋转处理
*/
public class ImageRotator {
/**
* 旋转90度
*/
public static BufferedImage rotate90(BufferedImage source) {
int width = source.getHeight();
int height = source.getWidth();
BufferedImage rotated = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = rotated.createGraphics();
// 旋转并绘制
g2d.rotate(Math.PI / 2, width / 2.0, height / 2.0);
g2d.drawImage(source, (width - source.getWidth()) / 2,
(height - source.getHeight()) / 2, null);
g2d.dispose();
return rotated;
}
/**
* 任意角度旋转
*/
public static BufferedImage rotate(BufferedImage source, double angleInRadians) {
int width = source.getWidth();
int height = source.getHeight();
// 计算旋转后图像的尺寸
double cos = Math.abs(Math.cos(angleInRadians));
double sin = Math.abs(Math.sin(angleInRadians));
int newWidth = (int) (width * cos + height * sin);
int newHeight = (int) (width * sin + height * cos);
BufferedImage rotated = new BufferedImage(newWidth, newHeight,
BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = rotated.createGraphics();
// 设置渲染质量
g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
// 背景色(透明)
g2d.setBackground(new java.awt.Color(0, 0, 0, 0));
g2d.clearRect(0, 0, newWidth, newHeight);
// 旋转中心
double centerX = newWidth / 2.0;
double centerY = newHeight / 2.0;
g2d.rotate(angleInRadians, centerX, centerY);
g2d.drawImage(source, (newWidth - width) / 2, (newHeight - height) / 2, null);
g2d.dispose();
return rotated;
}
/**
* 翻转图片
*/
public static BufferedImage flip(BufferedImage source, boolean horizontal) {
int width = source.getWidth();
int height = source.getHeight();
BufferedImage flipped = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = flipped.createGraphics();
if (horizontal) {
g2d.translate(width, 0);
g2d.scale(-1.0, 1.0);
} else {
g2d.translate(0, height);
g2d.scale(1.0, -1.0);
}
g2d.drawImage(source, 0, 0, null);
g2d.dispose();
return flipped;
}
}
图片滤镜效果
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.util.Random;
/**
* 图片滤镜处理
*/
public class ImageFilter {
/**
* 灰度化
*/
public static BufferedImage toGrayscale(BufferedImage source) {
BufferedImage result = new BufferedImage(source.getWidth(),
source.getHeight(),
BufferedImage.TYPE_INT_RGB);
for (int x = 0; x < source.getWidth(); x++) {
for (int y = 0; y < source.getHeight(); y++) {
int rgb = source.getRGB(x, y);
int r = (rgb >> 16) & 0xFF;
int g = (rgb >> 8) & 0xFF;
int b = rgb & 0xFF;
// 加权平均算法
int gray = (int) (0.299 * r + 0.587 * g + 0.114 * b);
Color grayColor = new Color(gray, gray, gray);
result.setRGB(x, y, grayColor.getRGB());
}
}
return result;
}
/**
* 黑白(二值化)
*/
public static BufferedImage toBlackWhite(BufferedImage source, int threshold) {
BufferedImage grayScale = toGrayscale(source);
BufferedImage result = new BufferedImage(source.getWidth(),
source.getHeight(),
BufferedImage.TYPE_INT_BYTE_BINARY);
for (int x = 0; x < source.getWidth(); x++) {
for (int y = 0; y < source.getHeight(); y++) {
int rgb = grayScale.getRGB(x, y);
int gray = (rgb >> 16) & 0xFF;
Color color = gray > threshold ? Color.BLACK : Color.WHITE;
result.setRGB(x, y, color.getRGB());
}
}
return result;
}
/**
* 浮雕效果
*/
public static BufferedImage emboss(BufferedImage source) {
int width = source.getWidth();
int height = source.getHeight();
BufferedImage result = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
for (int x = 0; x < width - 1; x++) {
for (int y = 0; y < height - 1; y++) {
int rgb = source.getRGB(x, y);
int nextRgb = source.getRGB(x + 1, y + 1);
int r = ((rgb >> 16) & 0xFF) - ((nextRgb >> 16) & 0xFF) + 128;
int g = ((rgb >> 8) & 0xFF) - ((nextRgb >> 8) & 0xFF) + 128;
int b = (rgb & 0xFF) - (nextRgb & 0xFF) + 128;
// 裁剪
r = Math.max(0, Math.min(255, r));
g = Math.max(0, Math.min(255, g));
b = Math.max(0, Math.min(255, b));
result.setRGB(x, y, new Color(r, g, b).getRGB());
}
}
return result;
}
/**
* 模糊效果(高斯模糊简化版)
*/
public static BufferedImage blur(BufferedImage source, int radius) {
int width = source.getWidth();
int height = source.getHeight();
BufferedImage result = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
int kernelSize = 2 * radius + 1;
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
int rTotal = 0, gTotal = 0, bTotal = 0;
int count = 0;
for (int dx = -radius; dx <= radius; dx++) {
for (int dy = -radius; dy <= radius; dy++) {
int nx = Math.min(width - 1, Math.max(0, x + dx));
int ny = Math.min(height - 1, Math.max(0, y + dy));
int rgb = source.getRGB(nx, ny);
rTotal += (rgb >> 16) & 0xFF;
gTotal += (rgb >> 8) & 0xFF;
bTotal += rgb & 0xFF;
count++;
}
}
int r = rTotal / count;
int g = gTotal / count;
int b = bTotal / count;
result.setRGB(x, y, new Color(r, g, b).getRGB());
}
}
return result;
}
}
图片水印功能
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
/**
* 图片水印处理
*/
public class ImageWatermarker {
/**
* 添加文字水印
*/
public static BufferedImage addTextWatermark(BufferedImage source, String text,
Font font, Color color,
float alpha, int x, int y) {
BufferedImage result = new BufferedImage(source.getWidth(),
source.getHeight(),
BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = (Graphics2D) result.getGraphics();
// 绘制原图
g2d.drawImage(source, 0, 0, null);
// 设置水印属性
g2d.setFont(font);
g2d.setColor(color);
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
// 绘制水印
g2d.drawString(text, x, y);
g2d.dispose();
return result;
}
/**
* 添加图片水印
*/
public static BufferedImage addImageWatermark(BufferedImage source,
BufferedImage watermark,
float alpha, int x, int y) {
BufferedImage result = new BufferedImage(source.getWidth(),
source.getHeight(),
BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = (Graphics2D) result.getGraphics();
// 绘制原图
g2d.drawImage(source, 0, 0, null);
// 设置透明度
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));
// 绘制水印
g2d.drawImage(watermark, x, y, null);
g2d.dispose();
return result;
}
/**
* 斜向铺满水印(防伪水印)
*/
public static BufferedImage addDiagonalWatermark(BufferedImage source,
String text, Font font) {
BufferedImage result = new BufferedImage(source.getWidth(),
source.getHeight(),
BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = (Graphics2D) result.getGraphics();
// 绘制原图
g2d.drawImage(source, 0, 0, null);
// 设置水印属性
g2d.setFont(font);
g2d.setColor(new Color(255, 255, 255));
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.3f));
g2d.rotate(Math.toRadians(-45));
// 计算铺满的水印
int width = source.getWidth();
int height = source.getHeight();
int textWidth = g2d.getFontMetrics().stringWidth(text);
int textHeight = g2d.getFontMetrics().getHeight();
for (int y = -height; y < height; y += textHeight * 3) {
for (int x = 0; x < width + textWidth; x += textWidth * 3) {
g2d.drawString(text, x, y);
}
}
g2d.dispose();
return result;
}
}
图像质量增强
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.awt.image.ConvolveOp;
import java.awt.image.Kernel;
/**
* 图像质量增强
*/
public class ImageEnhancer {
/**
* 锐化处理
*/
public static BufferedImage sharpen(BufferedImage source) {
float[] kernelData = {
0.0f, -1.0f, 0.0f,
-1.0f, 5.0f, -1.0f,
0.0f, -1.0f, 0.0f
};
Kernel kernel = new Kernel(3, 3, kernelData);
ConvolveOp convolveOp = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);
return convolveOp.filter(source, null);
}
/**
* 调整亮度
*/
public static BufferedImage adjustBrightness(BufferedImage source, int brightness) {
int width = source.getWidth();
int height = source.getHeight();
BufferedImage result = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
int rgb = source.getRGB(x, y);
int r = Math.max(0, Math.min(255, (rgb >> 16) & 0xFF + brightness));
int g = Math.max(0, Math.min(255, (rgb >> 8) & 0xFF + brightness));
int b = Math.max(0, Math.min(255, rgb & 0xFF + brightness));
result.setRGB(x, y, new java.awt.Color(r, g, b).getRGB());
}
}
return result;
}
/**
* 调整对比度
*/
public static BufferedImage adjustContrast(BufferedImage source, double contrast) {
// 仅演示,实际需要更复杂的算法
double factor = (259 * (contrast + 255)) / (255 * (259 - contrast));
int width = source.getWidth();
int height = source.getHeight();
BufferedImage result = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
int rgb = source.getRGB(x, y);
int r = (int) (factor * (((rgb >> 16) & 0xFF) - 128) + 128);
int g = (int) (factor * (((rgb >> 8) & 0xFF) - 128) + 128);
int b = (int) (factor * ((rgb & 0xFF) - 128) + 128);
r = Math.max(0, Math.min(255, r));
g = Math.max(0, Math.min(255, g));
b = Math.max(0, Math.min(255, b));
result.setRGB(x, y, new java.awt.Color(r, g, b).getRGB());
}
}
return result;
}
}
完整使用示例
import java.awt.Font;
import java.awt.Color;
import java.io.File;
public class ImageProcessingDemo {
public static void main(String[] args) {
try {
// 1. 读取原始图片
File inputFile = new File("input.jpg");
BufferedImage original = ImageProcessor.readImage(inputFile);
System.out.println("原始图片: " + original.getWidth() + "x" + original.getHeight());
// 2. 图片缩放
BufferedImage resized = ImageResizer.scaleToFit(original, 800, 600);
ImageProcessor.saveImage(resized, new File("output/resized.jpg"), "jpg");
System.out.println("缩放完成");
// 3. 创建缩略图
BufferedImage thumbnail = ImageResizer.createThumbnail(original, 150);
ImageProcessor.saveImage(thumbnail, new File("output/thumb.jpg"), "jpg");
System.out.println("缩略图完成");
// 4. 图片裁剪
BufferedImage cropped = ImageCropper.centerCrop(original, 500, 400);
ImageProcessor.saveImage(cropped, new File("output/cropped.jpg"), "jpg");
System.out.println("裁剪完成");
// 5. 旋转图片
BufferedImage rotated = ImageRotator.rotate90(original);
ImageProcessor.saveImage(rotated, new File("output/rotated.jpg"), "jpg");
System.out.println("旋转完成");
// 6. 滤镜效果
BufferedImage gray = ImageFilter.toGrayscale(original);
ImageProcessor.saveImage(gray, new File("output/gray.jpg"), "jpg");
BufferedImage blurred = ImageFilter.blur(original, 5);
ImageProcessor.saveImage(blurred, new File("output/blur.jpg"), "jpg");
System.out.println("滤镜处理完成");
// 7. 添加水印
Font font = new Font("Arial", Font.BOLD, 36);
BufferedImage watermarked = ImageWatermarker.addTextWatermark(
original, "COPYRIGHT", font, Color.WHITE, 0.5f, 50, 50);
ImageProcessor.saveImage(watermarked, new File("output/watermarked.jpg"), "jpg");
System.out.println("水印添加完成");
// 8. 质量增强
BufferedImage enhanced = ImageEnhancer.sharpen(original);
ImageProcessor.saveImage(enhanced, new File("output/sharpen.jpg"), "jpg");
System.out.println("图像增强完成");
System.out.println("所有图片处理完成!");
} catch (Exception e) {
e.printStackTrace();
}
}
}
高级应用 - 人脸检测裁剪
import java.awt.image.BufferedImage;
import java.io.File;
/**
* 集成OpenCV的人脸检测裁剪示例
*/
public class FaceDetectionCropper {
public static void main(String[] args) {
try {
// 注意:此示例需要OpenCV库支持
System.loadLibrary(org.opencv.core.Core.NATIVE_LIBRARY_NAME);
// 读取图片
BufferedImage image = ImageProcessor.readImage(new File("group_photo.jpg"));
// 使用OpenCV进行人脸检测(伪代码示例)
// 实际需要引入OpenCV的Java接口
/*
Mat mat = bufferedImageToMat(image);
CascadeClassifier faceDetector = new CascadeClassifier("haarcascade_frontalface.xml");
MatOfRect faceDetections = new MatOfRect();
faceDetector.detectMultiScale(mat, faceDetections);
Rect[] faces = faceDetections.toArray();
if (faces.length > 0) {
for (Rect rect : faces) {
// 裁剪每个人脸区域
BufferedImage faceCrop = ImageCropper.crop(image,
rect.x, rect.y, rect.width, rect.height);
ImageProcessor.saveImage(faceCrop,
new File("faces/face_" + System.currentTimeMillis() + ".jpg"), "jpg");
}
}
*/
System.out.println("人脸检测裁剪完成");
} catch (Exception e) {
e.printStackTrace();
}
}
}
图片上传处理(Web应用示例)
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Path;
import java.nio.file.Paths;
/**
* Web图片上传处理
*/
public class UploadImageProcessor {
/**
* 处理上传的图片(校验、压缩、保存)
*/
public static String processUploadImage(InputStream inputStream,
String fileName,
String uploadDir) throws IOException {
// 读取原始图片
BufferedImage original = ImageIO.read(inputStream);
// 限制最大尺寸
int maxWidth = 1920;
int maxHeight = 1080;
// 压缩图片
BufferedImage compressed = ImageResizer.scaleToFit(original, maxWidth, maxHeight);
// 生成唯一文件名
String newFileName = System.currentTimeMillis() + "_" + fileName;
Path uploadPath = Paths.get(uploadDir, newFileName);
// 保存图片
ImageIO.write(compressed, "jpg", uploadPath.toFile());
return newFileName;
}
/**
* 生成多个尺寸的图片
*/
public static void generateResponsiveImages(BufferedImage original, String fileName, String dir)
throws IOException {
// 生成原图
ImageIO.write(original, "jpg", new File(dir + "/" + fileName + "_original.jpg"));
// 生成中等尺寸
BufferedImage medium = ImageResizer.scaleToFit(original, 1280, 720);
ImageIO.write(medium, "jpg", new File(dir + "/" + fileName + "_medium.jpg"));
// 生成缩略图
BufferedImage small = ImageResizer.createThumbnail(original, 200);
ImageIO.write(small, "jpg", new File(dir + "/" + fileName + "_small.jpg"));
}
}
依赖配置(Maven)
如果使用OpenCV等库,可以在pom.xml中添加依赖:
<dependencies>
<!-- OpenCV Java接口(可选) -->
<dependency>
<groupId>org.opencv</groupId>
<artifactId>opencv</artifactId>
<version>4.8.0</version>
</dependency>
<!-- 用于读取不同格式图片 -->
<dependency>
<groupId>com.twelvemonkeys.imageio</groupId>
<artifactId>imageio-jpeg</artifactId>
<version>3.9.4</version>
</dependency>
<dependency>
<groupId>com.twelvemonkeys.imageio</groupId>
<artifactId>imageio-tiff</artifactId>
<version>3.9.4</version>
</dependency>
</dependencies>
这些案例涵盖了Java图片处理的常见需求:
- 基础操作:读取、保存、格式转换
- 几何变换:缩放、裁剪、旋转、翻转
- 滤镜效果:灰度、二值化、模糊、锐化
- 增强功能:水印、亮度/对比度调整
- 高级应用:人脸检测、智能裁剪
需要根据实际场景选择合适的处理方法,并在生产环境中注意内存管理、异步处理等问题。