在微信小程序中,您可以通过以下步骤实现获取原始视频的宽高,并将其压缩至指定宽度(如 720 像素):
选择视频:使用 wx.chooseMedia 让用户选择视频文件。
获取视频信息:使用 wx.getVideoInfo 获取视频的原始宽度和高度。
计算分辨率比例:根据目标宽度(如 720 像素)和原始宽度,计算所需的分辨率比例。
压缩视频:使用 wx.compressVideo,设置 resolution 参数为计算得到的比例,压缩视频至目标宽度。
以下是实现上述步骤的示例代码:
Page({
data: {
videoPath: ''
},
chooseAndCompressVideo() {
const targetWidth = 720; // 目标宽度
// 1. 选择视频
wx.chooseMedia({
count: 1,
mediaType: ['video'],
sourceType: ['album', 'camera'],
success: (res) => {
const videoPath = res.tempFiles[0].tempFilePath;
this.setData({ videoPath });
// 2. 获取视频信息
wx.getVideoInfo({
src: videoPath,
success: (info) => {
const originalWidth = info.width;
const originalHeight = info.height;
// 3. 计算分辨率比例
const resolutionRatio = targetWidth / originalWidth;
// 4. 压缩视频
wx.compressVideo({
src: videoPath,
resolution: resolutionRatio,
success: (compressRes) => {
console.log('压缩后的视频路径:', compressRes.tempFilePath);
// 在此处处理压缩后的视频文件,例如上传或保存
},
fail: (err) => {
console.error('视频压缩失败:', err);
}
});
},
fail: (err) => {
console.error('获取视频信息失败:', err);
}
});
},
fail: (err) => {
console.error('选择视频失败:', err);
}
});
}
}); 注意事项:
resolution 参数:wx.compressVideo 的 resolution 参数接受一个 (0, 1] 范围内的值,表示相对于原视频的分辨率比例。通过计算目标宽度与原始宽度的比值,可以得到合适的 resolution 值。例如,若原始视频宽度为 1440 像素,目标宽度为 720 像素,则 resolution 应设置为 0.5。
视频宽高比:上述方法保持了视频的宽高比不变。如果需要调整视频的高度,可以根据原始视频的宽高比,计算目标高度。
基础库版本要求:wx.compressVideo 接口在基础库 2.11.0 及以上版本支持。请确保您的小程序基础库版本满足要求。
通过上述步骤,您可以在微信小程序中实现视频的选择、获取原始尺寸、计算压缩比例,并将视频压缩至指定的宽度。
网友回复
systemd-nspawn与unshare区别?
Firejail、Bubblewrap沙箱与docker、podman容器区别?
如何访问unshare -n -- python3 -m http.server 8000创建的网站url?
linux中如何限制进程执行非法的系统调用命令,例如reboot 删除等等?
pivot_root与chroot有啥区别?
linux中如何限制进程使用cpu、内存、网络的最大值?
用户态沙箱、硬件隔离、namespace + cgroups的隔离有啥不同?
OverlayFS、AUFS 、 Btrfs的区别是啥?
linux上各种Namespace有啥作用?
linux体积最小最精简的版本是多大?


