如何用JS改变图像的原始大小

JavaScript09

如何用JS改变图像的原始大小,第1张

用JS改变图像的原始大小方法:

var canvas = document.getElementById("canvas")

var context = canvas.getContext("2d")

$('input[type=file]').change(function(){

var file=this.files[0]

var reader=new FileReader()

var image=new Image()

reader.readAsDataURL(file)

reader.onload=function(){

// 通过 reader.result 来访问生成的 DataURL

var url=reader.result

image.src=url

alert(image.width)

alert(image.height)

image.height /=4

image.width /=4

canvas.setAttribute("width", image.width+"px")

canvas.setAttribute("height", image.height+"px")

alert(image.naturalWidth)

alert(image.naturalHeight)

context.drawImage(image,0,0,image.width,image.height)

}

})

原理:

用JS在加载图片后判断图片是否突破规定的高和宽,如果超过再根据图片的宽高比例进行调整。

特别说明,JS代码只限制图片的高或者宽时,宽或者高会按照比例进行相应调整。

假如你需要把所有的图片显示在140*226的区间里面,那么就使用下面这样的代码:

<img src=2009/04/1232336585-19.jpg onload='if (this.width>140 || this.height>226) if (this.width/this.height>140/226) this.width=140else this.height=226'>

这种情况用CSS来控制最合适。例如你想让初始图片显示为100px*100px,则:

<img src="images/pic.png" width="100" height="100" />

或者:

<img src="images/pic.png" style="width:100pxheight:100px" />

当页面中图片非常多,且要求每张图片的大小依据其父容器来固定怎么办?可以使用max-weight:

img {max-weight:100%}

这样图片会自动缩放到和其父容器等宽。