萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> JSP 程式設計

Java 圖片處理工具類:縮放、裁剪、格式轉換、灰度、文字水印、圖片水印全功能實現

功能清單

  • 縮放:按比例 / 指定寬高
  • 裁剪:座標裁剪 / 等分切片 / 固定塊大小切片
  • 格式轉換:JPG ↔ PNG ↔ GIF ↔ BMP
  • 彩色轉灰度
  • 文字水印:字體、顏色、透明度、位置可配置
  • 圖片水印:疊加圖片、透明度、位置可配置

核心工具類 (ImageUtils)

package com.example.util;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.*;
import java.io.File;
import java.io.IOException;

public class ImageUtils {

    // 常見格式常量
    public static final String FMT_JPG = "jpg";
    public static final String FMT_PNG = "png";
    public static final String FMT_GIF = "gif";
    public static final String FMT_BMP = "bmp";

    /** 1. 按比例縮放 */
    public static void scale(String srcPath, String destPath, double scale, boolean enlarge) throws IOException {
        BufferedImage src = ImageIO.read(new File(srcPath));
        int w = (int) (src.getWidth() * (enlarge ? scale : 1/scale));
        int h = (int) (src.getHeight() * (enlarge ? scale : 1/scale));
        BufferedImage dest = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = dest.createGraphics();
        g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g.drawImage(src, 0, 0, w, h, null);
        g.dispose();
        ImageIO.write(dest, getFormat(destPath), new File(destPath));
    }

    /** 2. 指定寬高縮放 (可選保持比例) */
    public static void scaleFixed(String srcPath, String destPath, int targetW, int targetH, boolean keepRatio) throws IOException {
        BufferedImage src = ImageIO.read(new File(srcPath));
        int w = targetW, h = targetH;
        if (keepRatio) {
            double ratio = Math.min((double)targetW/src.getWidth(), (double)targetH/src.getHeight());
            w = (int) (src.getWidth() * ratio);
            h = (int) (src.getHeight() * ratio);
        }
        BufferedImage dest = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = dest.createGraphics();
        g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g.drawImage(src, 0, 0, w, h, null);
        g.dispose();
        ImageIO.write(dest, getFormat(destPath), new File(destPath));
    }

    /** 3. 座標裁剪 */
    public static void crop(String srcPath, String destPath, int x, int y, int w, int h) throws IOException {
        BufferedImage src = ImageIO.read(new File(srcPath));
        BufferedImage dest = src.getSubimage(x, y, w, h);
        ImageIO.write(dest, getFormat(destPath), new File(destPath));
    }

    /** 4. 等分切片 (rows x cols) */
    public static void sliceGrid(String srcPath, String destDir, int rows, int cols) throws IOException {
        BufferedImage src = ImageIO.read(new File(srcPath));
        int tileW = src.getWidth() / cols;
        int tileH = src.getHeight() / rows;
        File dir = new File(destDir);
        dir.mkdirs();
        for (int r = 0; r < rows; r++) {
            for (int c = 0; c < cols; c++) {
                BufferedImage tile = src.getSubimage(c*tileW, r*tileH, tileW, tileH);
                ImageIO.write(tile, getFormat(srcPath), new File(dir, String.format("tile_%d_%d.%s", r, c, getFormat(srcPath))));
            }
        }
    }

    /** 5. 固定大小切片 */
    public static void sliceFixed(String srcPath, String destDir, int tileW, int tileH) throws IOException {
        BufferedImage src = ImageIO.read(new File(srcPath));
        File dir = new File(destDir);
        dir.mkdirs();
        int count = 0;
        for (int y = 0; y < src.getHeight(); y += tileH) {
            for (int x = 0; x < src.getWidth(); x += tileW) {
                int w = Math.min(tileW, src.getWidth() - x);
                int h = Math.min(tileH, src.getHeight() - y);
                BufferedImage tile = src.getSubimage(x, y, w, h);
                ImageIO.write(tile, getFormat(srcPath), new File(dir, String.format("slice_%d.%s", count++, getFormat(srcPath))));
            }
        }
    }

