Php 创建png图像缩略图时出现问题!
我使用了下面的php函数来创建缩略图Php 创建png图像缩略图时出现问题!,php,image,png,thumbnails,transparent,Php,Image,Png,Thumbnails,Transparent,我使用了下面的php函数来创建缩略图 function createThumbs( $pathToImages, $pathToThumbs, $thumbWidth ) { $dir = opendir( $pathToImages ); while (false !== ($fname = readdir( $dir ))) { $info = pathinfo($pathToImages . $fname); if ( strtolower($info['e
function createThumbs( $pathToImages, $pathToThumbs, $thumbWidth )
{
$dir = opendir( $pathToImages );
while (false !== ($fname = readdir( $dir ))) {
$info = pathinfo($pathToImages . $fname);
if ( strtolower($info['extension']) == 'jpg' || strtolower($info['extension']) == 'png' )
{
// load image and get image size
if(strtolower($info['extension']) == 'jpg')
$img = imagecreatefromjpeg( "{$pathToImages}{$fname}" );
else
$img = imagecreatefrompng( "{$pathToImages}{$fname}" );
$width = imagesx( $img );
$height = imagesy( $img );
// calculate thumbnail size
$new_width = $thumbWidth;
$new_height = floor( $height * ( $thumbWidth / $width ) );
// create a new tempopary image
$tmp_img = imagecreatetruecolor( $new_width, $new_height );
// copy and resize old image into new image
//imagecopyresized( $tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height );
imagecopyresampled($tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height );
// save thumbnail into a file
if(strtolower($info['extension']) == 'jpg')
imagejpeg( $tmp_img, "{$pathToThumbs}{$fname}" );
else
imagepng( $tmp_img, "{$pathToThumbs}{$fname}" );
}
}
// close the directory
closedir( $dir );
}
为jpg图像创建适当的缩略图。但对于png透明图像,缩略图是用黑色背景创建的。如何使函数适用于png图像?请给我提个建议。提前谢谢。我记不清确切的细节,但您需要仔细阅读,并尝试使用和 如果我没有记错的话,您需要将ImageAlpha设置为off,然后将imagesavealpha设置为true。(事实上,是的,imagesavealpha()的手册页就暗示了这一点) 因此,在代码末尾:
// save thumbnail into a file
if(strtolower($info['extension']) == 'jpg'){
imagejpeg( $tmp_img, "{$pathToThumbs}{$fname}");
}else{
imagealphablending($tmp_img,false);
imagesavealpha($tmp_img,true);
imagepng( $tmp_img, "{$pathToThumbs}{$fname}" );
}
你想重新发明轮子吗?用法:)
那很容易
<?php
// load the library
require 'Thumbnailer';
// make callback function
function myfunc(& $thumb) {
// that will make a image thumbnail square 100x100px
$thumb->thumbSquare(100)->save('photos/output/'.$thumb->filename);
}
// call batch helper
// find all jpg, png and gif images in /photos/directory
Thumbnailer::batch('myfunc', '/photos/directory/*.{jpg,png,gif}');
?>