我正在为一个数字资产管理器创建缩略图,使用imagemagick做这件事的最好方法是什么?
有没有好的资源?
发布于 2012-09-21 02:43:14
我解决了这个问题,并将与世界分享!它可以将.ai,.psd,.jpg,.png,.gif转换成缩略图。
下面是一个接受4个参数的函数:
$dir -要保存到的目录。
$tmpName -用于命名文件的名称,不包括扩展名。
$fileType -不言自明。
$size -大或小。
function thumbGenerator($dir,$tmpName,$fileType,$size){
$saveFileType = "png";
$imagePath = $dir.$tmpName.".".$fileType;
$image = new Imagick();
$image->readimage($imagePath);
if($fileType == "psd"){
$image->setIteratorIndex(0);
}
$dimensions = $image->getImageGeometry();
$width = $dimensions['width'];
$height = $dimensions['height'];
if($size == "large"){
$maxWidth = 720;
$maxHeight =720;
}
if($size == "small"){
$maxWidth = 250;
$maxHeight =250;
}
if($height > $width){
//Portrait
if($height > $maxHeight)
$image->thumbnailImage(0, $maxHeight);
$dimensions = $image->getImageGeometry();
if($dimensions['width'] > $maxWidth){
$image->thumbnailImage($maxWidth, 0);
}
}elseif($height < $width){
//Landscape
$image->thumbnailImage($maxWidth, 0);
}else{
//square
$image->thumbnailImage($maxWidth, 0);
}
if($size == "large"){
$image->writeImage($dir . $tmpName."-lg.".$saveFileType);
}
if($size == "small"){
$image->writeImage($dir . $tmpName."-sm.".$saveFileType);;
}
}发布于 2013-06-24 23:47:28
@Jason -感谢分享。这里有一些更简洁、更容易维护/扩展代码的技巧。同样,这在很大程度上取决于您的需求。另外,我实际上并没有运行这段代码,所以请原谅我的拼写错误。
$dir -要保存到的目录。
$tmpName -用于命名文件的名称,不包括扩展名。
$fileType -不言自明。
$size -大或小。您可以考虑将像素宽度值作为缩略图,而不是将字符串作为预定义宽度。假设你将来在页面的新部分需要一个更大的缩略图(即500px的Retina-ready图标用于“小”缩略图)。最好在代码的新部分中定义大小,而不是在共享thumbGenerator函数中定义
function thumbGenerator($dir,$tmpName,$fileType,$size){
$saveFileType = "png";
$imagePath = $dir.$tmpName.".".$fileType;
$image = new Imagick();
$image->readimage($imagePath);
if($fileType == "psd"){
$image->setIteratorIndex(0);
}
/* Simplify this code section below
$dimensions = $image->getImageGeometry();
$width = $dimensions['width'];
$height = $dimensions['height'];
*/
list($width,$height) = $image->getImageGeometry(); // <--- new code
/* Use $size for the pixel width/height instead and remove the code below
if($size == "large"){
$maxWidth = 720;
$maxHeight =720;
}
if($size == "small"){
$maxWidth = 250;
$maxHeight =250;
}
*/
if($height > $width){
//Portrait
if($height > $size)
$image->thumbnailImage(0, $size);
$dimensions = $image->getImageGeometry();
if($width > $size){ // <--- use the previously created $width variable
$image->thumbnailImage($size, 0);
}
/* Don't need this duplicate code.
}elseif($height < $width){
//Landscape
$image->thumbnailImage($maxWidth, 0);
*/
}else{
// square or landscape
$image->thumbnailImage($maxWidth, 0);
}
/* DRY - do not repeat yourself - Simplify it and use the pixel width in the image name
if($size == "large"){
$image->writeImage($dir . $tmpName."-lg.".$saveFileType);
}
if($size == "small"){
$image->writeImage($dir . $tmpName."-sm.".$saveFileType);;
}
*/
$image->writeImage($dir . $tmpName."-".$size.".".$saveFileType);;
}https://stackoverflow.com/questions/12516842
复制相似问题