    /** 6. 格式轉換 */
    public static void convert(String srcPath, String destPath, String targetFormat) throws IOException {
        BufferedImage src = ImageIO.read(new File(srcPath));
        BufferedImage dest = new BufferedImage(src.getWidth(), src.getHeight(), BufferedImage.TYPE_INT_RGB);
        Graphics2D g = dest.createGraphics();
        g.drawImage(src, 0, 0, null);
        g.dispose();
        ImageIO.write(dest, targetFormat.toUpperCase(), new File(destPath));
    }

    /** 7. 灰度化 */
    public static void toGray(String srcPath, String destPath) throws IOException {
        BufferedImage src = ImageIO.read(new File(srcPath));
        ColorConvertOp op = new ColorConvertOp(ColorSpace.getInstance(ColorSpace.CS_GRAY), null);
        BufferedImage dest = op.filter(src, null);
        ImageIO.write(dest, getFormat(destPath), new File(destPath));
    }

    /** 8. 文字水印 */
    public static void watermarkText(String srcPath, String destPath, String text,
                                     String fontName, int fontStyle, Color color, int fontSize,
                                     int x, int y, float alpha) throws IOException {
        BufferedImage src = ImageIO.read(new File(srcPath));
        BufferedImage dest = new BufferedImage(src.getWidth(), src.getHeight(), BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = dest.createGraphics();
        g.drawImage(src, 0, 0, null);
        g.setFont(new Font(fontName, fontStyle, fontSize));
        g.setColor(color);
        g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));
        g.drawString(text, x, y);
        g.dispose();
        ImageIO.write(dest, getFormat(destPath), new File(destPath));
    }

    /** 9. 圖片水印 */
    public static void watermarkImage(String srcPath, String destPath, String watermarkPath,
                                      int x, int y, float alpha) throws IOException {
        BufferedImage src = ImageIO.read(new File(srcPath));
        BufferedImage mark = ImageIO.read(new File(watermarkPath));
        BufferedImage dest = new BufferedImage(src.getWidth(), src.getHeight(), BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = dest.createGraphics();
        g.drawImage(src, 0, 0, null);
        g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));
        g.drawImage(mark, x, y, null);
        g.dispose();
        ImageIO.write(dest, getFormat(destPath), new File(destPath));
    }

    private static String getFormat(String path) {
        int dot = path.lastIndexOf('.');
        return (dot > 0) ? path.substring(dot+1).toLowerCase() : FMT_JPG;
    }
}

使用範例 (main 測試)

public static void main(String[] args) throws IOException {
    String src = "e:/source.jpg";
    ImageUtils.scale(src, "e:/scale_half.jpg", 0.5, false);
    ImageUtils.scaleFixed(src, "e:/scale_300x200.jpg", 300, 200, true);
    ImageUtils.crop(src, "e:/crop.jpg", 100, 100, 400, 300);
    ImageUtils.sliceGrid(src, "e:/tiles/", 2, 3);
    ImageUtils.convert(src, "e:/converted.png", "png");
    ImageUtils.toGray(src, "e:/gray.jpg");
    ImageUtils.watermarkText(src, "e:/wm_text.jpg", "版權所有", "微軟雅黑", Font.BOLD, Color.WHITE, 48, 50, 50, 0.5f);
    ImageUtils.watermarkImage(src, "e:/wm_img.jpg", "e:/logo.png", 200, 200, 0.3f);
}

關鍵技術點補充

  • TYPE_INT_ARGB:支援透明通道,水印疊加必須用此類型,否則透明度失效。
  • AlphaComposite.SRC_OVER:標準「源覆蓋目標」混合模式,配合 alpha 實現半透明。
  • RenderingHints:`VALUE_INTERPOLATION_BILINEAR` 雙線性插值,縮放品質較好;可升級 `BICUBIC`。
  • 大圖處理:`ImageIO.read` 會將整張圖載入記憶體,超大圖 (如 10000x10000) 易 OOM。生產環境建議使用 **TwelveMonkeys ImageIO** 或 **Thumbnailator** 流式處理。
  • 字體檔案:Linux 伺服器常缺中文字體,需安裝 `fontconfig` + 真實字體檔 (`.ttf`),或將字體打包進 JAR 以 `Font.createFont()` 載入。
copyright © 萬盛學電腦網 all rights reserved