前端常用的小函數(shù)(2)---圖片的處理

  • 需求背景

需要從服務器讀取圖片到頁面(圖片大小未知),或者上傳圖片到服務器(圖片體積過大,需要壓縮) ,此外后端可能能對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;
  // 創(chuàng)建Image 對象
  const image = new Image();
  image.src = base64file;
  // 創(chuàng)建畫布
  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

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 178,777評論 25 709
  • 有個女孩說:文藝青年的話沒有一句是靠譜,其實文藝青年想說的是:女孩的這句話,完全不靠譜。 第一次見到大媽的時候,她...
    王書著閱讀 522評論 0 0
  • 終于和走南闖北的人聊會兒天,我問她:“最近怎么又感冒?” 丫頭有些吃驚,問我怎么知道她感冒的?我自知說走了嘴,忙打...
    a宮雨閱讀 355評論 0 1
  • 永遠最愛你的那個男人(一) 我出門在外多年以后,回了老家。 每天,我下班回家后的第一...
    fun眼望世界閱讀 2,509評論 23 134
  • 在滬工作有6余年,一般參加商會活動跟培訓學習比較多。第一次參加關于文化類祭祀活動,感受不一樣。 中國文化博...
    范琳琳123閱讀 1,974評論 2 2

友情鏈接更多精彩內容