昨天需要做一个功能,把上传的图片制作成指定尺寸的缩略图。 由于指定的尺寸是正方形,而上传图大多是长条形,所以不足的部分用白色背景填充。
想想其实简单,就是把上传图和白色背景合并,再调整下位置居中就好。
结果第一步就不行,imagecreatetruecolor()创建的画布,始终是黑色。
$thumb = imagecreatetruecolor($newwidth, $newheight);
imagecolorallocate($thumb, 255, 255, 255);
百度之后发现解决方案,是需要imagefill()这个方法来上色,
$thumb = imagecreatetruecolor($newwidth, $newheight);
$white = imagecolorallocate($thumb, 255, 255, 255);
imagefill($thumb, 0,0, $white);
这样就是白色背景了。
顺便把这个制作缩略图的代码也记录一下。
<?php
$filename = './Cordovan wallet.jpg';
//$filename = './book.jpg';
// Content type
header('Content-Type: image/jpeg');
// Get new sizes
list($width, $height) = getimagesize($filename);
$newwidth = 350;
$newheight = 350;
$w=0;//宽度偏移量
$h=0;//高度偏移量
if($width>$height){
$percent = $newwidth/$width;
$newwidth1 = $width * $percent;
$newheight1 = $height * $percent;
$h = ($newwidth1-$newheight1)/2;
}
else{
$percent = $newheight/$height;
$newwidth1 = $width * $percent;
$newheight1 = $height * $percent;
$w = ($newheight1-$newwidth1)/2;
}
// Load
$thumb = imagecreatetruecolor($newwidth, $newheight);
$white = imagecolorallocate($thumb, 255, 255, 255);
imagefill($thumb, 0,0, $white);
$source = imagecreatefromjpeg($filename);
// Resize
imagecopyresized($thumb, $source, $w, $h, 0, 0, $newwidth1, $newheight1, $width, $height);
// Output
imagejpeg($thumb);
?>