JavaScript图片压缩

在前端开发中,许多地方需要用到图片上传,此脚本是对图片进行压缩,支持压缩方式:根据宽、高、系统自动判断与强制拉伸四种方式

主包,复制下来新建即可用,也可以使用网络地址进行测试

trace.img.js

(function(root, factory) {
	if(typeof define === 'function' && define.amd) {
		define(['jquery']);
	} else if(typeof exports === 'object') {
		module.exports = factory(require('jquery'));
	} else {
		root.TraceImg = factory(root.jQuery);
	}
}(this, function($) {
	let util = {
		windowHeight: $(window).height(),
		windowWidth: $(window).width(),
		bodyHeight: $(document.body).outerHeight(true),
		bodyWidth: $(document.body).outerWidth(true)
	},
	imageCompress = (() => {
		let cpsPer = {width: "width", height: "height", force: "force", auto: "auto"},
		files = {},
		imgCps = (e, fn) => {
			let imgDom = $(e.dom),
			type = e.type,
			body = $('body'),
			time = new Date().getTime(),
			cw = e.width,
			ch = e.height,
			canvasId = (() => {
				body.append(`<canvas style='display:none;' id="original_canvas_${time}"></canvas>`)
				return `original_canvas_${time}`
			})(),
			jsDom = document.getElementById(canvasId),
			context = jsDom.getContext("2d"),
			base64Data = (w, h, img) => {
				let widthPro = 0,
				heightPro = 0,
				fw = ()=> {
					widthPro = cw
					heightPro = h/(w/cw)
				},
				fh = ()=> {
					widthPro = w/(h/ch)
					heightPro = ch
				}
				switch (e.per){
					case cpsPer.width:
						console.log("w")
						fw()
						break;
					case cpsPer.height:
						console.log("h")
						fh()
						break;
					case cpsPer.force://宽高必传
						widthPro = cw
						heightPro = ch
						break;
					case cpsPer.auto:
					default:
						console.log("d")
						if(w>h) {
							fw()
						}else {
							fh()
						}
						break;
				}
				jsDom.width = widthPro
				jsDom.height = heightPro
				context.scale(widthPro/w, heightPro/h)
				context.drawImage(img, 0, 0)
				return jsDom.toDataURL()
			},
			handleimg = (e) => {
				files.base64 = base64Data(e.width, e.height, e.jsDom)
				let binary = atob(files.base64.split(',')[1]),arr = []
				for(let i = 0; i < binary.length; i++) {
					arr.push(binary.charCodeAt(i))
				}
				files.file = new Blob([new Uint8Array(arr)], {type: type})
				return files
			}
			((e) => {
				let reader = new FileReader(),
				img = new Image(),
				file = e[0].files[0]
				files.name = file.name
				reader.onload = function(e) {
					img.onload = function() {
						fn(handleimg({
							jsDom: img,
							width: img.width,
							height: img.height
						}))
					}
					img.src = e.target.result
				}
				reader.readAsDataURL(file)
			})(imgDom)
		},
		inBlob = (e, fn) => {
			let type = e.type,
			body = $('body'),
			time = new Date().getTime(),
			cw = e.width,
			ch = e.height,
			canvasId = (() => {
				body.append(`<canvas style='display:none;' id="original_canvas_${time}"></canvas>`)
				return `original_canvas_${time}`
			})(),
			jsDom = document.getElementById(canvasId),
			context = jsDom.getContext("2d"),
			base64Data = (w, h, img) => {
				let widthPro = 0,
				heightPro = 0,
				fw = ()=> {
					widthPro = cw
					heightPro = h/(w/cw)
				},
				fh = ()=> {
					widthPro = w/(h/ch)
					heightPro = ch
				}
				switch (e.per){
					case cpsPer.width:
						console.log("w")
						fw()
						break;
					case cpsPer.height:
						console.log("h")
						fh()
						break;
					case cpsPer.force://宽高必传
						widthPro = cw
						heightPro = ch
						break;
					case cpsPer.auto:
					default:
						console.log("d")
						if(w>h) {
							fw()
						}else {
							fh()
						}
						break;
				}
				jsDom.width = widthPro
				jsDom.height = heightPro
				context.scale(widthPro/w, heightPro/h)
				context.drawImage(img, 0, 0)
				return jsDom.toDataURL()
			},
			handleimg = (e) => {
				files.base64 = base64Data(e.width, e.height, e.jsDom)
				let binary = atob(files.base64.split(',')[1]),arr = []
				for(let i = 0; i < binary.length; i++) {
					arr.push(binary.charCodeAt(i))
				}
				files.file = new Blob([new Uint8Array(arr)], {type: type})
				return files
			}
			((e) => {
				let reader = new FileReader(),
				img = new Image(),
				file = e
				files.name = file.name
				reader.onload = function(e) {
					img.onload = function() {
						fn(handleimg({
							jsDom: img,
							width: img.width,
							height: img.height
						}))
					}
					img.src = e.target.result
				}
				reader.readAsDataURL(file)
			})(e.blob)
		},
		check = (e) => {
			let dp = {
				type: "jpg",
				per: "auto"
			}
			$.extend(dp, e)
			dp.type = dp.type == "png" ? dp.type : "jpg"
			switch (dp.per){
				case cpsPer.width:
					if(dp.width == undefined || dp.width != Number(dp.width))
						throw new Error("params error: The parameter per is wide and the width cannot be empty.")
					break;
				default:
					break;
			}
		}
		return {
			inDom: imgCps,
			inBlob: inBlob
		}
	})()
	return {
		imageCompress: imageCompress
	}
}));

使用说明:README.md

图片压缩--imageCompress
	TraceImg.imageCompress中提供两种方法
		参数说明: 
				dom----inputfile标签的selector/blob----inputfile标签的文件流
				width----压缩后的宽度
				height----压缩后的高度
				type----返回的图片类型(支持jpg与png)
				per----压缩方式(支持四种参数width:按宽度压缩,height:按高度压缩,auto:如图宽度大于高则按宽度压缩,反之,force:强制拉伸图片至设定的宽高)
		1).inDom({
			dom: "#imgfile",
			width: 100,
			height: 100,
			type: "jpg",
			per: "force"
		},function(e) {
			
		})
		2).inBlob({
			blob: document.getElementById("imgfile").files[0],
			width: 100,
			height: 100,
			type: "jpg",
			per: "force"
		}, function(e) {
			
		})
	let imgCompress = TraceImg.imageCompress
	imgCompress.inBlob/inDom({})

测试网页:test.html

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<script src="https://hutrace.info/files/js/jquery.min.js"></script>
    	<script src="https://hutrace.info/files/js/trace.img.js"></script>
		<title></title>
	</head>
	<body>
		<div>
			<input type="file" id="imgfile"/>
			<button οnclick="yasuo()">压缩</button>
		</div>
	</body>
	<script type="text/javascript">
		function yasuo() {
			/*TraceImg.imageCompress.inDom({
				dom: "#imgfile",
				width: 100,
				height: 100,
				type: "jpg",
				per: "force"
			}, function(e) {
				$('body').append("<img src='" + e.base64 + "'/>")
				console.log(e)
			})*/
			TraceImg.imageCompress.inBlob({
				blob: document.getElementById("imgfile").files[0],
				width: 100,
				height: 100,
				type: "jpg",
				per: "force"
			}, function(e) {
				$('body').append("<img src='" + e.base64 + "'/>")
				console.log(e)
			})
		}
	</script>
</html>


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值