php完美缩略图
产品缩略图在网站的设计中再常见不过了,但却时常被忽略。由于用于生成缩略图的大图经常是由访客上传,你不能指望他们按照你预定的比例去上传图片。又或者,虽然比例对了,但是缩小后图片却惨不忍睹。如何生成较好的缩略图?本文尝试给您一些参考建议。
先说明一下,文章是基于PEAR的,为了更快速简单的实现效果,我选用了pear类库的Image_Transform。如果您还不知道如何使用php保存文件,那请先了解下php的基础知识。如果您不了解PEAR,请看这里。
对于第一种情况,图片非等比例压缩导致图片变形的问题。可以采取最大化裁切方案。什么时最大化裁切方案?就是按照一定的比例最大化的裁切图片,然后按照此比例生成缩略图。这样就能保证图片不会因为压缩而变形。
但是,有些时候,光是按比例缩小还不够。这时候,就需要按比例自由裁切。就是按一定的比例设定裁切框比例,但是裁切框的大小和位置可以自由设定。类似于photoshop的裁切工具。
有了这两个方案,相信可以解决大部分缩略图处理的问题。
实现代码:
PHP:
-
<?php
-
require_once 'Image/Transform.php';
-
-
-
/*
-
自动按一定比例最大化裁切图片
-
autoResizeImage('old.jpg',100,200,'new.jpg');
-
*/
-
-
function autoResizeImage($fileName,$width,$height,$saveName=''){
-
$imagesSourse=& Image_Transform::factory('GD');
-
$imagesSourse->load($fileName);
-
$proportion=$width/$height;
-
$img_width=$imagesSourse->getImageWidth();
-
$img_height=$imagesSourse->getImageHeight();
-
if($img_width>$proportion*$img_height){
-
$img_width=$img_height*$proportion;
-
}else{
-
$img_height=$img_width/$proportion;
-
}
-
$imagesSourse->crop($img_width,$img_height);
-
_updateForResize($imagesSourse);
-
$imagesSourse->resize($width,$height);
-
if(!$saveName){
-
}
-
$imagesSourse->save($saveName);
-
-
}
-
/*
-
按一定比例自由裁切图片
-
freeResizeImage('old.jpg',100,300,400,'new.jpg');
-
*/
-
function freeResizeImage($fileName,$newWidth,$width,$height,$xPos=0,$yPos=0,$saveName=''){
-
$imagesSourse=& Image_Transform::factory('GD');
-
$imagesSourse->load($fileName);
-
$imagesSourse->crop($width,$height,$xPos,$yPos);
-
_updateForResize($imagesSourse);
-
$imagesSourse->resize($newWidth,$newWidth*$height/$width);
-
if(!$saveName){
-
}
-
$imagesSourse->save($saveName);
-
-
}
-
function _updateForResize(& $imageSourse){
-
$imageSourse->img_x=$imageSourse->new_x;
-
$imageSourse->img_y=$imageSourse->new_y;
-
$imageSourse->resized=false;
-
}
-
?>
测试ajax是否死锁