oss技能应用
阿里云OSS图片压缩
通过OSS图片处理参数,在图片URL后拼接处理参数实现服务端压缩,无需下载原图到本地处理。
typescript
/**
* OSS图片压缩 - 通过URL拼接图片处理参数
* @param url 原始OSS图片地址
* @param options 压缩配置
* @returns 处理后的图片URL
*/
interface OssImageCompressOptions {
/** 图片质量 1-100 */
quality?: number;
/** 目标宽度(px) */
width?: number;
/** 目标高度(px) */
height?: number;
/** 缩放模式: lfit(等比缩放限制在指定矩形内) | mfit(等比缩放覆盖指定矩形) | fill(裁剪填充) | pad(填充留白) | fixed(强制缩放) */
mode?: 'lfit' | 'mfit' | 'fill' | 'pad' | 'fixed';
/** 输出格式: jpg | png | webp | gif | bmp */
format?: 'jpg' | 'png' | 'webp' | 'gif' | 'bmp';
}
function getOssImageCompressUrl(url: string, options: OssImageCompressOptions = {}): string {
const { quality = 80, width, height, mode = 'lfit', format } = options;
const params: string[] = [];
// 缩放处理
if (width || height) {
let resizeParam = `image/resize,m_${mode}`;
if (width) resizeParam += `,w_${width}`;
if (height) resizeParam += `,h_${height}`;
params.push(resizeParam);
}
// 质量压缩
params.push(`image/quality,q_${quality}`);
// 格式转换
if (format) {
params.push(`image/format,${format}`);
}
const separator = url.includes('?') ? '&' : '?';
return `${url}${separator}x-oss-process=${params.join('/')}`;
}
// 应用样例:
// https://xxx.cn/xxx/04141922_b70be276.jpg?x-oss-process=image/format,webp/quality,q_20
//
// 使用示例:
const compressedUrl = getOssImageCompressUrl('https://xxx.cn/xxx/04141922_b70be276.jpg', {
quality: 20,
format: 'webp'
});
//
阿里云oss视频帧
通过OSS视频处理参数,在图片URL后拼接处理参数实现服务端压缩,无需下载原视频到本地处理。
typescript
/**
* OSS视频截帧 - 通过URL拼接视频截帧参数
* @param url 原始OSS视频地址
* @param options 截帧配置
* @returns 截帧图片URL
*
*/
interface OssVideoSnapshotOptions {
/** 截帧时间点(ms) */
time?: number;
/** 截图宽度(px),如果指定为0则自动计算 */
width?: number;
/** 截图高度(px),如果指定为0则自动计算 */
height?: number;
/** 截帧模式: fast(关键帧) | accurate(精确帧) */
mode?: 'fast' | 'accurate';
/** 输出格式: jpg | png */
format?: 'jpg' | 'png';
}
function getOssVideoSnapshotUrl(url: string, options: OssVideoSnapshotOptions = {}): string {
const { time = 0, width = 0, height = 0, mode = 'fast', format = 'jpg' } = options;
let snapshotParam = `video/snapshot,t_${time},f_${format},m_${mode}`;
if (width) {
snapshotParam += `,w_${width}`;
}
if (height) {
snapshotParam += `,h_${height}`;
}
const separator = url.includes('?') ? '&' : '?';
return `${url}${separator}x-oss-process=${snapshotParam}`;
}
// 应用样例:
// https://xxx.cn/xxx/04152014_8defc4e0.mp4?x-oss-process=video/snapshot,t_1000,f_jpg,w_800,h_0,m_fast
//
// 使用示例:
const thumbnailUrl = getOssVideoSnapshotUrl('https://xxx.cn/xxx/04152014_8defc4e0.mp4', {
time: 1000,
format: 'jpg',
width: 800,
height: 0,
mode: 'fast'
});