简体   繁体   English

调整大小后,imagecreatefromjpeg返回黑色图像

[英]Imagecreatefromjpeg returns a black image after resize

I have a script to resize an uploaded image, but when I use it, it just returns a black square. 我有一个脚本来调整上传图像的大小,但是当我使用它时,它只会返回一个黑色正方形。 All error messages are pointing at this function: 所有错误消息都指向此函数:

function resizeImage($image,$width,$height,$scale) {
    $newImageWidth = ceil($width * $scale);
    $newImageHeight = ceil($height * $scale);
    $newImage = imagecreatetruecolor($newImageWidth,$newImageHeight);
    $source = imagecreatefromjpeg($image);
    imagecopyresampled($newImage,$source,0,0,0,0,$newImageWidth,$newImageHeight,$width,$height);
    imagejpeg($newImage,$image,90);
    chmod($image, 0777);
    return $image;
}

My error logs: 我的错误日志:

PHP Warning:  imagecreatefromjpeg() [<a href='function.imagecreatefromjpeg'>function.imagecreatefromjpeg</a>]: gd-jpeg: JPEG library reports unrecoverable error
PHP Warning:  imagecreatefromjpeg() [<a href='function.imagecreatefromjpeg'>function.imagecreatefromjpeg</a>]: 'img/[hidden].jpg' is not a valid JPEG file
PHP Warning:  imagecopyresampled(): supplied argument is not a valid Image resource
  1. Check if the imagecreatetruecolor succeeded. 检查imagecreatetruecolor成功。 If the new image is "large" it could exceed the PHP memory_limit. 如果新图像为“大”,则可能超出PHP的memory_limit。 This function returns FALSE if it failed for any reason. 如果该函数由于任何原因失败,则返回FALSE。
  2. Ditto with imagecreatefromjpeg() . imagecreatefromjpeg()同上。 The two individual images may fit within the memory limit but together could be too large. 这两个单独的图像可能适合内存限制,但在一起可能太大。 The source image may also not exist. 源图像也可能不存在。 This function returns FALSE if it failed for any reason 如果该函数由于任何原因失败,则返回FALSE
  3. Check if the imagecopyresampled() failed - it also returns FALSE on failure. 检查imagecopyresampled()失败-失败时还返回FALSE。
  4. Check if imagejpeg() failed - maybe you don't have write permissions on whatever file you're specifying in $image . 检查imagejpeg()失败-也许您没有对$image指定的任何文件的写权限。 And again, this function returns FALSE on failure. 同样,此函数在失败时返回FALSE。

According to Marc B's answer you could probably make a check if the file is a JPG file. 根据Marc B的回答,您可能可以检查该文件是否为JPG文件。 (JPEG, JPG, jpg, jpeg extensions). (JPEG,JPG,JPG,JPEG扩展名)。

it could be something like: 可能是这样的:

$file = explode(".", $_POST['file']);
$file_ext = $file[count($file)]; // Get the last thing in the array - in this way the filename can containg dots (.)
$allowed_ext = array('jpg', 'JPG', 'jpeg', 'jpg');

if( in_array($file_ext, $allowed_ext )
{
    // The code for creating the image here.
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM