JavaScript

超轻量级php框架startmvc

Vue自定义指令结合阿里云OSS优化图片的实现方法

更新时间:2020-09-23 03:48:01 作者:startmvc
图片往往在加载前端项目中占大头,如何既不损失图片质量,又提升加载速度呢?根据显示

图片往往在加载前端项目中占大头,如何既不损失图片质量,又提升加载速度呢?

  • 根据显示设备pixelRatio和元素宽高来显示合适图片
  • 略微压缩图片质量
  • 使用webp

注册全局自定义指令


Vue.directive('img-condense', {
 bind: (el, binding, vnode) => {
 let src = el.getAttribute('src')
 let newSrc = compressImg(src, el)
 el.setAttribute('src', newSrc)
 }
})

获取元素宽高和显示设备pixelRatio


let compressImg = (imgUrl, el) => {
 // 获取显示设备 pixelRatio
 let pixelRatio = window.devicePixelRatio
 let elWidth = elStyle.width * pixelRatio
 let elHeight = elStyle.height * pixelRatio
 let resize = '/resize'
 if (elWidth) {
 resize += `,w_${elWidth}`
 }
 if (elHeight) {
 resize += `,h_${elHeight}`
 }
})

判断webp


let canUseWebp = document.createElement('canvas').toDataURL('image/webp').indexOf('data:image/webp') == 0
let webp = ''
if (canUseWebp) {
 webp = '/format,webp'
}

质量降低至80%


let ossParam?x-oss-process=image${resize}/auto-orient,1/quality,Q_80/bright,-1${webp}

完整版


<img v-img-condense alt="Vue logo" src="../assets/logo.png">
Vue.directive('img-condense', {
 bind: (el, binding, vnode) => {
 let src = el.getAttribute('src')
 let newSrc = compressImg(src, el)
 el.setAttribute('src', newSrc)
 }
})
let compressImg = (imgUrl, el) => {
 // 如果不是oss 或者已经压缩过的图片直接返回
 if (imgUrl.includes('aliyuncs.com') || imgUrl.indexOf('blob') === 0 || imgUrl.includes('x-oss-process=')){
 return imgUrl 
 }
 // 获取显示设备 pixelRatio
 let pixelRatio = window.devicePixelRatio
 let elWidth = el.width * pixelRatio
 let elHeight = el.height * pixelRatio
 let resize = '/resize'
 if (elWidth) {
 resize += `,w_${elWidth}`
 }
 if (elHeight) {
 resize += `,h_${elHeight}`
 }
 if (!elWidth && !elHeight) {
 resize = ''
 }
 // 判断webp
 let canUseWebp = document.createElement('canvas').toDataURL('image/webp').indexOf('data:image/webp') == 0
 let webp = ''
 if (canUseWebp) {
 webp = '/format,webp'
 }
 return `${imgUrl}?x-oss-process=image${resize}/auto-orient,1/quality,Q_80/bright,-1${webp}`
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

Vue 阿里云OSS优化图片 Vue 优化图片 Vue 阿里oss图片