1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
| input.addEventListener("change", function(){ var file = this.files[0];
// 接受 jpeg, jpg, png 类型的图片 // if (!/\/(?:jpeg|jpg|png)/i.test(file.type)) return;
var reader = new FileReader(); var compressCanvas = document.querySelector(".babyhappy_compressimg_con"); compressCtx = compressCanvas.getContext("2d");
reader.onload = function(event) { var result = this.result; var image = new Image(); image.src = reader.result;
image.onload = function(){ EXIF.getData(image, function(){ EXIF.getAllTags(this); var orientation = EXIF.getTag(this, 'Orientation'); switch(orientation){ case 1: //0° compressCanvas.height = image.height; compressCanvas.width = image.width; compressCtx.clearRect(0, 0, compressCanvas.width, compressCanvas.height) compressCtx.drawImage(image, 0, 0, image.width, image.height); break; case 6: //顺时针90° compressCanvas.width = image.height; compressCanvas.height = image.width; compressCtx.clearRect(0, 0, compressCanvas.width, compressCanvas.height) compressCtx.translate(0, 0); compressCtx.rotate(90 * Math.PI / 180); compressCtx.drawImage(image, 0, -image.height, image.width, image.height); break; case 8: //逆时针90° compressCanvas.width = image.height; compressCanvas.height = image.width; compressCtx.clearRect(0, 0, compressCanvas.width, compressCanvas.height) compressCtx.translate(0, 0); compressCtx.rotate(-90 * Math.PI / 180); compressCtx.drawImage(image, -image.width, 0, image.width, image.height); break; case 3: //180° compressCanvas.height = image.height; compressCanvas.width = image.width; compressCtx.clearRect(0, 0, compressCanvas.width, compressCanvas.height) compressCtx.translate(0, 0); compressCtx.rotate(Math.PI); compressCtx.drawImage(image, -image.width, -image.height, image.width, image.height); break; default: compressCanvas.height = image.height; compressCanvas.width = image.width; compressCtx.clearRect(0, 0, compressCanvas.width, compressCanvas.height) compressCtx.drawImage(image, 0, 0, image.width, image.height); } var base64 = compressCanvas.toDataURL("image/jpeg", .5);
}) } reader.readAsDataURL(file); }, false)
|