java视频压缩工具类

引入依赖

   <!-- schild 媒体资源压缩转码等 -->
        <dependency>
            <groupId>ws.schild</groupId>
            <artifactId>jave-core</artifactId>
            <version>${ws.schild}</version>
        </dependency>
        <dependency>
            <groupId>ws.schild</groupId>
            <artifactId>jave-nativebin-linux64</artifactId>
            <version>${ws.schild}</version>
        </dependency>
        <dependency>
            <groupId>ws.schild</groupId>
            <artifactId>jave-nativebin-win64</artifactId>
            <version>${ws.schild}</version>
        </dependency>

java示例

package com.zzx.utils;

import cn.hutool.core.io.FileUtil;
import org.apache.commons.io.FileUtils;
import org.jcodec.api.FrameGrab;
import org.jcodec.common.model.Picture;
import org.jcodec.scale.AWTUtil;
import org.springframework.web.multipart.MultipartFile;
import ws.schild.jave.Encoder;
import ws.schild.jave.MultimediaObject;
import ws.schild.jave.encode.AudioAttributes;
import ws.schild.jave.encode.EncodingAttributes;
import ws.schild.jave.encode.VideoAttributes;
import ws.schild.jave.info.AudioInfo;
import ws.schild.jave.info.VideoInfo;
import ws.schild.jave.info.VideoSize;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.math.BigDecimal;
import java.net.URL;

/**
 * @author zzx 视频压缩工具类
 * @date 2024年01月05日 17:17
 */
public class VideoUtils {

	public static String[] videoEnum = new String[] { "AVI", "mov", "rmvb", "rm", "FLV", "mp4", "3GP" };

