全栈开发技术分享
首页
👉 CSS大揭秘 👈
  • 目录
  • 分类
  • 标签
  • 归档
  • Vue
  • JavaScript
  • 微信开发
  • 移动端H5调试工具
  • 国内十大前端团队网站
  • Nodejs
  • Egg
  • 环境搭建
  • 运维面板
  • 域名配置
  • Nginx
  • 收藏
  • 常用工具
  • 实用技巧
  • 常用命令
  • 友情链接
关于

Dreaming Lee 🍍 ҉҉҉҉҉҉҉҉

开发小菜鸡
首页
👉 CSS大揭秘 👈
  • 目录
  • 分类
  • 标签
  • 归档
  • Vue
  • JavaScript
  • 微信开发
  • 移动端H5调试工具
  • 国内十大前端团队网站
  • Nodejs
  • Egg
  • 环境搭建
  • 运维面板
  • 域名配置
  • Nginx
  • 收藏
  • 常用工具
  • 实用技巧
  • 常用命令
  • 友情链接
关于
  • 代码规范

    • Eslint
    • Eslint-Plugin-Vue
    • Stylelint
  • uniapp

    • 问题解决

      • 【uniapp】字节小程序BUG - “navigateToMiniProgram/getUserProfile:fail must be invoked by user tap gesture”
  • JavaScript

    • JS验证18位身份证号码
    • JS图片压缩
      • 背景
      • 图片压缩
    • JS调用elementUI图片预览
    • JS图片上传前校验大小、尺寸
  • Vue

    • Vue基础教程

      • Vue教程(1)-基础篇
      • Vue教程(2)-路由篇Vue-Router
      • Vue教程(3)- 状态管理Vuex
    • Vue自定义组件开发

      • Vue实现移动端轮播swiper组件
      • Vue实现switch开关组件
    • Vue扩展

      • Vue接入阿里OSS文件上传
    • Vue学习参考资料
  • 微信开发

    • 微信开发参考资料
    • 微信公众号

      • 微信公众号/订阅号/服务号主动给用户发消息
      • 微信jssdk自定义分享在iOS不生效
    • 微信小程序

      • 微信小程序区分运行环境:开发版/体验版/正式版
      • H5唤醒微信小程序
  • 收藏

    • 国内十大前端团队官网及GitHub
  • 常见问题解决

    • js错误

      • iframe下localStorage禁止访问。“Failed to read the localStorage property from Window”
      • TypeError: Promise.allSettled is not a function
    • IE兼容

      • fixed定位在IE下页面滚动时抖动
  • 工具

    • 移动端H5调试工具
  • 前端
  • JavaScript
Dreaming Lee 🍍 ҉҉҉҉҉҉҉҉
2021-04-01

JS图片压缩

# 背景

随着手机像素越来越高,使用手机拍摄的照片动辄就是几兆或十几兆,在移动端H5上传图片的场景,会造成流量的浪费。特别是在网络不好的情况下,更容易出现上传时间超长甚至是上传失败的问题。

为了提示图片上传体验,故需要在上传前对图片进行压缩。

# 图片压缩

/**
 * 图片压缩
 * @param {File} file 文件
 * @param {Function} success 成功回调,返回压缩后文件
 * @param {File} error 失败回调,返回错误信息
 */
function compressImage(file, success, error) {
  // 图片小于1M不压缩
  if (file.size < Math.pow(1024, 2)) {
    return success(file)
  }

  const name = file.name // 文件名
  const reader = new FileReader()
  reader.readAsDataURL(file)
  reader.onload = (e) => {
    const src = e.target.result

    const img = new Image()
    img.src = src
    img.onload = (e) => {
      const rate = img.width / 1000 > 1 ? img.width / 1000 : 1
      const w = img.width / rate
      const h = img.height / rate
      const quality = 0.9 // 默认图片质量为0.92
      // 生成canvas
      const canvas = document.createElement('canvas')
      const ctx = canvas.getContext('2d')
      canvas.width = w
      canvas.height = h
      console.log(w, h)
      // 铺底色 PNG转JPEG时透明区域会变黑色
      ctx.fillStyle = '#fff'
      ctx.fillRect(0, 0, w, h)
      ctx.drawImage(img, 0, 0, w, h)
      // quality值越小,所绘制出的图像越模糊
      const base64 = canvas.toDataURL('image/jpeg', quality) // 图片格式jpeg或webp可以选0-1质量区间
      // 去掉url的头,并转换为byte
      const bytes = window.atob(base64.split(',')[1])
      // 返回base64转blob的值
      console.log(`原图${(src.length / 1024).toFixed(2)}kb`, `新图${(bytes.length / 1024).toFixed(2)}kb`)
      // 处理异常,将ascii码小于0的转换为大于0
      const ia = new Uint8Array(bytes.length)
      for (let i = 0, len = bytes.length; i < len; i++) {
        ia[i] = bytes.charCodeAt(i)
      }
      file = new File([ ia ], name, { type: 'image/jpeg', lastModified: Date.now() })
      success(file)
    }
    img.onerror = (e) => {
      error(e)
    }
  }
  reader.onerror = (e) => {
    error(e)
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
上次更新: 2021-05-10 14:08:54
JS验证18位身份证号码
JS调用elementUI图片预览

← JS验证18位身份证号码 JS调用elementUI图片预览→

最近更新
01
【uniapp】字节小程序BUG - “navigateToMiniProgram/getUserProfile:fail must be invoked by user tap gesture”
06-21
02
七牛云上传自有证书
04-27
03
使用腾讯云申请免费SSL证书
04-27
更多文章>
Theme by Vdoing | Copyright © 2020-2024 | 豫ICP备2020030395号 | 靳立祥 | MIT License
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式