JAVA 处理目录下及子目录下 图片压缩和图片加水印

本文介绍了如何使用JAVA编程语言,配合thumbnailator库处理目录下的图片,包括压缩图片至指定尺寸并添加水印,同时支持子目录的递归处理。
摘要由CSDN通过智能技术生成

JAVA 处理目录下及子目录下图片压缩

压缩需要用到其他jar包

<dependency>
    <groupId>net.coobird</groupId>
    <artifactId>thumbnailator</artifactId>
    <version>0.4.14</version>
</dependency>

处理目录下及子目录下图片压缩

import net.coobird.thumbnailator.Thumbnails;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;

public class ImageProcessor3 {

    public static void main(String[] args) {
        // 图片存放目录地址
        String imgPath = "/test/inputImg";
        // 输出目录
        String outPath = "/test/outImg";
        // 水印
        String watermarkText = "水印内容";

        File directory = new File(imgPath);
        processFilesInDirectory(directory, outPath, imgPath, watermarkText);

    }

    private static void processFilesInDirectory(File directory, String outPath, String imgPath, String watermarkText) {
        if (directory.isDirectory()) {
            File[] files = directory.listFiles();

            if (files != null) {
                for (int i=0; i<files.length;i++) {
                    File file = files[i];
                    if (file.isDirectory()) {
                        // 递归处理子目录
                        processFilesInDirectory(file, outPath, imgPath, watermarkText);
                    } else if (isImageFile(file)) {
                        try {
                            // 压缩图片
                            String replaceOutPath = file.getPath().replace(imgPath, outPath);
                            replaceOutPath = replaceOutPath.substring(0,replaceOutPath.length()-file.getName().length());
                            compressImage(file, new File(replaceOutPath));
                            // 添加水印
                            String imagePath = addWatermark(new File(file.getPath().replace(imgPath, outPath)), new File(replaceOutPath), watermarkText);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }


    private static boolean isImageFile(File file) {
        String name = file.getName().toLowerCase();
        return name.endsWith(".jpg") || name.endsWith(".jpeg") || name.endsWith(".png");
    }

    /**
     * 添加水印
     * @param imageFile
     * @param outputDirectory
     * @throws IOException
     */
    private static String addWatermark(File imageFile, File outputDirectory, String watermarkText) throws IOException {
        BufferedImage originalImage = ImageIO.read(imageFile);
        int width = originalImage.getWidth();
        int height = originalImage.getHeight();

        BufferedImage watermarkedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = watermarkedImage.createGraphics();
        g2d.drawImage(originalImage, 0, 0, null);

        // Add watermark text
        Font font = new Font("Arial", Font.BOLD, 60);
        g2d.setFont(font);
        FontMetrics fontMetrics = g2d.getFontMetrics();
        int textWidth = fontMetrics.stringWidth(watermarkText);
        int textHeight = fontMetrics.getHeight();

        // Calculate the position for the watermark
        int x = (width - textWidth) / 2;
        int y = (height + textHeight) / 2;

        // Rotate the text
        g2d.rotate(Math.toRadians(-45), x + textWidth / 2, y - textHeight / 2);

        // 设置颜色为白色,透明度 100
        g2d.setColor(new Color(255, 255, 255, 100));
        g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

        // Draw the text
        g2d.drawString(watermarkText, x, y);

        g2d.dispose();

        String path = outputDirectory.getPath() + File.separator + imageFile.getName();

        File outputImageFile = new File(path);
        ImageIO.write(watermarkedImage, "jpg", outputImageFile);
        return path;
    }

    /**
     * 图片压缩
     * @param imageFile
     * @param outputDirectory
     * @throws IOException
     */
    private static void compressImage(File imageFile, File outputDirectory) throws IOException {
        if (!outputDirectory.isDirectory()) {
            outputDirectory.mkdir();
        }
        File compressedImageFile = new File(outputDirectory.getPath() + File.separator + imageFile.getName());
        OutputStream os = new FileOutputStream(compressedImageFile);

        Thumbnails.of(imageFile)
                .size(800, 600)
                .outputQuality(0.8)
                .toOutputStream(os);

        os.close();
    }

}
  • 6
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java 中,图片压缩和添文字水印通常涉及到图像处理库,如Apache Commons Imaging、ImageIO等。以下是基本步骤: 1. **图片压缩**: - 使用 `BufferedImage` 类图片。 - 调用 `getScaledInstance()` 或 `rescaleWidthHeight()` 函数调整图片尺寸,减少宽度和高度,达到压缩效果。 - 将压缩后的 `BufferedImage` 写入一个新的文件。 ```java import javax.imageio.ImageIO; import java.awt.geom.AffineTransform; import java.awt.image.BufferedImage; public BufferedImage compressImage(BufferedImage original, int newWidth, int newHeight) { // 压缩比例 double scale = Math.min((double)newWidth / original.getWidth(), (double)newHeight / original.getHeight()); AffineTransform at = new AffineTransform(); at.scale(scale, scale); at.translate(-(newWidth * scale - original.getWidth()) / 2, -(newHeight * scale - original.getHeight()) / 2); BufferedImage resized = new BufferedImage(newWidth, newHeight, original.getType()); Graphics2D g = resized.createGraphics(); g.drawImage(original, at, null); g.dispose(); return resized; } ``` 2. **文字水印**: - 使用 `Font` 和 `Graphics2D` 绘制文字到压缩后的图片上。 - 确定文字的位置,可以放在图片的右下角或其他自定义位置。 ```java public void addWatermark(BufferedImage image, String watermarkText, Color color, float x, float y) { Graphics2D g = image.createGraphics(); Font font = new Font("Arial", Font.BOLD, 16); g.setFont(font); g.setColor(color); g.drawString(watermarkText, (int)x, (int)y); g.dispose(); } ``` 将这两个方法结合起来,先压缩图片再添文字水印: ```java BufferedImage original = ImageIO.read(new File("input.jpg")); BufferedImage watermarked = compressImage(original, 800, 600); // 假设目标大小为800x600 addWatermark(watermarked, "这是水印", Color.YELLOW, 750, 550); // 文字位置在右下角 ImageIO.write(watermarked, "jpg", new File("output.jpg")); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值