import axios from "axios"; /** * oss resize 参数 * 详情见 https://help.aliyun.com/document_detail/44688.html?spm=a2c4g.11186623.6.751.7434663c1Ne07e */ interface OSSResizeOptions { scale?: number; w?: number; h?: number; watermark?: string; [key: string]: any; } interface OSSImageInfoOptions { [key: string]: any; } interface ImageInfo { [key: string]: any; } function createParmas(key: string, value: any) { return `${key}_${value}` } export function ossResize(url: string, options: OSSResizeOptions = {}): string { if (!url) return '' try { const target = new URL(url) const parmas = target.searchParams const list = ['image/resize'] //scale 追加scale 参数 默认为2 if(options.scale === undefined){ options.scale = 2 } if(options.w ){ options.w = options.w*options.scale } if(options.h){ options.h = options.h*options.scale } /* // 水印 if (options.watermark) { list.push( createParmas('watermark', { ...options.watermark, }) ) } */ Object.keys(options).forEach((key) => { if(!['watermark','scale'].includes(key)){ const value = options[key] list.push(createParmas(key, value)) } }) const watermark = [] if (options.watermark) { watermark.push('image/watermark') watermark.push('image_' + options.watermark) } let str = list.join(',') if(watermark.length >0){ if(str){ str+= ','+watermark.join(',') }else{ str+= watermark.join(',') } } parmas.set('x-oss-process',str + '/quality,Q_80') return target.toString() } catch (error) { console.warn(url) console.warn(error) return url } } export async function ossImageInfo(url: string, options: OSSImageInfoOptions = {}): Promise { if (!url) return '' try { const target = new URL(url) const parmas = target.searchParams const list = ['image/info'] Object.keys(options).forEach((key) => { const value = options[key] list.push(createParmas(key, value)) }) parmas.set('x-oss-process', list.join(',') + '/quality,Q_80') const ossUrl = target.toString() const { data } = await axios.get(ossUrl) return data } catch (error) { console.error(error) return undefined } }