为什么imagecreatefromjpeg()函数没有打开文件夹中的文件

时间:2018-05-29 06:34:44

标签: php

我想在imagecreatefromjpeg函数的帮助下上传后调整图像文件的大小,但是这个函数无法从文件夹中访问该文件,因为它抛出了错误,即**

  

imagecreatefromjpeg():gd-jpeg:JPEG库报告不可恢复   错误:在D:\ xampp \ htdocs \ resize \ index.php

**但文件已上传&我写了下面的代码。

<form method="post" enctype="multipart/form-data">
    <input type="file" name="f1">
    <input type="submit" name="btn" value="Upload">
</form>

<?php
ini_set("memory_limit","256M");
if(isset($_POST['btn'])) 
{

    if(move_uploaded_file($_FILES['f1']['tmp_name'], "images/".$_FILES['f1']['name'])) 
    {          


        $filename = "images/".$_FILES['f1']['name'];


        $original_info = getimagesize($filename);
         $original_w = $original_info[0];
        $original_h = $original_info[1];
        echo "<img src =$filename>";
        if( ini_get('allow_url_fopen') ) {
          // it's enabled, so do something        

            $original_img = imagecreatefromjpeg($filename);         
            $thumb_w = 100;
            $thumb_h = 60;
            $thumb_img = imagecreatetruecolor($thumb_w, $thumb_h);
            $thumb_filename = "new.jpg";
            imagecopyresampled($thumb_img, $original_img,
                               0, 0,
                               0, 0,
                               $thumb_w, $thumb_h,
                               $original_w, $original_h);
            imagejpeg($thumb_img, $thumb_filename);
            imagedestroy($thumb_img);
            imagedestroy($original_img); 
        }       
    }   
}
?>

1 个答案:

答案 0 :(得分:0)

您必须确保文件类型。

<?php
    $type = exif_imagetype($filename);
    // types 1=>gif, 2=>jpg, 3=>png, 6=>bmp
    switch ($type) {
        case 1 : $img = imageCreateFromGif ( $src );break;
        case 2 : $img = imageCreateFromJpeg( $src );break;
        case 3 : $img = imageCreateFromPng ( $src );break;
        case 6 : $img = imageCreateFromBmp ( $src );break;
    }
    // or if you cannot use exif_imagetype
    // you can use getImageSize
    $type = getImageSize($filename);
    switch ($type) {
        case 'image/gif'  : $img = imageCreateFromGif ( $filename ); break;
        case 'image/jpeg' : $img = imageCreateFromJpeg( $filename ); break;
        case 'image/png'  : $img = imageCreateFromPng ( $filename ); break;
        case 'image/bmp'  : $img = imageCreateFromBmp ( $filename ); break;
    }
//// than you can create new file with resize or crop...

?>