---
# System prepended metadata

title: JavaScrpt 前端筆記
tags: [JavaScript]

---

---
title: JavaScrpt 前端筆記
tags: JavaScript
description:
---
[TOC]

# 上傳圖片

## 上傳圖片壓縮圖片轉換Blob呈現圖片

```
const _this = this;
      var input = event.target;
      if (input.files) {
        var reader = new FileReader();
        reader.readAsDataURL(input.files[0]); //有這行 .oload才有作用
        reader.onload = () => {
          //    = e.target.result; //轉換成dataUrl
          var img = new Image();
          img.src = URL.createObjectURL(input.files[0]); //img.src="blod:...."
          var canvas = document.createElement("canvas");
          var ctx = canvas.getContext("2d");
          img.onload = function () {
            console.log("圖片寬度" + img.width);
            console.log("圖片高度" + img.height);
            if (img.width > img.height) {
              if (img.width > 1024 || img.height > 768) {
                console.log("寬圖-圖片過大");
                canvas.width = img.width * 0.8;
                canvas.height = img.height * 0.8;
              } else {
                canvas.width = img.width;
                canvas.height = img.height;
              }
            } else {
              if (img.width > 768 || img.height > 1024) {
                console.log("長圖-圖片過大");
                canvas.width = img.width * 0.25;
                canvas.height = img.height * 0.25;
              } else {
                canvas.width = img.width;
                canvas.height = img.height;
              }
            }
            ctx.drawImage(img, 0, 0, canvas.width, canvas.height); //(寬,高)
            canvas.toBlob(function (blob) {
              const url = URL.createObjectURL(blob);
              let fileName = new Date().getTime() + ".png";
              let fileData = new File([blob], fileName, {
                type: blob.type,
                lastModified: Date.now(),
              });
              _this.insertImageToEditor("/articleImage/me.jpg"); //放進編輯框
            });

            // const base64Image = canvas.toDataURL();
            // console.log(base64Image);
            // _this.intsertImageToEditer(base64Image);
          };
        };
      }
    },
}


```