js压缩图片的方法(手机端,兼容ios和android),返回值为base64的字符串,压缩率ratio可自定义
方法的定义:
getCompressBase64(img, ratio){//img为通过"document.getElementByTagName('input[type=file]')[0]"拿到的图片blog对象, 压缩率ratio范围为0-1
if(Object.prototype.toString.call(img) === '[object HTMLInputElement]'){
let phone = navigator.userAgent.indexOf('iPhone')//获取是否是iphone
let reader = new FileReader()
reader.readAsDataURL(img.files[0])
let tempPromise = new Promise((resolve,reject)=>{
reader.onload = function(e){
image = new Image()
image.src = e.target.result
image.onload = function () {
var that = this
// 默认按比例压缩
w = that.width
h = that.height
scale = w / h
canvas = document.createElement('canvas')
if(phone > -1){
canvas.width = h
canvas.height = w
ctx = canvas.getContext('2d')
ctx.save();
ctx.translate(h/2,w/2);
ctx.rotate(90*Math.PI/180)
ctx.drawImage(image, 0 - w/2, 0 - h/2, w, h)
ctx.restore()
}else{
canvas.width = w
canvas.height = h
ctx = canvas.getContext('2d')
ctx.drawImage(image, 0, 0, w, h)
}
img64 = canvas.toDataURL('image/jpeg', ratio)
resolve(img64)
}
}
})
return tempPromise//返回一个promise
}
方法的使用:
let img = document.getElementByTagName('input[type=file]')[0]//拿到页面中的某个图片
let file = img.files[0]
// 首先读取此图片,读取完毕之后进行压缩
let reader = new FileReader()
reader.readAsDataURL(file)
reader.onload = function () {//
getCompressBase64(img, 0.01).then(data => {
console.log(data)//data就是压缩后的base64格式的字符串
})
}