我使用GD功能调整照片大小。 我的问题是只能创建黑色图像,而如果我更改同一图像的扩展名并将PNG更改为jpg,则效果很好。 我测试了其他png图像,其中一些图像已调整好大小。 您认为问题出在哪里?
我的代码:
<?php
function getImageRatio($sourcePath){
list($width, $height) = getimagesize($sourcePath);
$ratio = $height / $width;
return $ratio;
}
function resizeImage($sourcePath, $newWidth, $newHeight, $destination = null) {
$parts = explode(".", $sourcePath);
$ext = $parts[count($parts)-1];
if ($ext == 'jpg' || $ext == 'jpeg'){
$format = 'jpg';
} else {
$format = 'png';
}
if ($format == 'jpg') {
$sourceImage = imagecreatefromjpeg($sourcePath);
}
if ($format == 'png') {
$sourceImage = imagecreatefrompng($sourcePath);
}
list($srcWidth, $srcHeight) = getimagesize($sourcePath);
$ratio = getImageRatio($sourcePath);
if ($newHeight == 0){
$newHeight = floor($newWidth * $ratio);
}
if ($newWidth == 0){
$newWidth = floor($newHeight / $ratio);
}
$destinationImage = imagecreatetruecolor($newWidth, $newHeight);
imagecopyresampled($destinationImage, $sourceImage, 0, 0, 0, 0, $newWidth, $newHeight, $srcWidth, $srcHeight);
if ($destination == null){
header('Content-Type: image/jpeg');
if ($format == 'jpg') {
imagejpeg($destinationImage, null, 100);
}
if ($format == 'png') {
imagepng($destinationImage);
}
} else {
if ($format == 'jpg') {
imagejpeg($destinationImage, $destination, 100);
}
if ($format == 'png') {
imagepng($destinationImage, $destination);
}
}
}
所以我用它们:
public function process($imageName, $size) {
$sizeArray = explode("*", $size);
$originalPath = rootUrl() . "/image/" . $imageName . ".png";
$thumbPath = getcwd() . "/image/" . $imageName . "_" . $size . ".png";
resizeImage($originalPath, $sizeArray[0], 0, $thumbPath);
}