react 图片压缩工具(可下载)

用到的插件:compressorjs

示例:

ExampleCanvas.js

import React from 'react';
import { compressorImage } from './Compressor'

export default class UploadPic extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      previewPic: '',
      laterPic: ''
    };
    this.handleUpload = this.handleUpload.bind(this);
    this.downloadImg = this.downloadImg.bind(this);
  }

  downloadImg(){
    // console.log('download',this.state.laterPic);
    var blob=this.dataURLtoBlob(this.state.laterPic)
    const aLink = document.createElement('a');
        document.body.appendChild(aLink);
        aLink.style.display='none';
        const objectUrl = window.URL.createObjectURL(blob);
        aLink.href = objectUrl;
        // 修改目标图片名字
        // aLink.download = 'a.png';
         aLink.download =document.getElementById('file').value.substring(document.getElementById('file').value.lastIndexOf('\\') + 1);
        aLink.click();
  }

  dataURLtoBlob(dataurl) {
    var arr = dataurl.split(',');
     //注意base64的最后面中括号和引号是不转译的   
     var _arr = arr[1].substring(0,arr[1].length-2);
     var mime = arr[0].match(/:(.*?);/)[1],
       bstr =atob(_arr),
       n = bstr.length,
       u8arr = new Uint8Array(n);
     while (n--) {
       u8arr[n] = bstr.charCodeAt(n);
     }
     return new Blob([u8arr], {
       type: mime
     });
   }

  handleUpload(e) {
    // console.log('啊哈!', e.target.files[0]);

    var myFile = this.A(e.target.files[0]);
    // console.log('---------myFile----------', myFile);
    const reader = new FileReader();
    reader.readAsDataURL(e.target.files[0]);
    reader.onload = function (e) {
      // console.log(e.target.result);  // 上传的图片的编码
      this.setState({
        previewPic:e.target.result
      });
    }.bind(this);
  }

  A = async (file) => {
    var myfile = await compressorImage(file, 'file', 0.6)
    // console.log('----myfie-----',myfile);
    const reader = new FileReader();
    reader.readAsDataURL(myfile);
    reader.onload = function (e) {
      // console.log(e.target.result);  // 上传的图片的编码
      this.setState({
        previewPic:this.state.previewPic,
        laterPic: e.target.result
      });
    }.bind(this);
    return myfile
  }

  render() {
    const { previewPic, laterPic } = this.state;
    return (
      
) } }

核心工具:

Compressor.js

import React from 'react'
import Compressor from 'compressorjs';


/**
 * @param image 图片
 * @param backType 需要返回的类型blob,file
 * @param quality 图片压缩比 0-1,数字越小,图片压缩越小
 * @returns
 */
export const compressorImage = (image, backType, quality) => {
  // console.log('image, backType, quality',image, backType, quality);
  return new Promise((resolve, reject) => {
    new Compressor(image, {
      quality: quality || 0.8,
      mimeType :'image/jpeg',
      success(result) {
        // console.log('result', result)
        let file = new File([result], image.name, { type: image.type })

        if (!backType || backType == 'blob') {
          resolve(result)
        } else if (backType == 'file') {
          resolve(file)
        } else {
          resolve(file)
        }
        console.log('图片压缩成功---->>>>>')
      },
      error(err) {
        console.log('图片压缩失败---->>>>>', err)
        reject(err)
      }
    })
  })
}


你可能感兴趣的:(react,react.js,前端)