Skip to content

Instantly share code, notes, and snippets.

@qzchenwl
Last active August 29, 2015 14:27
Show Gist options
  • Save qzchenwl/a327fc2377b8bba7e46a to your computer and use it in GitHub Desktop.
Save qzchenwl/a327fc2377b8bba7e46a to your computer and use it in GitHub Desktop.
压缩图像示例
<input type="file" id="fileinput"/>
var fileinput = document.querySelector('#fileinput');
console.log(fileinput);
fileinput.onchange = function() {
var file = this.files[0];
resizeImage(file, function(blob){
displayBlob(blob);
saveBlob(blob, "压缩图片.png");
});
}
function resizeImage(file, onSuccess) {
if (!( /image/i ).test( file.type )) {
fileinput.value = "";
return;
}
console.log(file.type);
var reader = new FileReader();
reader.readAsArrayBuffer(file);
reader.onload = function(event) {
// NOTE: Get file size in bytes
console.log(event.target.result.byteLength);
var blob = new Blob([event.target.result]);
var url = URL.createObjectURL(blob);
var image = new Image();
image.src = url;
image.onload = function() {
var originWidth = this.width;
var originHeight = this.height;
var targetWidth = originWidth / 2;
var targetHeight = originWidth / 2;
var canvas = document.createElement('canvas');
canvas.width = targetWidth;
canvas.height = targetHeight;
var ctx = canvas.getContext("2d");
ctx.drawImage(image, 0, 0, canvas.width, canvas.height);
var resultBase64URL = canvas.toDataURL(file.type);
console.log(resultBase64URL);
var blob = dataURLtoBlob(resultBase64URL);
URL.revokeObjectURL(url);
onSuccess && onSuccess(blob);
}
}
}
// ==================== Some Utilities ====================
function dataURLtoBlob(dataURI) {
// convert base64 to raw binary data held in a string
// doesn't handle URLEncoded DataURIs - see SO answer #6850276 for code that does this
var byteString = atob(dataURI.split(',')[1]);
// separate out the mime component
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]
// write the bytes of the string to an ArrayBuffer
var ab = new ArrayBuffer(byteString.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
return new Blob([ab], {type: mimeString});
}
function displayBlob(blob) {
console.log(blob);
var url = URL.createObjectURL(blob);
var image = new Image();
image.src = url;
document.body.appendChild(image);
}
function saveBlob(blob, filename) {
var url = window.URL.createObjectURL(blob);
var a = document.createElement("a");
a.href = url;
a.download = filename;
a.click();
URL.revokeObjectURL(url);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment