Java 实现压缩图片,视频,音频案例

Java 实现压缩图片,视频,音频案例

在 Java 中,要实现视频压缩通常需要使用外部的库或工具,因为 Java 标准库本身并不提供直接的视频处理功能。以下是一些常用的方法和工具来压缩视频:

FFmpeg:

FFmpeg 是一个开源跨平台的多媒体处理工具,可以用来对音频、视频等多媒体数据进行编解码、转换和流处理。你可以通过 Java 调用 FFmpeg 的命令行来实现视频压缩。

Xuggler:

Xuggler 是一个 Java 语言的多媒体处理库,基于 FFmpeg 和 X264 构建,提供了 Java API 来进行视频和音频的处理。你可以使用 Xuggler 来实现视频的压缩和转换。

JCodec:

JCodec 是一个专门用于视频编解码的 Java 库,支持常见的视频编解码格式,包括 H.264、MPEG-4 等。你可以使用 JCodec 来实现视频的压缩和编解码操作。


接下来我们使用FFmpeg实现音频及视频的压缩

导入Maven依赖

<dependency>
    <groupId>com.vaadin.external.google</groupId>
    <artifactId>android-json</artifactId>
    <version>0.0.20131108.vaadin1</version>
    <scope>compile</scope>
</dependency>

参数说明

1. ffmpegPath:FFmpeg可执行文件的路径。
2. "-i", inputFile.getAbsolutePath():指定输入文件的路径。
3. "-c:v", "libx264":指定视频编解码器为libx264。
4. "-crf", "28":设置视频的质量,数值越小,视频质量越高,推荐范围是18-28。
5. "-preset", "fast":设置编码速度和质量的平衡,"fast"为快速编码。
6. "-c:a", "aac":指定音频编解码器为AAC。
7. "-b:a", "64k":设置音频比特率为64kbps。
8. "-movflags", "+faststart":对生成的MP4文件进行优化,使其能够逐步播放。
9. outputFile.getAbsolutePath() + ".mp4":指定输出文件的路径和文件名,同时指定了输出文件的格式为MP4。

压缩视频

//压缩视频
public static void compressVideo(File inputFile, File outputFile) {
	Long startTime = System.currentTimeMillis();
	try {
		String ffmpegPath = "D:\\develop\\ffmpeg-master-latest-win64-gpl\\bin\\ffmpeg.exe"; 
		// FFmpeg可执行文件路径
		// 构建FFmpeg命令
		String[] command = {
			ffmpegPath,
			"-i", inputFile.getAbsolutePath(),
			"-c:v", "libx264",
			"-crf", "28",
			"-preset", "fast",
			"-c:a", "aac",
			"-b:a", "64k",
			"-movflags", "+faststart",
			outputFile.getAbsolutePath() + ".mp4"
		};
		// 创建进程生成器
		ProcessBuilder processBuilder = new ProcessBuilder(command);
		// 重定向进程的输入、输出和错误流
		processBuilder.inheritIO();
		// 启动进程
		Process process = processBuilder.start();

		// 等待进程完成
		process.waitFor();
		Long endTime = System.currentTimeMillis();
		System.out.println("视频压缩完成!用时: " + (endTime - startTime));
	} catch (Exception e) {
		e.printStackTrace();
	}
}

压缩音频

//压缩音频
public static byte[] compressAudio(InputStream inputStream) {
	Long startTime = System.currentTimeMillis();
	try {
		// FFmpeg可执行文件路径
		String[] command = {
				"ffmpeg",
				"-i", "pipe:0",
				"-b:a", "64k",
				"-f", "mp3",
				"pipe:1"
		};
		ProcessBuilder processBuilder = new ProcessBuilder(command);
		// 重定向进程的输入、输出和错误流
		processBuilder.redirectInput(ProcessBuilder.Redirect.PIPE);
		processBuilder.redirectOutput(ProcessBuilder.Redirect.PIPE);
		processBuilder.redirectError(ProcessBuilder.Redirect.INHERIT);
		// 启动进程
		Process process = processBuilder.start();

		// 将输入流拷贝到进程的输入流中
		Thread copyThread = new Thread(() -> {
			try {
				byte[] buffer = new byte[1024];
				int len;
				while ((len = inputStream.read(buffer)) > 0) {
					process.getOutputStream().write(buffer, 0, len);
				}
				process.getOutputStream().close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		});
		copyThread.start();

		// 将进程的输出流缓存到字节数组输出流中
		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len;
		while ((len = process.getInputStream().read(buffer)) > 0) {
			byteArrayOutputStream.write(buffer, 0, len);
		}

		// 等待输入流拷贝线程完成
		copyThread.join();
		// 等待进程完成
		process.waitFor();
		Long endTime = System.currentTimeMillis();
		System.out.println("音频压缩完成!用时: " + (endTime - startTime));

		// 返回压缩后的音频文件数据
		return byteArrayOutputStream.toByteArray();
	} catch (Exception e) {
		e.printStackTrace();
		return null;
	}
}
实现压缩图片
//压缩图片
public static InputStream compressImage(InputStream inputStream, String outputFormat) {
    BufferedImage image = null;
    try {
        image = ImageIO.read(inputStream);
    } catch (IOException e) {
        e.printStackTrace();
    }

    int newWidth = (int) (image.getWidth() * compressionRatio);
    int newHeight = (int) (image.getHeight() * compressionRatio);

    BufferedImage compressedImage = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);

    compressedImage.createGraphics().drawImage(image.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH), 0, 0, null);

    ByteArrayOutputStream out = new ByteArrayOutputStream();

    try {
        ImageIO.write(compressedImage, outputFormat, out);
        out.flush();
    } catch (Exception e) {
        e.printStackTrace();
    }

    ByteArrayInputStream compressedInputStream = new ByteArrayInputStream(out.toByteArray());

    return compressedInputStream;
}
posted @ 2024-03-21 16:19  ghostmen  阅读(144)  评论(0编辑  收藏  举报