我有免费的PHP代码功能(Pedro Pinheiro https://github.com/pedroppinheiro)
function createThumbnail($filepath, $thumbpath, $thumbnail_width, $thumbnail_height, $background=false) {
list($original_width, $original_height, $original_type) = getimagesize($filepath);
if ($original_width > $original_height) {
$new_width = $thumbnail_width;
$new_height = intval($original_height * $new_width / $original_width);
} else {
$new_height = $thumbnail_height;
$new_width = intval($original_width * $new_height / $original_height);
}
$dest_x = intval(($thumbnail_width - $new_width) / 2);
$dest_y = intval(($thumbnail_height - $new_height) / 2);
if ($original_type === 1) {
$imgt = "ImageGIF";
$imgcreatefrom = "ImageCreateFromGIF";
} else if ($original_type === 2) {
$imgt = "ImageJPEG";
$imgcreatefrom = "ImageCreateFromJPEG";
} else if ($original_type === 3) {
$imgt = "ImagePNG";
$imgcreatefrom = "ImageCreateFromPNG";
} else {
return false;
}
$old_image = $imgcreatefrom($filepath);
$new_image = imagecreatetruecolor($thumbnail_width, $thumbnail_height); // creates new image, but with a black background
// figuring out the color for the background
if(is_array($background) && count($background) === 3) {
list($red, $green, $blue) = $background;
$color = imagecolorallocate($new_image, $red, $green, $blue);
imagefill($new_image, 0, 0, $color);
// apply transparent background only if is a png image
} else if($background === 'transparent' && $original_type === 3) {
imagesavealpha($new_image, TRUE);
$color = imagecolorallocatealpha($new_image, 0, 0, 0, 127);
imagefill($new_image, 0, 0, $color);
}
imagecopyresampled($new_image, $old_image, $dest_x, $dest_y, 0, 0, $new_width, $new_height, $original_width, $original_height);
$imgt($new_image, $thumbpath);
return file_exists($thumbpath);
}`
当您调用此函数时,它会从单个图像文件创建缩略图
$success = createThumbnail(__DIR__.DIRECTORY_SEPARATOR.'image.jpg', __DIR__.DIRECTORY_SEPARATOR.'image_thumb.jpg', 60, 60, array(255,255,255));
单个图像文件可以,但我希望它能转换文件夹中的所有图像,我该怎么办?当我使用它时,它不起作用。 我正在尝试开发一个joomla模块,我有那个抓取图像的代码
static function getList($params) {
$filter = '\.png$|\.gif$|\.jpg$|\.bmp$';
$path = $params->get('path');
$files = JFolder::files(JPATH_BASE.$path,$filter);
$i=0;
$lists = array();
foreach ($files as $file) {
$lists[$i]['title'] = JFile::stripExt($file);
$lists[$i]['image'] = JURI::base().str_replace(DS,'/',substr($path,1)).'/'.$file;
$i++;
}
return $lists;
}
然后我添加它来创建缩略图
<?php
$filepath=JUri::root() . '/images/';
$thumbpath=JUri::root() . '/images/thumbs/';
$success=createThumbnail($filepath, $thumbpath, 160, 160, array(0,0,0));
?>
<?php foreach ($lists as $item):?>
<div>
<?php echo $success;?>
</div>
<?php endforeach; ?>
但它失败了。提前谢谢。