jotting

Check size and compress the picture

延續:Upload image into HTML5 canvas


Check File Size

JavaScript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function imgCheck(input) {
var file = input.files[0];
var fileSize = file.size / 1024 / 1024,
errors = [];

if (fileSize > 8) {
errors.push("照片最大僅支持8MB");
alert(errors[0]);
}

if (errors.length > 0) {
$('#upload').val('')
return false
} else
return true
}

Note

  1. input.files[0]
    File API 可以從 File 物件中讀取 FileList ,FileList 內包含使用者所選取的檔案
    如果使用者只選擇一個檔案,那麼我們只選取第一個物件
  2. file.size的單位為byte
  3. 回傳bool,用在change時判斷

Compress

JavaScript

1
2
3
4
5
6
7
8
9
10
11
12
function compress(img) {
var c = document.createElement("canvas");
var ctx = c.getContext('2d');

c.width = img.width/2;
c.height = img.height/2;

ctx.drawImage(img, 0, 0, img.width, img.height);
var data = canvas.toDataURL('image/jpeg',0.5);

return data;
}

Note

  1. HTMLCanvasElement.toDataURL()
    表達式:canvas.toDataURL(type, encoderOptions);
    type:圖像格式,預設為image/png
    encoderOptions:jpeg或是webp的品質,0~1之間,超過或無則為預設值1
  2. 回傳值是data URI的DOMString,若上傳到C#會再砍掉前面的data:image/jpeg;base64, …(base64)