Java实现doc、ppt、pdf和视频的缩略图

最近用java对word三大办公软件和视频进行缩略图展示,用到了spire这个插件,比较简单我直接展示下代码,主要就是那个jar包得自己打包,我自己使用pom没法直接导入(即使指定了网址),所以我这边只展示代码了。

1.word缩略图

    /**
     * word获取缩略图
     *
     * @param wordFile      word文件地址
     * @param outputImgPath 输出图片目录
     * @return 图片路径
     * @create 2023-01-09
     */
    private static String wordToImage(String wordFile, String outputImgPath) throws Exception {
        Document word = new Document();
        word.loadFromFile(wordFile);
        String fileName = getFileName(wordFile);
        BufferedImage image = word.saveToImages(0, ImageType.Bitmap);
        String imgUrl = outputImgPath + fileName + (0 + 1) + ".png";
        File file = new File(imgUrl);
        ImageIO.write(image, "PNG", file);
        log.info("word缩略图获取完成,图片目录:[{}]", imgUrl);
        return imgUrl;
    }

2.ppt缩略图

    /**
     * ppt获取缩略图
     *
     * @param pptFile       ppt文件地址
     * @param outputImgPath 输出图片目录
     * @return 图片路径
     * @create 2023-01-09
     */
    private static String pptToImage(String pptFile, String outputImgPath) throws Exception {
        Presentation ppt = new Presentation();
        ppt.loadFromFile(pptFile);
        String fileName = getFileName(pptFile);
        BufferedImage image = ppt.getSlides().get(0).saveAsImage();
        String imgUrl = outputImgPath + fileName + (0 + 1) + ".png";
        ImageIO.write(image, "PNG", new File(imgUrl));
        ppt.dispose();
        log.info("ppt缩略图获取完成,图片目录:[{}]", imgUrl);
        return imgUrl;
    }

3.pdf缩略图

    /**
     * pdf获取缩略图
     *
     * @param pdfFile       pdf文件地址
     * @param outputImgPath 输出图片目录
     * @return 图片路径
     * @create 2023-01-09
     */
    private static String pdfToImage(String pdfFile, String outputImgPath) throws Exception {
        PdfDocument pdf = new PdfDocument();
        pdf.loadFromFile(pdfFile);
        String fileName = getFileName(pdfFile);
        BufferedImage image = pdf.saveAsImage(0, PdfImageType.Bitmap);
        String imgUrl = outputImgPath + fileName + (0 + 1) + ".png";
        File file = new File(imgUrl);
        ImageIO.write(image, "PNG", file);
        log.info("pdf缩略图获取完成,图片目录:[{}]", imgUrl);
        return imgUrl;
    }

4.video缩略图

    /**
     * 截取视频第一帧的图片
     *
     * @param videoFile     视频路径
     * @param outputImgPath 文件存放的根目录
     * @return 图片路径
     * @throws FrameGrabber.Exception
     */
    private static String videoImage(String videoFile, String outputImgPath) throws FrameGrabber.Exception {
        FFmpegFrameGrabber ff = FFmpegFrameGrabber.createDefault(videoFile);
        ff.start();
        Frame f;
        f = ff.grabImage();
        //保存文件名称
        String pngPath = getFileName(videoFile) + ".png";

        //最终图片路径
        String resPath = outputImgPath + pngPath;
        //截取缩略图
        String imageMat = "PNG";
        if (null == f || null == f.image) {
            return "";
        }
        Java2DFrameConverter converter = new Java2DFrameConverter();
        BufferedImage bufferedImage = converter.getBufferedImage(f);
        File output = new File(resPath);
        try {
            ImageIO.write(bufferedImage, imageMat, output);
        } catch (IOException e) {
            e.printStackTrace();
        }

        log.info("video缩略图获取完成,图片目录:[{}]", resPath);
        ff.stop();
        return resPath;
    }

5.功能函数

