首页 > 编程语言 >JAVA 处理目录下及子目录下 图片压缩和图片加水印

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

时间:2024-04-09 17:01:02浏览次数:18  
标签:JAVA String 下及 imgPath File directory import 目录 图片

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();
    }

}

标签:JAVA,String,下及,imgPath,File,directory,import,目录,图片
From: https://blog.csdn.net/Ls66666Ls/article/details/137558961

相关文章

  • java基础的一小点
    java文件启动的一套流程:.java---通过编译器javac---->.class---经过解释器&JIT--->机器码--->电脑可识别运行 一般而言,不是开发的安个jre就行,但类似于jsp编译就需要jdk的开发工具。JIT(justintime)即使编译器,可对热点代码直接编译。所以说比解释性语言快些、解释和编译型语......
  • java -动态sql语句
    数据库算法双子针、动态规划、二分查找、贪心算法、深度优先搜索、字符串、递归、字典树、排序、链表等元素作用描述if......
  • Java 实例 - 在控制台上随机得到两个数之间的任意整数值(Random随机数)
       在控制台上随机得到4~11之间的任意值,含4和11 1packagecom.guyu.demo;23importjava.util.Random;45/**6*7*2024年4月9日上午10:39:438*@authorGuyu9*10*随机数示例:11*在控制台上随机得到4~11之间的任意......
  • java-validation(数据校验)
    @PostMapping("/register")@SystemLog(BusinessName="注册用户")//启动AOP实现日志记录publicResponseResultregister(@Validated(ValidateType.INSERT.class)@RequestBodyTsUsertsUser){returntsUserService.register(tsUser);......
  • java-queryWrapper条件
    QueryWrapper1.eq、ne2.gt、ge、lt、le3.between、notBetween4.like、notLike、likeLeft、likeRight5.isNull、isNotNull6.in、notIn7.or、and8.orderByAsc、orderByDesc9.inSql、notInSql(不常用)10.exists、notExists(不常用)11List(不常用)12groupby分组(不常......
  • java-Stream流
    lambda表达式定义:不管是什么对象,lambda表达式主要关注的是对数据进行了什么操作。基本格式(参数列表)->{代码}1.是一个匿名类并且只有一个抽象接口。(笔记)例子:newThread(newRunnable(){@Overridepublicvoidrun(){system。outprintln("新线程中run方法被......
  • 线上服务Java进程假死快速排查、分析
    服务器上的Java进程总是在运行个两三天后就无法响应请求了,具体现象如下:请求业务返回状态码502,查看进程还在,意味着Java进程假死,无法响应请求了;该Java进程占比CPU较高,高达132.8%。使用top命令查看服务器整体运行情况:可以看到PID为14760的Java进程CPU占比132.8%,内存占用37.6%,......
  • 【全开源】JAVA红娘婚恋相亲交友系统源码支持微信小程序+微信公众号+H5+APP
    JAVA红娘婚恋相亲交友系统源码:跨平台交友新纪元,微信小程序、公众号、H5、APP全覆盖在数字化浪潮汹涌的今天,婚恋相亲已不再是传统的线下模式所能满足。JAVA红娘婚恋相亲交友系统源码,以其卓越的跨平台特性和强大的功能优势,为您打造了一个全新的相亲交友体验。无论是微信小程序、......
  • 【全开源】JAVA上门家政服务系统源码微信小程序+微信公众号+APP+H5
    JAVA上门家政服务系统源码:一站式家政服务,微信小程序、公众号、APP、H5全平台覆盖,便捷生活触手可及在现代生活的快节奏中,人们对家政服务的需求日益旺盛。JAVA上门家政服务系统源码,以其高效、便捷的特性,结合微信小程序、公众号、APP和H5平台,为您打造了一站式的家政服务体验,让您......
  • 【全开源】JAVA红娘婚恋相亲交友系统源码支持微信小程序+微信公众号+H5+APP
    JAVA红娘婚恋相亲交友系统源码:跨平台交友新纪元,微信小程序、公众号、H5、APP全覆盖在数字化浪潮汹涌的今天,婚恋相亲已不再是传统的线下模式所能满足。JAVA红娘婚恋相亲交友系统源码,以其卓越的跨平台特性和强大的功能优势,为您打造了一个全新的相亲交友体验。无论是微信小程序、......