Image resize issue in PHP - gd creates ugly resized images

前端 未结 5 581
旧时难觅i
旧时难觅i 2020-12-17 00:54

I am creating thumbnails of fixed height and width from my PHP script using the following function

/*creates thumbnail of required dimensions*/
function crea         


        
相关标签:
5条回答
  • 2020-12-17 01:12

    if it is image quality you are after you need to give the quality parameter when you save the image using imagejpeg($tmp_img,$thumbnail_path,100) //default value is 75

    /*creates thumbnail of required dimensions*/
    function 
    createThumbnailofSize($sourcefilepath,$destdir,$reqwidth,$reqheight,$aspectratio=false)
    {
        /*
         * $sourcefilepath =  absolute source file path of jpeg
         * $destdir =  absolute path of destination directory of thumbnail ending with "/"
         */
        $thumbWidth = $reqwidth; /*pixels*/
        $filename = split("[/\\]",$sourcefilepath);
        $filename = $filename[count($filename)-1];
        $thumbnail_path = $destdir.$filename;
        $image_file = $sourcefilepath;
    
    $img = imagecreatefromjpeg($image_file);
    $width = imagesx( $img );
    $height = imagesy( $img );
    
    // calculate thumbnail size
    $new_width = $thumbWidth;
    if($aspectratio==true)
    {
        $new_height = floor( $height * ( $thumbWidth / $width ) );
    }
    else
    {
        $new_height = $reqheight;
    }
    
    // create a new temporary image
    $tmp_img = imagecreatetruecolor( $new_width, $new_height );
    
    // copy and resize old image into new image
    imagecopyresized( $tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height );
    
    // save thumbnail into a file
    
    $returnvalue = imagejpeg($tmp_img,$thumbnail_path,100);
    imagedestroy($img);
    return $returnvalue;
    

    }

    0 讨论(0)
  • 2020-12-17 01:13

    tried using the php.Thumbnailer ?

    $thumb=new Thumbnailer("photo.jpg");
    $thumb->thumbSquare(48)->save("thumb.jpg");
    

    Result photo will be 48x48px. Easy right? :)

    0 讨论(0)
  • 2020-12-17 01:19

    Use imagecopyresampled() instead of imagecopyresized().

    0 讨论(0)
  • 2020-12-17 01:24

    You could also consider using ImageMagick (http://us3.php.net/manual/en/book.imagick.php) instead of Gd. I had the same problem just a couple of days ago with Java. Going for ImageMagick instead of Java Advanced Images resultet in a huge quality difference.

    0 讨论(0)
  • 2020-12-17 01:28

    You might also want to take a look at the Image_Transform PEAR package. It takes care of a lot of the low-level details for you and makes creating and maniuplating images painless. It also lets you use either GD or ImageMagick libraries. I've used it with great success on several projects.

    0 讨论(0)
提交回复
热议问题