php和js对数据库图片进行等比缩放示例
JS 对某图片的等比缩放
Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/--><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>最新javascript自动按比例显示图片,按比例压缩图片显示</title>
<script type="text/javascript">
function AutoResizeImage(maxWidth,maxHeight,objImg){
var img = new Image();
img.src = objImg.src;
var hRatio;
var wRatio;
var Ratio = 1;
var w = img.width;
var h = img.height;
wRatio = maxWidth / w;
hRatio = maxHeight / h;
if (maxWidth ==0 && maxHeight==0){
Ratio = 1;
}else if (maxWidth==0){//
if (hRatio<1) Ratio = hRatio;
}else if (maxHeight==0){
if (wRatio<1) Ratio = wRatio;
}else if (wRatio<1 || hRatio<1){
Ratio = (wRatio<=hRatio?wRatio:hRatio);
}
if (Ratio<1){
w = w * Ratio;
h = h * Ratio;
}
objImg.height = h;
objImg.width = w;
}
</script>
</head>
<body>
<br />
原图显示(534 X 800)<br />
onload="AutoResizeImage(0,0,this)<br />
<a href="./img/IMG_20140424_200722.jpg" target="_blank"><img src="./img/IMG_20140424_200722.jpg" border="0" width="0" height="0" onload="AutoResizeImage(0,0,this)" alt="534 X 800"/></a><br/><br />
3.按高度250宽度250 按比例压缩<br />
onload="AutoResizeImage(250,250,this)"<br />
<a href="./img/IMG_20140424_200722.jpg" target="_blank"><img src="./img/IMG_20140424_200722.jpg" border="0" width="0" height="0" onload="AutoResizeImage(250,250,this)" alt="200 X 300"/></a><br /><br />
6.如果图片本来的高度和宽度小于压缩的最大高度和宽度,则不会拉大显示图片(按原图显示)<br />
原图444 x 207,压缩为 500 x 600,将保持原图显示<br />
onload="AutoResizeImage(500,600,this)"<br />
<a href="./img/IMG_20140424_200722.jpg" target="_blank"><img src="./img/IMG_20140424_200722.jpg" border="0" width="0" height="0" onload="AutoResizeImage(500,600,this)" alt="444 X 207"/></a><br /><br />
</body>
</html>
<?php
class ImgSF{
function make_img($img_address){
//图片的等比缩放
//因为PHP只能对资源进行操作,所以要对需要进行缩放的图片进行拷贝,创建为新的资源
$src=imagecreatefromjpeg($img_address);
//取得源图片的宽度和高度
$size_src=getimagesize($img_address);
$w=$size_src['0'];
$h=$size_src['1'];
//指定缩放出来的最大的宽度(也有可能是高度)
$max=300;
//根据最大值为300,算出另一个边的长度,得到缩放后的图片宽度和高度
if($w > $h){
$w=$max;
$h=$h*($max/$size_src['0']);
}else{
$h=$max;
$w=$w*($max/$size_src['1']);
}
//声明一个$w宽,$h高的真彩图片资源
$image=imagecreatetruecolor($w, $h);
//关键函数,参数(目标资源,源,目标资源的开始坐标x,y, 源资源的开始坐标x,y,目标资源的宽高w,h,源资源的宽高w,h)
imagecopyresampled($image, $src, 0, 0, 0, 0, $w, $h, $size_src['0'], $size_src['1']);
//告诉浏览器以图片形式解析
header('content-type:image/png');
imagepng($image);
//销毁资源
imagedestroy($image);
}
}
$obj=new ImgSF();
$obj->make_img("./img/IMG_20140424_200722.jpg");