以下PHP功能适用于jpg文件。然而,它会创建像素化和太裁剪的png文件。
如何更改功能以创建质量更高的png文件?
/**
* Resize image (while keeping aspect ratio and cropping it off sexy)
*
*
* @param string $source_image The location to the original raw image.
* @param string $destination The location to save the new image.
* @param int $final_width The desired width of the new image
* @param int $final_height The desired height of the new image.
* @param int $quality The quality of the JPG to produce 1 - 100
*
*
* @return bool success state
*/
public static function resizeImage($source_image, $file_ext, $destination, $final_width = 470, $final_height = 470, $quality = 85)
{
$image = imagecreatefromstring(file_get_contents($source_image));
$width = imagesx($image);
$height = imagesy($image);
if (!$width || !$height) {
return false;
}
$original_aspect = $width / $height;
$final_aspect = $final_width / $final_height;
if ($original_aspect >= $final_aspect) {
// horizontal image
$new_height = $final_height;
$new_width = $width / ($height / $final_height);
} else {
// vertical image
$new_width = $final_width;
$new_height = $height / ($width / $final_width);
}
$thumb = imagecreatetruecolor($final_width, $final_height);
// Resize and crop
imagecopyresampled($thumb,
$image,
0 - ($new_width - $final_width) / 2, // Center the image horizontally
0 - ($new_height - $final_height) / 2, // Center the image vertically
0, 0,
$new_width, $new_height,
$width, $height);
// if the file is a jpg file
if ($file_ext == 'jpg') {
// add '.jpg' to file path, save it as a .jpg file with our $destination_filename parameter
$destination .= '.jpg';
imagejpeg($thumb, $destination, $quality);
// if the file is a png file
} elseif ($file_ext == 'png') {
// add '.png' to file path, save it as a .jpg file with our $destination_filename parameter
$destination .= '.png';
imagepng($thumb, $destination);
}
if (file_exists($destination)) {
return true;
}
// default return
return false;
}
我对图像文件的知识非常有限,因此我不明白为什么这个函数适用于jpg-而不适用于png文件。
我会非常感谢任何帮助!