oss.ts 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. import axios from "axios";
  2. /**
  3. * oss resize 参数
  4. * 详情见 https://help.aliyun.com/document_detail/44688.html?spm=a2c4g.11186623.6.751.7434663c1Ne07e
  5. */
  6. interface OSSResizeOptions {
  7. scale?: number;
  8. w?: number;
  9. h?: number;
  10. watermark?: string;
  11. [key: string]: any;
  12. }
  13. interface OSSImageInfoOptions {
  14. [key: string]: any;
  15. }
  16. interface ImageInfo {
  17. [key: string]: any;
  18. }
  19. function createParmas(key: string, value: any) {
  20. return `${key}_${value}`
  21. }
  22. export function ossResize(url: string, options: OSSResizeOptions = {}): string {
  23. if (!url) return ''
  24. try {
  25. const target = new URL(url)
  26. const parmas = target.searchParams
  27. const list = ['image/resize']
  28. //scale 追加scale 参数 默认为2
  29. if(options.scale === undefined){
  30. options.scale = 2
  31. }
  32. if(options.w ){
  33. options.w = options.w*options.scale
  34. }
  35. if(options.h){
  36. options.h = options.h*options.scale
  37. }
  38. /*
  39. // 水印
  40. if (options.watermark) {
  41. list.push(
  42. createParmas('watermark', {
  43. ...options.watermark,
  44. })
  45. )
  46. }
  47. */
  48. Object.keys(options).forEach((key) => {
  49. if(!['watermark','scale'].includes(key)){
  50. const value = options[key]
  51. list.push(createParmas(key, value))
  52. }
  53. })
  54. const watermark = []
  55. if (options.watermark) {
  56. watermark.push('image/watermark')
  57. watermark.push('image_' + options.watermark)
  58. }
  59. let str = list.join(',')
  60. if(watermark.length >0){
  61. if(str){
  62. str+= ','+watermark.join(',')
  63. }else{
  64. str+= watermark.join(',')
  65. }
  66. }
  67. parmas.set('x-oss-process',str + '/quality,Q_80')
  68. return target.toString()
  69. } catch (error) {
  70. console.warn(url)
  71. console.warn(error)
  72. return url
  73. }
  74. }
  75. export async function ossImageInfo(url: string, options: OSSImageInfoOptions = {}): Promise<ImageInfo | undefined> {
  76. if (!url) return ''
  77. try {
  78. const target = new URL(url)
  79. const parmas = target.searchParams
  80. const list = ['image/info']
  81. Object.keys(options).forEach((key) => {
  82. const value = options[key]
  83. list.push(createParmas(key, value))
  84. })
  85. parmas.set('x-oss-process', list.join(',') + '/quality,Q_80')
  86. const ossUrl = target.toString()
  87. const { data } = await axios.get(ossUrl)
  88. return data
  89. } catch (error) {
  90. console.error(error)
  91. return undefined
  92. }
  93. }