element-ui 图片压缩上传

picture.js

js 复制代码
export const compressImgNew = (file) => {
  return new Promise(resolve => {
    const reader = new FileReader()
    const image = new Image()
    image.onload = (imageEvent) => {
      const canvas = document.createElement('canvas') // 创建画布
      const context = canvas.getContext('2d')         // 画布为2d
      // const width = image.width / 1.05        // 图片宽度 / 压缩比例
      // const height = image.height / 1.05        // 图片高度 / 压缩比例
      const width = image.width / 3       // 图片宽度 / 压缩比例
      const height = image.height / 3       // 图片高度 / 压缩比例
      canvas.width = width                            // 画布宽度
      canvas.height = height                          // 画布宽度
      context.clearRect(0, 0, width, height)
      context.drawImage(image, 0, 0, width, height)
      const dataUrl = canvas.toDataURL(file.type)     //图片转路径
      const blobData = dataURLtoBlob(dataUrl, file.type) //图片转二进制
      resolve(blobData)
    }
    reader.onload = e => { image.src = e.target.result }
    reader.readAsDataURL(file)
  })
};

//图片转二进制
function dataURLtoBlob(dataURL, type) {
  var binary = atob(dataURL.split(',')[1])
  var array = []
  for (var i = 0; i < binary.length; i++) {
    array.push(binary.charCodeAt(i))
  }
  return new Blob([new Uint8Array(array)], { type: type })
}

使用

import { compressImgNew } from "@/assets/js/picture.js";

js 复制代码
    beforeAvatarUpload(file) {
      let types = [
        "image/jpeg",
        "image/jpg",
        "image/png"
      ];
      const isImage = types.includes(file.type);
      const isLtSize = file.size / 1024 / 1024 < 5;
      if (!isImage) {
        this.$message.warning("上传图片只能是 JPG、JPEG、PNG 格式!");
        return false;
      }
      if (!isLtSize) {
        this.$message.warning("上传图片大小不能超过 5MB!");
        return false;
      }
      return compressImgNew(file);
    },
相关推荐
其实防守也摸鱼1 小时前
Day 3 · Agent Loop:从调用模型到控制循环 —— 课件精讲笔记
服务器·开发语言·javascript·数据库·人工智能·笔记·ecmascript
夕水1 小时前
我把颜色选择器拆成了 15 个插件,最后长成了 22 个包
前端·javascript·typescript
大今野2 小时前
2026 专转本计算机|移动互联网关键技术:SOA、Web2.0 与 HTML5 考点全解(附例题)
前端·html·html5·专转本
JudithHuang2 小时前
Vue3 与后端联调:代理、Mock 与接口约定
前端·vue
Swot2 小时前
工具转换 vs LLM 转换:以 Markdown 转 AsciiDoc 为例
前端
uuware2 小时前
Lupine.js 的 Native 5 端实现:一套代码覆盖 iOS、Android、macOS、Windows 和 Web
前端·typescript
用户88956195481712 小时前
戴上眼镜就把今天听完:绿光快报的 AIUI 语音新闻智能体
javascript
lisw053 小时前
前端:概念、历史、内容、挑战与展望!
前端
stormsha3 小时前
ResizeObserver loop completed with undelivered notifications:它只是个警告,但也是你代码的供词
javascript·css