Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Image resize issue in PHP - gd creates ugly resized images

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

/*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);
    imagedestroy($img);
    return $returnvalue;
}

and I call this function with following parameters

createThumbnailofSize($sourcefilepath,$destdir,48,48,false);

but the problem is the resulting image is of very poor quality, when I perform the same operation with Adobe Photo shop, it performs a good conversion.. why it is so? I am unable to find any quality parameter, through which I change the quality of output image..

like image 763
Muhammad Ummar Avatar asked Oct 07 '09 19:10

Muhammad Ummar


People also ask

How do I scale an image in PHP?

The imagescale() function is an inbuilt function in PHP which is used to scale an image using the given new width and height. Parameters: This function accepts four parameters as mentioned above and described below: $image: It is returned by one of the image creation functions, such as imagecreatetruecolor().

What is resize in image?

Resizing allows you to make your image smaller or larger without cutting anything out. Resizing alters the image's dimensions, which typically affects the file size and image quality. The most common reason for resizing photos is to reduce the size of large files to make them easier to email or share online.


1 Answers

Use imagecopyresampled() instead of imagecopyresized().

like image 78
timdev Avatar answered Oct 06 '22 00:10

timdev