分享一个工具类,图片通用的工具类

目录

1.简介:

2.功能:

1.文件后缀名修改

2.文件指定格式转换

3.合并文件夹

4.图片转PDF


1.简介:

        这个工具类的出生是因为有一天,我朋友分享了一堆文件图片给我,上面都是密密麻麻的小字和演示的图片示例等等,在查看的时候就只能一张一张去翻;当今天看完,明天再来看的时候就会发现,不知道从哪儿看起,因为图片聊天记录是没有顺序记录的,只能凭借记忆一点点去翻,好不容易翻到了已经是过去了半个小时,所以我突发奇想,可不可以把他导成word或者pdf,一个文件即可,可以增加书签,第二次打开就是第一次看过的地方;说干就干,我当场就去网上找了在线的pdf导出工具,或者pdf导出的程序(需要下载的那种);找了一段时间后,我只能说,要么导不出来,要么不支持大于15张图片的,要么就是要钱且有水印;我心一横,大不了自己写一个程序,于是,这个工具类就诞生啦;

2.功能:

        该工具类支持的功能不少,但都是根据我个人需求来做的,下面我使用swagger页面来解释:

1.文件后缀名修改

支持批量修改,读取需要修改的文件所在的文件夹路径,输入需要命中该文件下的那种后缀文件,需要修改成什么后缀到哪个文件夹下(支持同目录修改)

当然修改完成后,源文件会被删除,这个功能不需要的可以自行修改

2.文件指定格式转换

目前只支持将webp后缀的文件修改为jpg或png文件,因为webp文件特性,只修改后缀是不能正常读取的,因此我在工具中是通过先读取再重写的方式,将其输出成jpg或png文件的;

当然这里只是根据我自己的需求写的,我还提供了一个更方便的格式转换方法在工具类中,即通过你输入的后缀,转换为你指定的后缀,不过这个工具需要你们使用的时候自己测一下(我也不知道好不好用,因为我没测过doge)

3.合并文件夹

合并文件夹,即将多个文件夹放到一个文件夹下,输入该父文件夹的路径,会合并这个父文件夹下的所有子文件夹中的文件,到你指定的新文件夹路径中

4.图片转PDF

根据你输入的文件夹路径,读取下面的所有文件,输出一个pdf文件到指定文件夹下;该pdf文件的名字采用文件夹名自动生成,例如:D:\temp\123,输出的pdf文件就默认为123.pdf

以下是工具类代码:

import com.itextpdf.io.image.ImageData;
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Image;
import com.luciad.imageio.webp.WebPReadParam;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.graphics.image.LosslessFactory;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;


import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.FileImageInputStream;
import javax.imageio.stream.FileImageOutputStream;
import javax.imageio.stream.ImageInputStream;
import javax.imageio.stream.ImageOutputStream;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.Iterator;

/**
 * 文件转换工具
 */
public class ConversionUtil {

    /**
     * 后缀名修改
     * @param sourceFolder
     * @param newFolder
     * @param oldSuffix
     * @param newSuffix
     * @return
     */
    public static String conversionByPath(String sourceFolder, String newFolder,
                                        String oldSuffix, String newSuffix) {
        long l = System.currentTimeMillis();

        String oldExtension = "." + oldSuffix; // 原始后缀名
        String newExtension = "." + newSuffix; // 修改后的后缀名

        File folder = new File(sourceFolder);

        // 检查源文件夹是否存在
        if (!folder.exists() || !folder.isDirectory()) {
            System.out.println("源文件夹不存在");
            return "源文件夹不存在";
        }

        // 创建新文件夹
        File newDir = new File(newFolder);
        if (!newDir.exists()) {
            newDir.mkdirs();
        }

        // 遍历源文件夹下的所有文件
        File[] files = folder.listFiles();
        for (File file : files) {
            if (file.isFile()) {
                String fileName = file.getName();
                if (fileName.endsWith(oldExtension)) { // 仅处理具有指定后缀名的文件
                    String renamedFileName = fileName.replace(oldExtension, newExtension); // 修改文件名
                    File renamedFile = new File(newDir, renamedFileName); // 创建新文件对象

                    try {
                        // 复制并重命名文件
                        java.nio.file.Files.copy(file.toPath(), renamedFile.toPath());
//                        System.out.println("已重命名文件: " + renamedFileName);
                    } catch (IOException e) {
                        System.err.println("重命名文件时发生错误: " + fileName);
//                        e.printStackTrace();
                        throw new RuntimeException("重命名文件时发生异常");
                    }
                }
            }
        }

        long l1 = System.currentTimeMillis();
        long l2 = l1 - l;
        return "后缀修改完成" + ",耗时:" + l2 +" ms";
    }

