美文网首页让前端飞我在互联网金融做前端
前端常用的小函数(2)---图片的处理

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

作者: Null_大大 | 来源:发表于2018-08-15 12:14 被阅读4次
  • 需求背景

需要从服务器读取图片到页面(图片大小未知),或者上传图片到服务器(图片体积过大,需要压缩) ,此外后端可能能对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

相关文章

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

    需求背景 需要从服务器读取图片到页面(图片大小未知),或者上传图片到服务器(图片体积过大,需要压缩) ,此外后端可...

  • mysql常用函数

    1、常用日期时间处理函数 2、常用字符串处理函数 3、流程控制函数 4、进制转换函数

  • SQL中常用的文本处理函数和日期时间处理函数

    SQL中常用的文本处理函数和日期时间处理函数 常用文本处理函数 CONCAT(str1, str2, ...):拼...

  • C++常用库函数

    1.常用数学函数 #include 2.常用字符串处理函数 #include 3.其他常用函数 ...

  • photoshop常用图片处理技巧

    仅供学习,转载请注明出处 photoshop常用图片处理技巧 photoshop是一款优秀的图像处理软件,作为前端...

  • ES5和ES6常用数据处理函数

    ES5和ES6常用数据处理函数 前言 现代前端并不是画画静态页面那么简单,很多以前后端的数据处理都放到了前端,由于...

  • 前端如何使用canvas做图片处理

    ),可以选的方案两个: 1、前端使用canvas做图片处理; 2、服务端引用图片处理的类库来做图片处理 两个方案都...

  • 热更新03_标准库函数Day1128

    Lua内置提供了一些常用的函数帮助我们开发 1,数学处理的math相关函数 2,字符串处理的string相关函数 ...

  • MySQL 11-12章实操

    第十一章 使用数据处理函数 文本处理函数[常用的文本处理函数说明表] 常用的文本处理函数中locate()和sub...

  • JavaScript函数02

    目录 常用事件和事件处理函数 递归函数 函数的属性和方法 函数的作用域 常用事件和事件处理函数 事件参考--MDN...

网友评论

    本文标题:前端常用的小函数(2)---图片的处理

    本文链接:https://www.haomeiwen.com/subject/zuoibftx.html