当前位置:首页 > VUE

vue实现图片压缩

2026-02-18 07:18:32VUE

使用 canvas 实现图片压缩

在 Vue 中可以通过 canvas 的 drawImagetoDataURL 方法实现图片压缩。创建一个方法接收 File 对象和压缩比例参数,返回压缩后的 base64 或 Blob 对象。

vue实现图片压缩

function compressImage(file, quality = 0.8) {
  return new Promise((resolve) => {
    const reader = new FileReader()
    reader.onload = (e) => {
      const img = new Image()
      img.onload = () => {
        const canvas = document.createElement('canvas')
        const ctx = canvas.getContext('2d')
        canvas.width = img.width
        canvas.height = img.height
        ctx.drawImage(img, 0, 0, canvas.width, canvas.height)
        canvas.toBlob(
          (blob) => resolve(blob),
          'image/jpeg',
          quality
        )
      }
      img.src = e.target.result
    }
    reader.readAsDataURL(file)
  })
}

集成到 Vue 组件

在组件中创建文件上传 input,调用压缩方法后显示预览或上传到服务器。

vue实现图片压缩

<template>
  <div>
    <input type="file" @change="handleUpload" accept="image/*">
    <img v-if="previewUrl" :src="previewUrl" style="max-width: 300px">
  </div>
</template>

<script>
export default {
  data() {
    return {
      previewUrl: ''
    }
  },
  methods: {
    async handleUpload(e) {
      const file = e.target.files[0]
      if (!file) return

      const compressedBlob = await compressImage(file)
      this.previewUrl = URL.createObjectURL(compressedBlob)

      // 上传逻辑
      const formData = new FormData()
      formData.append('image', compressedBlob, file.name)
      // axios.post('/upload', formData)
    }
  }
}
</script>

使用第三方库

对于更复杂的压缩需求,可以使用专门的处理库:

  1. compressorjs - 提供更多压缩选项
    npm install compressorjs
import Compressor from 'compressorjs'

new Compressor(file, {
  quality: 0.6,
  success(result) {
    // 处理压缩结果
  }
})
  1. image-conversion - 支持多种输出格式
    npm install image-conversion
import * as imageConversion from 'image-conversion'

imageConversion.compress(file, 0.5).then(res => {
  // 处理压缩结果
})

注意事项

  • 大图片压缩时需要考虑内存问题,建议限制上传文件大小
  • 移动端拍摄的照片可能包含 EXIF 旋转信息,需要正确处理方向
  • 不同格式图片压缩效果不同,JPEG 适合照片,PNG 适合带透明度的图片
  • 压缩比例需要根据实际需求调整,过高的压缩会导致明显质量下降

标签: 图片vue
分享给朋友:

相关文章

vue 实现级联

vue 实现级联

Vue 实现级联选择器 级联选择器(Cascader)常用于省市区选择、分类选择等场景。Vue 中可以通过 Element UI、Ant Design Vue 等 UI 库实现,也可以手动封装。 使…

vue实现grid

vue实现grid

Vue 实现 Grid 布局的方法 使用 CSS Grid 布局 Vue 可以结合 CSS Grid 布局实现灵活的网格系统。CSS Grid 是现代浏览器原生支持的布局方案,无需额外依赖库。 &l…

vue实现route

vue实现route

Vue 路由实现方法 Vue 中实现路由通常使用 vue-router 库,这是 Vue 官方推荐的路由管理器。以下是具体实现步骤: 安装 vue-router 通过 npm 或 yarn 安装…

vue实现active

vue实现active

Vue 实现 active 状态的方法 在 Vue 中实现 active 状态可以通过以下几种方式实现,具体取决于使用场景和需求。 使用 v-bind:class 动态绑定类名 通过 v-bind:…

vue原理实现

vue原理实现

Vue 原理实现的核心机制 Vue.js 的核心原理基于响应式系统、虚拟 DOM 和模板编译。以下是其核心实现机制的分解: 响应式系统 Vue 使用 Object.defineProperty(Vu…

实现vue table

实现vue table

Vue 表格实现方法 基础表格实现 使用 Vue 的 v-for 指令可以快速渲染表格数据。在模板中定义表格结构,通过数据绑定动态生成行和列。 <template> <tabl…