600字范文,内容丰富有趣,生活中的好帮手!
600字范文 > js 图片压缩上传(base64位)以及上传类型分类

js 图片压缩上传(base64位)以及上传类型分类

时间:2022-10-07 16:26:11

相关推荐

js 图片压缩上传(base64位)以及上传类型分类

一、input file上传类型

1.指明只需要图片

<input type="file" accept='image/*'>

2.指明需要多张图片

<input type="file" multiple accept='image/*'>

3.指明调用摄像头获取图片

<input type="file" capture='camera' accept='image/*'>

4.调用摄像头并获取多张图片(摄像头只能单张获取,multiple无效)

<!-- multiple 无效 --><input type="file" multiple capture='camera' accept='image/*'>

二、图片压缩上传

(1)移动端IOS上传的某些图片预览时发生了旋转?

你会发现手机截图,网络图片都不会有旋转问题,只有手机拍摄的才有,这就跟拍摄时的角度有问题了,所以我们通过exif.js获取角度(Orientation)的值,所获值分别需要旋转的角度如下:

<!DOCTYPE html><html><head><meta charset="UTF-8"><title></title><meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" /><script src="js/jquery-1.11.3.min.js"></script><script src="js/exif.js"></script><style>#preview{width:100px;height:110px;}</style></head><body><input type="file" id="files" ><img src="blank.gif" id="preview"><script>var ipt = document.getElementById('files'),img = document.getElementById('preview'),Orientation = null;ipt.onchange = function () {var file = ipt.files[0],reader = new FileReader(),image = new Image();if(file){EXIF.getData(file, function() { Orientation = EXIF.getTag(this, 'Orientation');console.log(Orientation);});reader.onload = function (ev) {image.src = ev.target.result;image.onload = function () {var imgWidth = this.width,imgHeight = this.height;// 控制上传图片的宽高if(imgWidth > imgHeight && imgWidth > 600){imgWidth = 600;imgHeight = Math.ceil(600 * this.height / this.width);}else if(imgWidth < imgHeight && imgHeight > 600){imgWidth = Math.ceil(600 * this.width / this.height);imgHeight = 600;}var canvas = document.createElement("canvas"),ctx = canvas.getContext('2d');canvas.width = imgWidth;canvas.height = imgHeight;if(Orientation && Orientation != 1){switch(Orientation){case 6:// 旋转90度 canvas.width = imgHeight; canvas.height = imgWidth; ctx.rotate(Math.PI / 2); ctx.drawImage(this, 0, -imgHeight, imgWidth, imgHeight);break;case 3:// 旋转180度 ctx.rotate(Math.PI); ctx.drawImage(this, -imgWidth, -imgHeight, imgWidth, imgHeight);break;case 8:// 旋转-90度 canvas.width = imgHeight; canvas.height = imgWidth; ctx.rotate(3 * Math.PI / 2); ctx.drawImage(this, -imgWidth, 0, imgWidth, imgHeight);break;}}else{ctx.drawImage(this, 0, 0, imgWidth, imgHeight);}var newImageData = canvas.toDataURL("image/jpeg", 0.6);$("img").attr("src", newImageData.replace("data:base64", "data:image/jpeg;base64"));}}reader.readAsDataURL(file);}}</script></body></html>

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。