    /**
     * 文件格式转换
     *
     * @param sourceFolder
     * @param newFolder
     * @param newSuffix
     * @return
     */
    public static String conversionWebpToPng(String sourceFolder, String newFolder, String newSuffix) {
        long l = System.currentTimeMillis();
        File folder = new File(sourceFolder);

        // 检查源文件夹是否存在
        if (!folder.exists() || !folder.isDirectory()) {
            System.out.println("源文件夹不存在");
            return "源文件夹不存在";
        }

        // 创建新文件夹
        File newDir = new File(newFolder);
        if (!newDir.exists()) {
            newDir.mkdirs();
        }

        // 遍历源文件夹下的所有文件
        File[] files = folder.listFiles();
        for (File file : files) {
            if (file.isFile()) {
                String fileName = file.getName();
                String fileSuffix = fileName.replace("webp", newSuffix);
                try {
                    webpToPng(file.getAbsolutePath(), newFolder+"\\"+fileSuffix, newSuffix);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
        deleteFolderContents(folder);

        long l1 = System.currentTimeMillis();
        long l2 = l1 - l;
        return "格式转换完成" + ",耗时:" + l2 +" ms";
    }

    /**
     * 图片转pdf
     * @param sourceFolder
     * @param outputPdfPath
     */
    public static String conversionImgToPDF(String sourceFolder, String outputPdfPath) {
        long l = System.currentTimeMillis();

        File folder = new File(sourceFolder);
        // 检查源文件夹是否存在
        if (!folder.exists() || !folder.isDirectory()) {
//            System.out.println("源文件夹不存在");
            return "源文件夹不存在";
        }

        String folderName = folder.getName() + ".pdf";
        String s = outputPdfPath + "\\" + folderName;
        try {
            // 创建 PDF 文档对象
//            PdfDocument pdfDocument = new PdfDocument(new PdfWriter(outputPdfPath));
            PdfDocument pdfDocument = new PdfDocument(new PdfWriter(s));
            Document document = new Document(pdfDocument);

            // 遍历源文件夹下的所有文件
            File[] files = folder.listFiles();
            for (File file : files) {
                if (file.isFile()) {
                    String fileName = file.getName();
                    if (fileName.endsWith(".png") || fileName.endsWith(".jpg") || fileName.endsWith(".jpeg")) {
                        // 读取图片文件
                        ImageData imageData = ImageDataFactory.create(file.getAbsolutePath());
                        Image image = new Image(imageData);

                        // 添加图片到 PDF 文档中
                        document.add(image);
                    }
                }
            }

            // 关闭文档
            document.close();
            System.out.println("图片转换为 PDF 成功");
        } catch (IOException e) {
            System.out.println("转换过程中发生错误");
            e.printStackTrace();
            throw new RuntimeException("转换过程中发生异常");
        }
        long l1 = System.currentTimeMillis();
        long l2 = l1 - l;
        return "图片转PDF完成" + ",耗时:" + l2 +" ms";
    }

    /**
     * webp图片格式转换
     * @param webpPath
     * @param pngPath
     * @param last
     * @throws IOException
     */
    public static void webpToPng(String webpPath, String pngPath, String last) throws IOException {
        File file = new File(pngPath);
        if (!file.exists()){
            file.getParentFile().mkdirs();
        }
        // Obtain a WebP ImageReader instance
        ImageReader reader = ImageIO.getImageReadersByMIMEType("image/webp").next();

        try (ImageInputStream input = new FileImageInputStream(new File(webpPath))) {
            // Configure decoding parameters
            WebPReadParam readParam = new WebPReadParam();
            readParam.setBypassFiltering(true);

            // Configure the input on the ImageReader
            reader.setInput(input);

            // Decode the image
            BufferedImage image = reader.read(0, readParam);

            // Save the image in PNG format
            try (ImageOutputStream output = new FileImageOutputStream(new File(pngPath))) {
                ImageIO.write(image, last, output);
            }
        } finally {
            // Close the ImageReader
            reader.dispose();
        }

    }

    /**
     * 合并文件夹下子文件夹中的所有文件到一个新文件夹
     * @param sourceFolderPath
     * @param destinationFolderPath
     */
    public static String mergeFolders(String sourceFolderPath, String destinationFolderPath) {
        File sourceFolder = new File(sourceFolderPath);
        File destinationFolder = new File(destinationFolderPath);

        if (!destinationFolder.exists()) {
            destinationFolder.mkdirs();
        }

        if (sourceFolder.isDirectory()) {
            File[] subFolders = sourceFolder.listFiles();

            if (subFolders != null) {
                for (File subFolder : subFolders) {
                    if (subFolder.isDirectory()) {
                        File[] files = subFolder.listFiles();
                        String folderName = subFolder.getName();

                        if (files != null) {
                            for (int i = 0; i < files.length; i++) {
                                File file = files[i];
                                String fileName = folderName + "_" + file.getName();

                                try {
                                    Files.copy(file.toPath(), new File(destinationFolder, fileName).toPath(),
                                            StandardCopyOption.REPLACE_EXISTING);
                                } catch (IOException e) {
                                    e.printStackTrace();
                                    throw new RuntimeException("文件合并异常");
                                }
                            }
                        }
                    }
                }
            }
        }

        return "文件夹内容合并完成!";
    }

    /**
     * apache 原生图片转PDF
     */
    public static void conversionImgToPDF() {
        String sourceFolder = "D:\\temp\\中转";
        String outputPdfPath = "D:\\temp\\中转\\11";

        File folder = new File(sourceFolder);

        // 检查源文件夹是否存在
        if (!folder.exists() || !folder.isDirectory()) {
            System.out.println("源文件夹不存在");
            return;
        }

        try {
            PDDocument document = new PDDocument();

            // 遍历源文件夹下的所有文件
            File[] files = folder.listFiles();
            for (File file : files) {
                if (file.isFile()) {
                    String fileName = file.getName();
                    if (fileName.endsWith(".png") || fileName.endsWith(".jpg") || fileName.endsWith(".jpeg")) {
                        BufferedImage image = loadImage(file);
                        PDPage page = new PDPage(new PDRectangle(image.getWidth(), image.getHeight()));
                        document.addPage(page);
                        PDImageXObject ximage = LosslessFactory.createFromImage(document, image);
                        PDPageContentStream contentStream = new PDPageContentStream(document, page);
                        contentStream.drawImage(ximage, 0, 0);
                        contentStream.close();
                    }
                }
            }

            // 保存为 PDF 文件
            document.save(outputPdfPath);
            document.close();
            System.out.println("图片转换为 PDF 成功");
        } catch (IOException e) {
            System.out.println("转换过程中发生错误");
            e.printStackTrace();
        }
    }

    /**
     * 读取图片到缓冲区
     *
     * @param file
     * @return
     * @throws IOException
     */
    private static BufferedImage loadImage(File file) throws IOException {
        try (ImageInputStream inputStream = ImageIO.createImageInputStream(file)) {
            Iterator<ImageReader> readers = ImageIO.getImageReaders(inputStream);
            if (readers.hasNext()) {
                ImageReader reader = readers.next();
                reader.setInput(inputStream);
                return reader.read(0);
            }
        }
        return null;
    }

    /**
     * 删除文件夹以及文件夹下的所有子文件
     *
     * @param folder
     * @return
     */
    private static Boolean deleteFolderContents(File folder) {
        if (folder.exists()) {
            File[] files = folder.listFiles();

            if (files != null) {
                for (File file : files) {
                    if (file.isDirectory()) {
                        // 递归删除子文件夹及其内容
                        deleteFolderContents(file);
                    } else {
                        // 删除文件
                        file.delete();
                    }
                }
            }

            // 删除空文件夹
            return folder.delete();
        }
        return false;
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值