单张图片转Base64

<script>
    methods: {
		//异步执行
		imageUrlToBase64() {
			//一定要设置为let,不然图片不显示
			let image = new Image();
	
			//解决跨域问题
			image.setAttribute('crossOrigin', 'anonymous');
			
			let imageUrl = "http://bigf.cqugeo.cn/landslip/res/defaultImages/default.png";
			image.src = imageUrl
			
			//image.onload为异步加载
			image.onload = () => {
				var canvas = document.createElement("canvas");
				canvas.width = image.width;
				canvas.height = image.height;
				var context = canvas.getContext('2d');
				context.drawImage(image, 0, 0, image.width, image.height);
				
				var quality = 0.8;
				//这里的dataurl就是base64类型
				var dataURL = canvas.toDataURL("image/jpeg", quality);//使用toDataUrl将图片转换成jpeg的格式,不要把图片压缩成png,因为压缩成png后base64的字符串可能比不转换前的长!
			
			}
		},
	}
</script>

使用toDataUrl将图片转换成jpeg的格式,不要把图片压缩成png,因为压缩成png后base64的字符串可能比不转换前的长!

多张图片转Base64

<script>
  data() {
    return {
   	 base64Datas: [],
    }
	methods: {
		imageUrlToBase64(){
			let data = [
				"http://bigf.cqugeo.cn/landslip/res/defaultImages/default.png",
				"http://bigf.cqugeo.cn/landslip/res/defaultImages/default.png",
				"http://bigf.cqugeo.cn/landslip/res/defaultImages/default.png"
			]
			this.onloadImg(data, 1, data.length);
		},
	
		//采用递归同步执行
		onloadImg(data, i, len) {
	
			//一定要设置为let,不然图片不显示
			let image = new Image();
	
			//解决跨域问题
			image.setAttribute('crossOrigin', 'anonymous');
			
			let imageUrl = "http://bigf.cqugeo.cn/landslip/res/defaultImages/default.png";
			image.src = imageUrl
	
			let that = this;
			//image.onload为异步加载
			image.onload = () => {
				var canvas = document.createElement("canvas");
				canvas.width = image.width;
				canvas.height = image.height;
				var context = canvas.getContext('2d');
				context.drawImage(image, 0, 0, image.width, image.height);
				
				var quality = 0.8;
				//这里的dataurl就是base64类型
				var dataURL = canvas.toDataURL("image/jpeg", quality);//使用toDataUrl将图片转换成jpeg的格式,不要把图片压缩成png,因为压缩成png后base64的字符串可能比不转换前的长!
				
				//数组存放图片base64
				that.base64Datas.push(dataURL);
				
				//递归执行图片url转base64
				i = i + 1;
				if (i <= len) {
					that.onloadImg(data1, i, len)
				}
			
			}
		},
	}
</script>
Logo

前往低代码交流专区

更多推荐