	/**
	 * 传视频File对象(这是一个具体的文件),返回压缩后File对象信息
	 * @param source
	 */
	public static InputStream compressionVideo(MultipartFile source) {
		if (source == null) {
			return null;
		}
		String suffix = FileUtil.extName(source.getOriginalFilename());
		String targetPath = System.getProperty("user.dir") + System.getProperty("file.separator") + "target." + suffix;
		File target = new File(targetPath);
		String tmpPath = System.getProperty("user.dir") + System.getProperty("file.separator") + "tmp." + suffix;
		File tmpSource = new File(tmpPath);
		try {
			FileUtils.copyInputStreamToFile(source.getInputStream(), tmpSource);
			MultimediaObject object = new MultimediaObject(tmpSource);
			AudioInfo audioInfo = object.getInfo().getAudio();
			// 根据视频大小来判断是否需要进行压缩,
			int maxSize = 5;
			long size = source.getSize();
			double mb = Math.ceil(size / 1048576);
			int second = (int) object.getInfo().getDuration() / 1000;
			BigDecimal bd = new BigDecimal(String.format("%.4f", mb / second));
			System.out.println("开始压缩视频了--> 视频每秒平均 " + bd + " MB ");
			// 视频 > 5MB, 或者每秒 > 0.5 MB 才做压缩, 不需要的话可以把判断去掉
			boolean temp = mb > maxSize || bd.compareTo(new BigDecimal(0.5)) > 0;
			if (temp) {
				long time = System.currentTimeMillis();
				// TODO 视频属性设置
				int maxBitRate = 128000;
				int maxSamplingRate = 44100;
				int bitRate = 800000;
				int maxFrameRate = 20;
				int maxWidth = 1280;

				AudioAttributes audio = new AudioAttributes();
				// 设置通用编码格式10
				audio.setCodec("aac");
				// 设置最大值:比特率越高,清晰度/音质越好
				// 设置音频比特率,单位:b (比特率越高,清晰度/音质越好,当然文件也就越大 128000 = 182kb)
				if (audioInfo.getBitRate() > maxBitRate) {
					audio.setBitRate(Integer.valueOf(maxBitRate));
				}

				// 设置重新编码的音频流中使用的声道数(1 =单声道,2 = 双声道(立体声))。如果未设置任何声道值,则编码器将选择默认值 0。
				audio.setChannels(audioInfo.getChannels());
				// 采样率越高声音的还原度越好,文件越大
				// 设置音频采样率,单位:赫兹 hz
				// 设置编码时候的音量值,未设置为0,如果256,则音量值不会改变
				// audio.setVolume(256);
				if (audioInfo.getSamplingRate() > maxSamplingRate) {
					audio.setSamplingRate(maxSamplingRate);
				}

				// TODO 视频编码属性配置
				VideoInfo videoInfo = object.getInfo().getVideo();
				VideoAttributes video = new VideoAttributes();
				video.setCodec("h264");
				if ("avi".equals(suffix)) {
					video.setCodec("mpeg4");
				}
				// 设置音频比特率,单位:b (比特率越高,清晰度/音质越好,当然文件也就越大 800000 = 800kb)
				if (videoInfo.getBitRate() > bitRate) {
					video.setBitRate(bitRate);
				}

				// 视频帧率:15 f / s 帧率越低,效果越差
				// 设置视频帧率(帧率越低,视频会出现断层,越高让人感觉越连续),视频帧率(Frame
				// rate)是用于测量显示帧数的量度。所谓的测量单位为每秒显示帧数(Frames per Second,简:FPS)或“赫兹”(Hz)。
				if (videoInfo.getFrameRate() > maxFrameRate) {
					video.setFrameRate(maxFrameRate);
				}

				// 限制视频宽高
				int width = videoInfo.getSize().getWidth();
				int height = videoInfo.getSize().getHeight();
				if (width > maxWidth) {
					float rat = (float) width / maxWidth;
					video.setSize(new VideoSize(maxWidth, (int) (height / rat)));
				}

				EncodingAttributes attr = new EncodingAttributes();
				attr.setOutputFormat(suffix);
				attr.setAudioAttributes(audio);
				attr.setVideoAttributes(video);
				Encoder encoder = new Encoder();
				encoder.encode(new MultimediaObject(tmpSource), target, attr);
				System.out.println("压缩总耗时:" + (System.currentTimeMillis() - time));
				FileInputStream inputStream = new FileInputStream(target);
				// MultipartFile multipartFile = new MockMultipartFile(picName, picName,
				// ContentType.APPLICATION_OCTET_STREAM.toString(), inputStream);
				return inputStream;
			}
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		finally {
			if (target != null && target.length() > 0) {
				target.delete();
			}
			if (tmpSource != null && tmpSource.length() > 0) {
				tmpSource.delete();
			}
			try {
				return source.getInputStream();
			}
			catch (IOException e) {
				return null;
			}
		}
	}

	/*** 图片格式 */
	private static final String FILE_EXT = "jpg";

	/*** 帧数 */
	private static final int THUMB_FRAME = 5;

	/**
	 * 获取第一帧缩略图
	 * @param videoUrl 视频完整的url
	 * @return 图片路径
	 */
	public static void getThumbnail(File targetFile, String videoUrl) {
		try {
			// 根据扩展名创建一个新文件路径
			File file = saveFile(videoUrl);
			Picture picture = FrameGrab.getFrameFromFile(file, THUMB_FRAME);
			BufferedImage bufferedImage = AWTUtil.toBufferedImage(picture);
			ImageIO.write(bufferedImage, FILE_EXT, targetFile);
		}
		catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static File saveFile(String urlString) {
		try {
			URL url = new URL(urlString);
			InputStream inputStream = url.openStream();
			String tmpPath = System.getProperty("user.dir") + System.getProperty("file.separator") + "tmp.jpg";
			File file = new File(tmpPath);
			OutputStream outputStream = new FileOutputStream(file);

			byte[] buffer = new byte[4096];
			int bytesRead;
			while ((bytesRead = inputStream.read(buffer)) != -1) {
				outputStream.write(buffer, 0, bytesRead);
			}

			outputStream.close();
			inputStream.close();
			return file;
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值