这个主要就是生成的缩略图的文件命名。

    /**
     * 增加时间戳的文件名(不带后缀)
     *
     * @param filePath 文件路径
     * @return java.lang.String
     * @create 2023-01-09
     */
    private static String getFileName(String filePath) {
        String fileName = new File(filePath).getName();
        String res = System.currentTimeMillis() + "-" + fileName.substring(0, fileName.lastIndexOf("."));
        return res;
    }

	/**
	*缩略图通用方法
	*/
	public static String generateThumbnail(String file, String outputImgPath) throws Exception {
        if (!outputImgPath.endsWith(File.separator)) {
            //如果不是斜杠结尾增加
            outputImgPath += File.separator;
        }
        String filePath = "";
        if (file.endsWith("doc") | file.endsWith("docx")) {
            filePath = wordToImage(file, outputImgPath);
        } else if (file.endsWith("ppt") | file.endsWith("pptx")) {
            filePath = pptToImage(file, outputImgPath);
        } else if (file.endsWith("pdf")) {
            filePath = pdfToImage(file, outputImgPath);
        } else if (file.endsWith("mp4")) {
            filePath = videoImage(file, outputImgPath);
        }
        return filePath;
    }
import com.spire.doc.Document;
import com.spire.doc.documents.ImageType;
import com.spire.pdf.PdfDocument;
import com.spire.pdf.graphics.PdfImageType;
import com.spire.presentation.Presentation;
import lombok.extern.slf4j.Slf4j;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.FrameGrabber;
import org.bytedeco.javacv.Java2DFrameConverter;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

/**
 * 类描述:缩略图工具类
 *
 * @ClassName ThumbnailUtil
 * @Author ward
 * @Date 2023-01-06 17:46
 */
@Slf4j
public class ThumbnailUtil {

    /**
     * 增加时间戳的文件名(不带后缀)
     *
     * @param filePath 文件路径
     * @return java.lang.String
     * @create 2023-01-09
     */
    private static String getFileName(String filePath) {
        String fileName = new File(filePath).getName();
        String res = System.currentTimeMillis() + "-" + fileName.substring(0, fileName.lastIndexOf("."));
        return res;
    }

    /**
     * word获取缩略图
     *
     * @param wordFile      word文件地址
     * @param outputImgPath 输出图片目录
     * @return 图片路径
     * @create 2023-01-09
     */
    private static String wordToImage(String wordFile, String outputImgPath) throws Exception {
        Document word = new Document();
        word.loadFromFile(wordFile);
        String fileName = getFileName(wordFile);
        BufferedImage image = word.saveToImages(0, ImageType.Bitmap);
        String imgUrl = outputImgPath + fileName + (0 + 1) + ".png";
        File file = new File(imgUrl);
        ImageIO.write(image, "PNG", file);
        log.info("word缩略图获取完成,图片目录:[{}]", imgUrl);
        return imgUrl;
    }

    /**
     * ppt获取缩略图
     *
     * @param pptFile       ppt文件地址
     * @param outputImgPath 输出图片目录
     * @return 图片路径
     * @create 2023-01-09
     */
    private static String pptToImage(String pptFile, String outputImgPath) throws Exception {
        Presentation ppt = new Presentation();
        ppt.loadFromFile(pptFile);
        String fileName = getFileName(pptFile);
        BufferedImage image = ppt.getSlides().get(0).saveAsImage();
        String imgUrl = outputImgPath + fileName + (0 + 1) + ".png";
        ImageIO.write(image, "PNG", new File(imgUrl));
        ppt.dispose();
        log.info("ppt缩略图获取完成,图片目录:[{}]", imgUrl);
        return imgUrl;
    }

    /**
     * pdf获取缩略图
     *
     * @param pdfFile       pdf文件地址
     * @param outputImgPath 输出图片目录
     * @return 图片路径
     * @create 2023-01-09
     */
    private static String pdfToImage(String pdfFile, String outputImgPath) throws Exception {
        PdfDocument pdf = new PdfDocument();
        pdf.loadFromFile(pdfFile);
        String fileName = getFileName(pdfFile);
        BufferedImage image = pdf.saveAsImage(0, PdfImageType.Bitmap);
        String imgUrl = outputImgPath + fileName + (0 + 1) + ".png";
        File file = new File(imgUrl);
        ImageIO.write(image, "PNG", file);
        log.info("pdf缩略图获取完成,图片目录:[{}]", imgUrl);
        return imgUrl;
    }

