zoukankan      html  css  js  c++  java
  • js 图片压缩

    代码如下:

     1 compressImage(file) {
     2       // 参数file,是通过input 选择本地文件获取的
     3       return new Promise((resolve, reject) => {
     4         const { type, name } = file.file
     5         let img = new Image()
     6         // 创建一个reader实例
     7         let reader = new FileReader()
     8 
     9         // 读取拿到的文件
    10         reader.readAsDataURL(file.file)
    11         reader.onload = function(e) {
    12 
    13           // 文件加载成功后去转成Img对象,为了拿到图片的原始宽高
    14           img.src = e.target.result
    15           img.onload = function() {
    16             // 创建画布canvas
    17             let canvas = document.createElement('canvas')
    18             let content = canvas.getContext('2d')
    19 
    20             // 设置画布的宽高
    21             canvas.width = img.width  // 需要压缩到的图片宽度
    22             canvas.height = img.width * (img.height / img.width)
    23 
    24             // 将图片画在画布上
    25             content.drawImage(img, 0, 0, canvas.width, canvas.height)
    26 
    27             //画布转成blob格式的图片
    28             canvas.toBlob(function(blob) {
    29               // blob 格式的图片 转成file对象,这里主要看接口支不支持blob格式的文件上传,如果支持就没有必要转
    30               let file = new File([blob], name, { type: type })
    31               resolve({type: type, compressFile: file})
    32             }, `image/${type.split('/')[1]}`, 0.7)  // 0.7 是文件压缩程度
    33           }
    34         }
    35       })
    36     },

    有问题可以评论哦

  • 相关阅读:
    t
    溢出
    https://stackoverflow.com/questions/45591594/fetch-does-not-send-headers
    显示在用户屏幕上的缩略图
    cache buffer
    LZW
    t
    指针悬挂
    使用Linux服务器来通过网络安装和激活Windows 7 —— 一些基本原理
    在C++中如何动态分配一个二维数组
  • 原文地址:https://www.cnblogs.com/yyh1/p/13719797.html
Copyright © 2011-2022 走看看