在PHP中保存上传图像文件的平方缩略图

时间:2016-02-20 22:58:30

标签: php thumbnails

我正在尝试使用php创建并保存上传图像文件的平方版本(拇指)。我当前的脚本按原样裁剪它,但图像完全是黑色的。这是我的代码:

if ($_FILES['profile_pic']['type'] == "image/png") {
                            $is_image = true;
                            $newImage = imagecreatefrompng($img);
                        } else if ($_FILES['profile_pic']['type'] == "image/jpeg") {
                            $is_image = true;
                            $newImage = imagecreatefromjpeg($img);
                        } else if ($_FILES['profile_pic']['type'] == "image/gif") {
                            $is_image = true;
                            $newImage = imagecreatefromgif($img);
                        } else {
                            $is_image = false;
                        }
                        $img         = $_FILES["profile_pic"]['tmp_name'];
                        $min_width   = 100;
                        $min_height  = 100;
                        $width       = 0;
                        $height      = 0;
                        if ($is_image) {
                            list($width, $height) = getimagesize($img);
                        }

                        if ($is_image && $height >= $min_height && $width >= $min_width) {
                            $img         = $_FILES["profile_pic"]['tmp_name'];
                            $imgPath     = "../img/profile_pics/{$member_id}.png";

                            // Resize
                            $aspect_ratio = $width / $min_width;
                            $new_height = $height * $aspect_ratio;
                            $canvas1 = imagecreatetruecolor($min_width, $new_height);
                            imagecopyresampled($canvas1, $newImage, 0, 0, 0, 0, $min_width, $new_height, $width, $new_height);

                            // Crop
                            $canvas2 = imagecreatetruecolor($min_width, $min_height);
                            imagecopyresampled($canvas2, $newImage, 0, 0, 0, 0, $min_width, $min_height, $min_width, $min_height);
                            imagejpeg($canvas2, $imgPath, 80);
                            imagedestroy($canvas1);

                        }

我意识到之前已经问过这个问题,但由于某种原因,我似乎无法使自己的脚本工作。

1 个答案:

答案 0 :(得分:0)

您尝试通过$img或类似内容创建imagecreatefrompng($img)后初始化=MATCH(A1,$B$1:$B$10,0) 。可能是它失败的原因。

我也不确定您是否要将所有图像保存到* .png文件中,无论其来源类型如何:您可能希望实现更灵活的内容。

相关问题