javacv-ffmpeg ProcessBuilder实现对图片的旋转,最近需要处理很多图片,量有点多,所以不能一个一个去编辑旋转图片,所以写一个工具类,实现对图片的旋转

maven配置文件,加上对ffmpeg的依赖,由于ffmpeg依赖cpp,所以加上javacppjavacpp是可以支持调用c/c++方法的库。加上<classifier>标签,因为ffmpeg是基于c语言编写的,在不同平台上的编译结果不同,所以这个标签指定一下平台的类型

<dependency>
     <groupId>org.bytedeco</groupId>
     <artifactId>javacpp</artifactId>
     <version>1.5.6</version>
     <classifier>windows-x86_64</classifier>
 </dependency>

 <dependency>
     <groupId>org.bytedeco</groupId>
     <artifactId>ffmpeg-platform</artifactId>
     <version>4.4-1.5.6</version>
 </dependency>
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.

如果不想引入两个jar,可以直接引入javacv-platform,但是这个会引入其它的依赖

<dependency>
    <groupId>org.bytedeco</groupId>
    <artifactId>javacv-platform</artifactId>
    <version>1.5.5</version>
</dependency>
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.

这里使用jdk中的ProcessBuilder 用于创建操作系统进程来运行程序,ProcessBuilder 是jdk提供的用于创建操作系统进程的类,使用Loader.load(org.bytedeco.ffmpeg.ffmpeg.class);支持对ffmpeg(c语言编写)方法的调用

package com.example.common.util.file;

import org.bytedeco.javacpp.Loader;
import java.text.MessageFormat;

public class PictureProcess {

    /**
     * 旋转
     *
     * @Date 2024/08/27 15:46
     * @Param imagePath 图片地址
     * @Param outputPath 输出地址
     * @Param angle 角度
     * @return java.lang.String 图片地址
     */
    public static String rotate(String imagePath, String outputPath , Integer angle) throws Exception {
        String ffmpeg = Loader.load(org.bytedeco.ffmpeg.ffmpeg.class);
        ProcessBuilder builder =
                new ProcessBuilder(
                        ffmpeg,
                        "-i",
                        imagePath,
                        "-vf",
                        MessageFormat.format("rotate=PI*{0}/180", String.valueOf(angle)),
                        "-y",
                        outputPath);
        builder.inheritIO().start().waitFor();
        return outputDir;
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.

这里介绍一下弧度的计算公式:弧度= 角度 * Math.PI / 180 PI*{0}/180李的{0}是占位符,来传入角度的值

javacv-ffmpeg ProcessBuilder批量旋转图片_c语言

写个测试类,将文件夹里的所有图片都旋转90度

@Test
public void testProcess() {
    File file = new File("D:\\picture");
    File[] files = file.listFiles();
    String targetPath = "D:\\picture_NEW";
    for (File file1 : files) {
        System.out.println(rotate(file1.getPath(), targetPath +"/"+ file1.getName(), 90));
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.