JS获取本地图片和网络图片的宽高尺寸和存储大小

最新更新时间:2020年07月08日09:13:28

《猛戳-查看我的博客地图-总有你意想不到的惊喜》

本文内容:图片作为一种记录信息的载体,比文本更加生动,比视频更加精简,在日常生活中的用处很大。作为前端开发人员,操作图片的场景非常多,本文记录读取本地图片的宽高尺寸和存储大小,以及获取网络图片的宽高尺寸和存储大小。

读取本地图片

  • html
{this.onChange(e)}}
	className={styles.getImg}
	title={this.state.title}
	id="fileinput"
	ref='onChange'
	accept="image/*"
	// capture="camera"
/>
  • JS
//input 标签的原生 change 事件
onChange(e){
	let file = e.currentTarget.files[0];//File
	//用户取消操作
	if(file == undefined){
		return
	}
	console.log(file.constructor);//ƒ File() { [native code] }
	console.log(file.name);
	console.log(file.size/1024);// kb 图片容量
	File2Base64(file);
}
function File2Base64(file){
	let fr = new FileReader();
	//如果下面的语句执行失败,需要放入 setTimeout 异步处理
	fr.readAsDataURL(file);
	fr.onload=function(e) {
		console.log(this.result);// base64
		console.log(e.target.result);// base64
		let base64 = e.target.result;// data:image/jpeg;base64,/9j/4AAQSkZJ
		console.log(base64.constructor);//ƒ String() { [native code] }
		getWH(base64);
	}
}
function getWH(base64){
	var img = new Image();
    img.src = base64;
    img.onload = function() {
    	//图片尺寸
		console.log(img.width,img.height);
	}
}

读取网络图片

  • 注意:如果不设置img.setAttribute('crossorigin', 'anonymous')允许跨域加载,调用canvas.toDataURL('image/jpeg', 1) 会报错Uncaught DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.
  • DOM
<canvas id="canvas">canvas>
  • JS
let url = 'https://www.wanshaobo.com/static/1.png';
const canvas = document.getElementById('canvas');
let ctx = null;
var img = new Image();
img.src = url;
img.setAttribute('crossorigin', 'anonymous'); // 设置图片跨域应该在图片加载之前
img.onload = function(e) {
	//e.target = e.path[0] 
	//图片原始宽高
	console.log(img.constructor)//ƒ HTMLImageElement() { [native code] }
	let w = img.width;
	let h = img.height;
	//将图片的绝对宽高绘制在canvas上
	canvas.width = w;
	canvas.height = h;
	ctx = canvas.getContext('2d');
	ctx.drawImage(img,0,0);
	canvas.toBlob(function(res){
		console.log(res.size);//图片真实存储大小
		console.log(res.type);
	},'image/jpeg',1)
	let base64 = canvas.toDataURL('image/jpeg', 1);//data:image/jpeg;base64,/9j/4AAQSkZJ
	console.log(base64.length);//不代表图片的存储大小
	Base642Blob(base64);
}
function Base642Blob(base64){
	var arr = base64.split(',');//['data:image/jpeg;base64',',/9j/4AAQSkZJ']
	var mime = arr[0].match(/:(.*?);/)[1];//image/jpeg
	var decodeBase64 = atob(arr[1]);//解码使用 base-64 编码的字符串 atob(',/9j/4AAQSkZJ')
	var len = decodeBase64.length;
	var u8arr = new Uint8Array(len);
	while (len--) {
		u8arr[len] = decodeBase64.charCodeAt(len);
	}
	let blob = new Blob([u8arr], {type: mime});
	console.log(blob.constructor)//ƒ Blob() { [native code] }
	console.log(blob.type);//image/jpeg
	//图片真实存储大小
	console.log(blob.size/1024);//kb
	Blob2Base64(blob);
}
function Blob2Base64(blob){
	var fr = new FileReader();
	fr.readAsDataURL(blob);
	fr.onload = function (e) {
		//e ProgressEvent loaded: 65861 total: 65861 type: "load"
		//this = e.target FileReader {}
		console.log(e.target.constructor);//ƒ FileReader() { [native code] }
		let base64 = e.target.result;
		console.log(this.result);// base64
		console.log(e.target.result);// base64
		let base64 = e.target.result;// data:image/jpeg;base64,/9j/4AAQSkZJ
		console.log(base64.constructor);//ƒ String() { [native code] }
		console.log(base64.length);//不代表图片的存储大小
	};
}

参考资料

  • FileReader - Web API 接口参考 | MDN
  • Blob - Web API 接口参考 | MDN
  • File - Web API 接口参考 | MDN
  • ArrayBuffer - JavaScript | MDN
  • Uint8Array - JavaScript | MDN
  • HTMLCanvasElement - toDataURL() - toBlob()

感谢阅读,欢迎评论^-^

打赏我吧^-^

你可能感兴趣的:(文件操作)