我有一段代码似乎在处理实时服务器上的jpeg时工作正常,但处理png或gif总是给我黑色图像。有趣的是,在我的测试服务器上,它处理png很好,但也没有GIF。这个函数应该适用于所有mime类型,但我猜php在查找文件路径时遇到的问题是文件路径不是jpg。除了切换到python之外,有没有人想要修改我的功能来正确处理png和gif?
function ak_img_resize($target, $newcopy, $w, $h, $ext) {
list($w_orig, $h_orig) = getimagesize($target);
$scale_ratio = $w_orig / $h_orig;
if (($w / $h) > $scale_ratio) {
$w = $h * $scale_ratio; //if original image width is greater than height
} else {
$h = $w / $scale_ratio; //if original image height is greater than width
}
$img = "";
$ext = strtolower($ext);
if ($ext == "gif"){
$img = imagecreatefromgif($target);//gd functions
} else if($ext =="png"){
$img = imagecreatefrompng($target);
} else {
$img = imagecreatefromjpeg($target);
}
$tci = imagecreatetruecolor($w, $h);//makes a black rectangle with width and height you specify
// imagecopyresampled(dst_img, src_img, dst_x, dst_y, src_x, src_y, dst_w, dst_h, src_w, src_h)
imagecopyresampled($tci, $img, 0, 0, 0, 0, $w, $h, $w_orig, $h_orig);
if ($ext == "gif"){
imagegif($tci, $newcopy);
} else if($ext =="png"){
imagepng($tci, $newcopy);
} else {
imagejpeg($tci, $newcopy, 84);
}
}
$file_name = $_FILES["uploaded_file"]["name"]; // The file name
$path_suffix = pathinfo($file_name);
$path_ext = $path_suffix['extension'];
$target_file = "uploads/$file_name";
$list_file = "uploads/list_$file_name";
$wmax = 400;
$hmax = 400;
ak_img_resize($target_file, $list_file, $wmax, $hmax, $path_ext);
答案 0 :(得分:1)
我亲自尝试过你的代码,没有触及这个功能,但只修改了底部部分,它运行得很好。 这就是我的工作脚本的样子(我通过GET从URL获取文件名,用于调试):
<?php
function ak_img_resize($target, $newcopy, $w, $h, $ext) {
list($w_orig, $h_orig) = getimagesize($target);
$scale_ratio = $w_orig / $h_orig;
if (($w / $h) > $scale_ratio) {
$w = $h * $scale_ratio; //if original image width is greater than height
} else {
$h = $w / $scale_ratio; //if original image height is greater than width
}
$img = "";
$ext = strtolower($ext);
if ($ext == "gif"){
$img = imagecreatefromgif($target);//gd functions
} else if($ext =="png"){
$img = imagecreatefrompng($target);
} else {
$img = imagecreatefromjpeg($target);
}
$tci = imagecreatetruecolor($w, $h);//makes a black rectangle with width and height you specify
// imagecopyresampled(dst_img, src_img, dst_x, dst_y, src_x, src_y, dst_w, dst_h, src_w, src_h)
imagecopyresampled($tci, $img, 0, 0, 0, 0, $w, $h, $w_orig, $h_orig);
if ($ext == "gif"){
imagegif($tci, $newcopy);
} else if($ext =="png"){
imagepng($tci, $newcopy);
} else {
imagejpeg($tci, $newcopy, 84);
}
}
$file_name = $_GET['img']; // The file name
$path_ext = substr($file_name, -3);
$target_file = $file_name;
$list_file = 'list_' . $file_name;
$wmax = 400;
$hmax = 400;
ak_img_resize($target_file, $list_file, $wmax, $hmax, $path_ext);
?>
请注意,我测试了几个不同的png,jpg和gif文件,它们都调整得很好,也适用于你,除非原始图像文件本身有问题。
希望这有帮助。