html如何选择本地图片,Html5本地图片读取及裁剪
需要使用到Html5的FileReader,其中image-file是一個input type=file的文件瀏覽框。如果需要限制讀取圖片或者照相機:
當(dāng)用戶選擇了圖片之后,給input file綁定change事件,自動讀取本地文件。
var image_file = document.getElementById("image-file");
if(typeof FileReader==='undefined'){
image.innerHTML = "抱歉,你的瀏覽器不支持 FileReader";
image_file.setAttribute('disabled','disabled');
}else{
image_file.addEventListener('change',readFile,false);
}
image就是一個id為image的img標(biāo)簽。readFile函數(shù)將圖片讀入,并自動居中裁剪為 寬度自適應(yīng)屏幕,高度固定為180px的圖片。裁剪的過程中需要使用Canvas。
function readFile(){
var file = this.files[0];
if(!/image\/\w+/.test(file.type)){
alert("文件必須為圖片!");
return false;
}
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function(e){
var image = document.getElementById("image");
var image=new Image();
image.src = this.result;
var x = 0, y = 0, width = image.width, height = image.height;
if (image.width / $(window).width() > image.height / 180) {
width = $(window).width() * image.height / 180;
x = (image.width - width) / 2;
}
else {
height = 180 * image.width / $(window).width();
y = (image.height - height) / 2;
}
var canvas=$('')[0],
ctx=canvas.getContext('2d');
ctx.drawImage(image,x,y,width,height,0,0,width,height);
var data=canvas.toDataURL();
image.innerHTML = ''
}
}
總結(jié)
以上是生活随笔為你收集整理的html如何选择本地图片,Html5本地图片读取及裁剪的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 吉林大学计算机学院微信公众号,吉林大学开
- 下一篇: 测试用例设计(等价类、边界值、因果图、判