JavaScript前端实现压缩图片功能

  1. 通过原生的input标签拿到要上传的图片文件
  2. 将图片文件转化成img元素标签
  3. 在canvas上压缩绘制该HTMLImageElement
  4. 将canvas绘制的图像转成blob文件
  5. 最后将该blob文件传到服务端

1. 使用Input标签来获取图片文件资源

原生input标签,通过设置 type 属性为file来让用户可以选择文件,设置 accept 限制选择的文件类型,绑定onchange事件,来获取确认选择后的文件

<input type="file" accept="image/*" />

点击控件,触发焦点,打开文件资源管理器,选中文件并确认后,会触发change事件,所以可以在change事件的回调中获取选中文件,它长这个样
在这里插入图片描述

2. 读取文件转成img标签元素

拿到图片文件后,先将其转成HTMLImageElement,也就是普通的img标签,具体要使用 FileReader构造函数。
先new出来一个img和fileReader的实例,通过fileReader的 readAsDataURL这个api,来读取图片文件,其返回值是一个编码后的base64的字符串,然后将这个字符串赋值给img的src属性上,这样就完成了图片文件到 HTMLImageElement的转化。

// 先new一个img和fileReader的实例
const img = new Image()
const reader = new FileReader()// 读取文件资源
reader.readAsDataURL(file) 
reader.onload = function(e){ 
 img.src = e.target.result
}

转化的HTMLImageElement
在这里插入图片描述

3. canvas压缩,核心步骤

拿到转化后的img元素后,先取出该元素的宽高度,这个宽高度就是实际图片文件的宽高度。

const { width: originWidth, height: originHeight } = img

然后定义一个最大限度的宽高度,如果超过这个限制宽高度,则进行等比例的缩放

// 最大尺寸限制
const maxWidth = 1000,maxHeihgt = 1000
// 需要压缩的目标尺寸
let targetWidth = originWidth, targetHeight = originHeight
// 等比例计算超过最大限制时缩放后的图片尺寸
if (originWidth > maxWidth || originHeight > maxHeight) {
  if (originWidth / originHeight > 1) {
   // 宽图片
   targetWidth = maxWidth
   targetHeight = Math.round(maxWidth * (originHeight / originWidth))
  } else {
   // 高图片
   targetHeight = maxHeight
   targetWidth = Math.round(maxHeight * (originWidth / originHeight))
  }
 }

计算好将要压缩的尺寸后,创建canvas实例,设置canvas的宽高度为压缩计算后的尺寸,并将img绘制到上面

// 创建画布
const canvas = document.createElement('canvas')
const context = canvas.getContext('2d')
 
// 设置宽高度为等同于要压缩图片的尺寸
 canvas.width = targetWidth
 canvas.height = targetHeight
 context.clearRect(0, 0, targetWidth, targetHeight)
 //将img绘制到画布上
 context.drawImage(img, 0, 0, targetWidth, targetHeight)

4. 转成blob文件

canvas绘制完成后,就可以使用 toBlob来将图像转成blob文件了,这个api接受三个入参

canvas.toBlob(callback, type, encoderOptions);

回调函数中可以得到转化后的blob文件,type为要转成的图片类型,默认png。
encoderOptions为当设置的图片格式为 image/jpeg 或者 image/webp 时用来指定图片展示质量。
所以如果我们只是要压缩jpg或者webp格式的图片的话,不需要进行第3部的操作,直接使用这个api,然后填入想要的质量参数就可以了。但实际上,我们还是要考虑多种的图片格式,因此很有必要使用第三部的过程。
转成的blob长这个样子
在这里插入图片描述

5. 将blob上传,大功告成。

完整的代码实现
因为整个过程中都存在着异步回调操作,所以我使用了async,实现异步代码的同步执行

// 压缩前将file转换成img对象
function readImg(file) {
 return new Promise((resolve, reject) => {
  const img = new Image()
  const reader = new FileReader()
  reader.onload = function(e) {
   img.src = e.target.result
  }
  reader.onerror = function(e) {
   reject(e)
  }
  reader.readAsDataURL(file)
  img.onload = function() {
   resolve(img)
  }
  img.onerror = function(e) {
   reject(e)
  }
 })
}
/**
 * 压缩图片
 *@param img 被压缩的img对象
 * @param type 压缩后转换的文件类型
 * @param mx 触发压缩的图片最大宽度限制
 * @param mh 触发压缩的图片最大高度限制
 */
function compressImg(img, type, mx, mh) {
 return new Promise((resolve, reject) => {
  const canvas = document.createElement('canvas')
  const context = canvas.getContext('2d')
  const { width: originWidth, height: originHeight } = img
  // 最大尺寸限制
  const maxWidth = mx
  const maxHeight = mh
  // 目标尺寸
  let targetWidth = originWidth
  let targetHeight = originHeight
  if (originWidth > maxWidth || originHeight > maxHeight) {
   if (originWidth / originHeight > 1) {
    // 宽图片
    targetWidth = maxWidth
    targetHeight = Math.round(maxWidth * (originHeight / originWidth))
   } else {
    // 高图片
    targetHeight = maxHeight
    targetWidth = Math.round(maxHeight * (originWidth / originHeight))
   }
  }
  canvas.width = targetWidth
  canvas.height = targetHeight
  context.clearRect(0, 0, targetWidth, targetHeight)
  // 图片绘制
  context.drawImage(img, 0, 0, targetWidth, targetHeight)
  canvas.toBlob(function(blob) {
   resolve(blob)
  }, type || 'image/png') })
}

大致执行过程,具体可根据需求,自行改动

async function upload(file){
  const img = await readImg(file)
  const blob = await compressImg(img, file.type, 1000, 1000)
  const formData = new FormData()
  formData.append('file', blob, 'xxx.jpg')
  axios.post('http://xxx.com/api',formData)
}
upload(file).catch(e => console.log(e))
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值