我已经实现了一些代码,允许我重新采样图像到不同的大小,尽管目前它似乎只适用于jpeg。我想我必须添加imagepng($image_p, null, 100);
类型的代码片段,尽管这似乎仍然失败。至于头文件,我不太确定如何允许这三种文件类型?
<?php
// The file
$filename = 'Channel-Art-Spec.png';
// Set a maximum height and width
$width = 300;
$height = 300;
// Content type
header('Content-Type: image/jpeg');
// Get new dimensions
list($width_orig, $height_orig) = getimagesize($filename);
$ratio_orig = $width_orig/$height_orig;
if ($width/$height > $ratio_orig) {
$width = $height*$ratio_orig;
} else {
$height = $width/$ratio_orig;
}
// Resample
$image_p = imagecreatetruecolor($width, $height);
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
// Output
imagejpeg($image_p, null, 100);
?>
您需要使用适合您正在读取的文件类型的函数而不是imagecreatefromjpeg()
。
getimagesize()
检查类型并在imageinfo
数组中给出IMAGETYPE_XXX
(参见文档)。
您也可以使用效率稍低的imagecreatefromstring(file_get_contents($filename))
。
您的代码只适用于JPEG图像的原因是代码中的以下行:
$image = imagecreatefromjpeg($filename);
对于PNG图像使用imagecreatefrompng