    /**
     * 截取视频第六帧的图片
     *
     * @param videoFile     视频路径
     * @param outputImgPath 文件存放的根目录
     * @return 图片路径
     * @throws FrameGrabber.Exception
     */
    private static String videoImage(String videoFile, String outputImgPath) throws FrameGrabber.Exception {
        FFmpegFrameGrabber ff = FFmpegFrameGrabber.createDefault(videoFile);
        ff.start();
        Frame f;
        f = ff.grabImage();
        //保存文件名称
        String pngPath = getFileName(videoFile) + ".png";

        //最终图片路径
        String resPath = outputImgPath + pngPath;
        //截取缩略图
        String imageMat = "PNG";
        if (null == f || null == f.image) {
            return "";
        }
        Java2DFrameConverter converter = new Java2DFrameConverter();
        BufferedImage bufferedImage = converter.getBufferedImage(f);
        File output = new File(resPath);
        try {
            ImageIO.write(bufferedImage, imageMat, output);
        } catch (IOException e) {
            e.printStackTrace();
        }

        log.info("video缩略图获取完成,图片目录:[{}]", resPath);
        ff.stop();
        return resPath;
    }

    public static String generateThumbnail(String file, String outputImgPath) throws Exception {
        if (!outputImgPath.endsWith(File.separator)) {
            //如果不是斜杠结尾增加
            outputImgPath += File.separator;
        }
        String filePath = "";
        if (file.endsWith("doc") | file.endsWith("docx")) {
            filePath = wordToImage(file, outputImgPath);
        } else if (file.endsWith("ppt") | file.endsWith("pptx")) {
            filePath = pptToImage(file, outputImgPath);
        } else if (file.endsWith("pdf")) {
            filePath = pdfToImage(file, outputImgPath);
        } else if (file.endsWith("mp4")) {
            filePath = videoImage(file, outputImgPath);
        }
        return filePath;
    }

    public static void main(String[] args) throws Exception {
        String path = generateThumbnail("D:\\desktop\\test\\video.mp4",
                "D:\\desktop\\test\\img");
        System.out.println(path);
    }
}

6.异常情况

项目部署在linux上,生成缩略图的时候部分字体就会显示不了,如下图。后来发现是linux缺少中文字体导致的,这里介绍下导入中文字体的方法。
在这里插入图片描述

6.1安装软件

#安装fontconfig和mkfontscale工具
yum install -y fontconfig
yum install -y mkfontscale

#创建字体文件夹(存中文字体)
mkdir -p /usr/share/fonts/chinese/

#给与权限
chmod -R 775 /usr/share/fonts/chinese/

#接下来就是把你电脑里的C:\Windows\Fonts路径下的全部压缩上传解压到刚刚创建的文件夹里

#进入文件夹,以下命令要进入文件夹下
cd /usr/share/fonts
#字体扩展
mkfontscale 
#新增字体目录
mkfontdir 
#刷新缓存
fc-cache -fv 
#查看字体
fc-list :lang=zh
  • 6
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
Java可以通过使用文件上传组件来实现PDFPPTDOC文件的上传。常见的文件上传组件有Apache Commons FileUpload、Servlet 3.0规范的Part和Spring MVC的MultipartFile等。 实现步骤如下: 1. 在HTML页面中添加文件上传控件,例如: ``` <form method="post" enctype="multipart/form-data" action="upload"> <input type="file" name="file"> <input type="submit" value="上传"> </form> ``` 2. 在Java后端代码中获取上传的文件,例如: ``` // 使用Apache Commons FileUpload获取上传的文件 ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory()); List<FileItem> items = servletFileUpload.parseRequest(request); for (FileItem item : items) { if (!item.isFormField()) { InputStream inputStream = item.getInputStream(); // 处理上传的文件 } } ``` 或者使用Servlet 3.0规范的Part获取上传的文件,例如: ``` Part filePart = request.getPart("file"); InputStream inputStream = filePart.getInputStream(); // 处理上传的文件 ``` 或者在Spring MVC中使用MultipartFile获取上传的文件,例如: ``` @PostMapping("/upload") public String handleFileUpload(@RequestParam("file") MultipartFile file) throws IOException { InputStream inputStream = file.getInputStream(); // 处理上传的文件 } ``` 3. 对于上传的PDFPPTDOC文件,可以使用Apache POI或iText库进行解析和处理。例如,使用Apache POI来读取上传的PPT文件: ``` InputStream inputStream = item.getInputStream(); XMLSlideShow ppt = new XMLSlideShow(inputStream); for (XSLFSlide slide : ppt.getSlides()) { // 处理PPT每一张幻灯片 } ``` 或者使用iText来读取上传的PDF文件: ``` InputStream inputStream = item.getInputStream(); PdfReader reader = new PdfReader(inputStream); for (int i = 1; i <= reader.getNumberOfPages(); i++) { // 处理PDF每一页 } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值