让前端飞我在互联网金融做前端

前端常用的小函数(2)---图片的处理

2018-08-15  本文已影响4人  Null_大大

需要从服务器读取图片到页面(图片大小未知),或者上传图片到服务器(图片体积过大,需要压缩) ,此外后端可能能对post请求有设置。

知识罗列

1.从URL 读取图片信息
2.从本地上传图片
3.前端图片压缩
4.canvas 压缩图片的处理
5.base64转Blob

-Talk is cheap, show me your code

handleChange = async (e, compressRatio = 0.5) => {
  const file = e.target.files[0];
  const { base64file, paddingTop } = await handleFile(file);
  const { compressedBase64File } = await handleCompressFile(
    file,
    compressRatio
  );
  const origin = base64toBlob(base64file);
  const compress = base64toBlob(compressedBase64File);
  const originSize = (origin.size / 1000).toFixed(2);
  const compressSize = (compress.size / 1000).toFixed(2);
  const compressRate = `${(
    (originSize - compressSize) /
    originSize *
    100
  ).toFixed(2)}%`;
  return {
    originStyle: {
      backgroundImage: `url(${base64file})`,
      paddingTop
    },
    compressStyle: {
      backgroundImage: `url(${compressedBase64File})`,
      paddingTop
    },
    originSize,
    compressSize,
    compressRate
  };
};

// 获取原始图片信息
handleFile = async file => {
  const { originFile, base64file, originSize } = await getBase64File(file);
  const { width, height } = await getImageParams(base64file);
  const paddingTop = `${height / width * 100}%`;
  return { originFile, base64file, originSize, width, height, paddingTop };
};

// 获取压缩图片信息
handleCompressFile = async (file, compressRatio) => {
  const { base64file } = await getBase64File(file);
  const { width, height } = await getImageParams(base64file);
  const targetWidth = width * compressRatio;
  const targetHeight = height * compressRatio;
  // 创建Image 对象
  const image = new Image();
  image.src = base64file;
  // 创建画布
  const canvas = document.createElement("canvas");
  const context = canvas.getContext("2d");
  canvas.width = targetWidth;
  canvas.height = targetHeight;

  context.fillStyle = "rgba(255,255,255,1)";
  context.fillRect(0, 0, targetWidth, targetHeight);
  context.drawImage(image, 0, 0, targetWidth, targetHeight);
  const compressedBase64File = canvas.toDataURL("image/jpeg", compressRatio);
  return { compressedBase64File };
};

// file 2 base64
getBase64File = file =>
new Promise((resolve, reject) => {
  const reader = new FileReader();
  const result = {};
  reader.readAsDataURL(file);
  reader.onload = () => {
    result.base64file = reader.result;
    result.originFile = file;
    result.originSize = file.size;
    resolve(result);
  };
  reader.onerror = error => reject(error);
});

// 通过base64file获取图像尺寸(把base64file换成图片的url,即可通过url获取图片信息,常用来加载cdn的未知图片)
getImageParams = base64file =>
new Promise((resolve, reject) => {
  const image = new Image();
  image.src = base64file;
  image.onload = function() {
    const width = this.width;
    const height = this.height;
    resolve({ width, height });
  };
  image.onerror = error => reject(error);
});

// 由于后端post请求的限制 ,可以根据具体情况确定是否 需要把 base64转为 blob
base64toBlob = (base64file, contentType = "image/jpg", sliceSize = 512) => {
  // 参考 https://stackoverflow.com/questions/16245767/creating-a-blob-from-a-base64-string-in-javascript
  const byteCharacters = atob(base64file.split(",")[1]);
  const byteArrays = [];
  for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
    const slice = byteCharacters.slice(offset, offset + sliceSize);
    const byteNumbers = new Array(slice.length);
    for (let i = 0; i < slice.length; i += 1) {
      byteNumbers[i] = slice.charCodeAt(i);
    }
    const byteArray = new Uint8Array(byteNumbers);
    byteArrays.push(byteArray);
  }
  return new Blob(byteArrays, { type: contentType });
};

$(function() {
  $("#file").on("change", async function(e) {
    const {
      originStyle,
      compressStyle,
      originSize,
      compressSize,
      compressRate
    } = await handleChange(e);

    // 原始图片预览
    $(".origin").css({
      "padding-top": originStyle.paddingTop,
      "background-image": originStyle.backgroundImage
    });
    // 压缩图片
    $(".compress").css({
      "padding-top": compressStyle.paddingTop,
      "background-image": compressStyle.backgroundImage
    });

    // 信息展示
    $(".massage").html(`
<div>原始图片大小:${originSize}k</div>
<div>压缩图片大小:${compressSize}k</div>
<div>压缩比:${compressRate}</div>
`);
  });
});

在线demo

上一篇下一篇

猜你喜欢

热点阅读