---- AI试用 ---域名问题某些图片和js资源无法访问,导致一些代码实例无法运行!(代码里gzui.net换成momen.vip即可)

使用HTML5+Canvas调用IPHONE摄像头拍照并压缩处理

前端开发 蚂蚁 6450℃ 0评论

【用到的HTML5标签】

<input type="file" capture="camera" accept="image/*" id="cameraInput" name="cameraInput" class="sign_file"/>

就这一个标签就搞定了调用IPHONE摄像头,真是无比的威武!!!
【等比缩放图片】

function drawOnCanvas(file) { 
		var reader = new FileReader();
		reader.onload = function (e) {
		 var dataURL = e.target.result, canvas = document.querySelector('canvas'), 
		 ctx = canvas.getContext('2d'), 
		 img = new Image(); 
		 img.onload = function() {
		  var square = 320; canvas.width = square; canvas.height = square; 
		  var context = canvas.getContext('2d'); context.clearRect(0, 0, square, square);
		  var imageWidth; 
		  var imageHeight; 
		  var offsetX = 0; 
		  var offsetY = 0; 
		  if (this.width > this.height) { 
		  	imageWidth = Math.round(square * this.width / this.height); 
		  	imageHeight = square; offsetX = - Math.round((imageWidth - square) / 2); 
		  } else { imageHeight = Math.round(square * this.height / this.width); 
		  	imageWidth = square;  offsetY = - Math.round((imageHeight - square) / 2); 
		  	 }	 
		  	 context.drawImage(this, offsetX, offsetY, imageWidth, imageHeight); 
		  	 var base64 = canvas.toDataURL('image/jpeg',0.5); $('#j_thumb').val(base64.substr(22)); }; 
		  	 img.src = dataURL; };  
		  	 reader.readAsDataURL(file); 
	}

FileReader对象是用来解析file控件获取的本地图片地址的,具体介绍请百度一下。把解析好的地址设置给IMG标签的SRC属性,然后通过canvas对象把图片绘制; 在这过程中就有个等比缩放的算法,再用drawImage方法把图像画到canvas中。
【如何获取画好的图片数据传到后端处理】
通过 canvas.toDataURL('image/jpeg',0.5)就可以获取到base64编码值,然后你就可以按照传统的POST或者AJAX方式处理了。

【让图片显示】

document.querySelector('input[type=file]').onchange = function () { var file = input.files[0]; drawOnCanvas(file); };

【后台处理方式】

$base64 = $_POST['formFile']; $IMG = base64_decode( $base64 ); file_put_contents('1.png', $IMG );

根传统的上传图片不同,这时候后台需要用base64_decode解码

提示:你可以先修改部分代码再运行。

http://www.0773linji.com/article/index/id/109
http://stackoverflow.com/questions/23916566/html5-input-type-file-accept-image-capture-camera-display-as-image-rat

转载请注明:有爱前端 » 使用HTML5+Canvas调用IPHONE摄像头拍照并压缩处理

喜欢 (0)or分享 (0)

(3)个小伙伴在吐槽
  1. http://cong5.net/post/260
    朽木2015-08-18 10:35
  2. 路过看一下!