base64串格式的图片压缩,base64与二进制流type[]互转

历史背景:

最近项目与硬件设备进行联调,硬件服务返回的指纹图片是一个base64串,前端页面要做图片展示,同时后端要保存,因为太大,有160kb左右,一般情况下,logo头像上传,不超过10kb的才有base64可以,这里前端需要对图片进行压缩,以为我们后端也没有longText类型接收,而是type[]格式接受参数。

这里我们的文件格式是图片哈!

private mine = 'data:image/jpeg;base64,';

解决方案:

1.通过canvas绘图API:
HTMLCanvasElement.drawImage()
ctx.drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight);
示例对照
对图像进行压缩,剪裁,缩放等操作,具体细节查看API文档

HTMLCanvasElement.toDataURL()
官网文档示例
再次拿到base64串

var canvas = document.getElementById('canvas');
var dataURL = canvas.toDataURL();
console.log(dataURL);
// "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNby
// blAAAADElEQVQImWNgoBMAAABpAAFEI8ARAAAAAElFTkSuQmCC"

图片压缩方法

/**
   * 压缩base64串
   * @param base64String 图片字符串,注意必须是带格式的base64
   * @param maxLength 最大高度或宽度
   * @param quality 质量 0-1之间
   */
  reduceBase64 (base64String, maxLength, quality) {
    const getMimeType = (base64: string): string => {
      const arr = base64.split(',');
      const mime = arr[0].match(/:(.*?);/)[1];
      return mime;
    };
    let imgWidth,
        imgHeight;
    const mine = getMimeType(base64String),
          newImage = new Image();
    // onload异步处理
    newImage.src = base64String;
    return new Promise(resolve => {
      newImage.onload = function() {
        imgWidth = newImage.width;
        imgHeight = newImage.height;
        const canvas = document.createElement('canvas'),
          ctx = canvas.getContext('2d');
        if (Math.max(imgWidth, imgHeight) > maxLength) {
          if (imgWidth > imgHeight) {
            canvas.width = maxLength;
            canvas.height = maxLength * imgHeight / imgWidth;
          } else {
            canvas.height = maxLength;
            canvas.width = maxLength * imgWidth / imgHeight;
          }
        } else {
          canvas.width = imgWidth;
          canvas.height = imgHeight;
        }
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        ctx.drawImage(newImage, 0, 0, canvas.width, canvas.height);
        const back = canvas.toDataURL(mine, quality);
        resolve(back);
      };
    });
  }
  1. 技术分析
    atob:
    creates a binary string from a base-64 encoded ASCII string
    btoa:
    creates a base-64 encoded ASCII string from a binary string

function decodes a string of data which has been encoded using base-64 encoding. You can use the btoa() method to encode and transmit data which may otherwise cause communication problems, then transmit it and use the atob() method to decode the data again.

函数对使用base-64编码编码的数据串进行解码。您可以使用btoa()方法对可能导致通信问题的数据进行编码和传输,然后再进行传输并使用atob()方法对数据进行解码。

base64转二进制

/**
   * base64字符串转二进制
   * @param base base64串,去掉头部格式
   */
  Base64ToFile(base: string) {
    const getMimeType = (base64: string): string => {
      const arr = base64.split(',');
      const mime = arr[0].match(/:(.*?);/)[1];
      return mime;
    };
    const bstr = Window.atob(base.slice(getMimeType(base).length));
    let n = bstr.length;
    const u8arr = new Uint8Array(n);
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n);
    }
    return u8arr;
  }

二进制流转base64

/**
   * 二进制转base64字符串
   * @param buffer byte[]
   */
  arrayBufferToBase64( buffer ) {
    let binary = '';
    const bytes = new Uint8Array( buffer );
    const len = bytes.byteLength;
    for (let i = 0; i < len; i++) {
      binary += String.fromCharCode( bytes[ i ] );
    }
    return window.btoa( binary );
  }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值