[英]Save a squared thumbnail of uploaded image file in PHP
I am attempting to create and save a squared version (thumb) of an uploaded image file with php. 我正在尝试使用php创建并保存上传图像文件的平方版本(缩略图)。 My current script crops it as it should, but the image is completely black. 我当前的脚本按需裁剪,但是图像完全是黑色的。 Here is my code: 这是我的代码:
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);
}
I realise that there this question has been asked before, but for some reason I can't seem to make my own script work. 我意识到以前曾有人问过这个问题,但是由于某种原因,我似乎无法使自己的脚本正常工作。
You're initializing $img
after you try to create it via imagecreatefrompng($img)
or similar. 尝试通过imagecreatefrompng($img)
或类似方法创建$img
后,便要初始化它。 Might be the reason why it fails. 可能是失败的原因。
I'm also not sure you want to save all your images into a *.png file, regardless of their source type: you might want to implement something more flexible instead. 我也不确定无论源类型如何,您都希望将所有图像保存到* .png文件中:您可能想实现一些更灵活的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.