Page 1 of 1

Resample image function

Posted: Fri Dec 05, 2008 5:23 pm
by peterj
pickle | Please use [ code=php ], [ code=text ], etc tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read: :arrow: Posting Code in the Forums to learn how to do it too.


Fairly new to PHP.
I am using the below resample image function but when I insert a gif or png-24 image into my site the thumbnail has a black background.
I have read a couple of similar posts but am a little confused. How can I give my thumbnails a transparent background.

Code: Select all

public function resampleImage(){
    $imageName = $this->imageName;
    $filename    = $this->path.$imageName;
 
    // Set a maximum height and width
    $width = $this->maxWidth;
    $height = $this->maxHeight;
 
    // Content type (create one for gifs)
    header('Content-type: image/jpeg');
    header('Content-type: image/gif');
    header('Content-type: image/png');
 
    // Get dimensions & work out resample ratio and reset width/height vars depending:
    list($width_orig, $height_orig) = getimagesize($filename);
    $ratio_orig = $width_orig/$height_orig;
    if ($width/$height > $ratio_orig) {
       $width = $height*$ratio_orig;
    } else {
       $height = $width/$ratio_orig;
    }
 
    // Resample
    $image_p = imagecreatetruecolor($width, $height);
    $image = imagecreatefromjpeg($filename);
    $image = imagecreatefromgif($filename);
    $image = imagecreatefrompng($filename);
    imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
    // Output
    $thumbnail = "tn_".$imageName;
    $this->thumbnail = $thumbnailPath = $this->path.$thumbnail;
    $sampleRate = $this->sampleRate;
    $result = imagejpeg($image_p, $thumbnailPath, $sampleRate);
    if(!$result){
        return "imagejpeg creation was not successful";
    } else {
        return "resampled";
    }
 
}

Thanks


pickle | Please use [ code=php ], [ code=text ], etc tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read: :arrow: Posting Code in the Forums to learn how to do it too.[/color]

Re: Resample image function

Posted: Thu Jan 22, 2009 5:49 am
by Rovas
Saving a gif transparent background is more difficult than the one for a png one.
Look in the manual for imagesavealpha, imagecolortransparent and imagecollorallocate. The examples in those page will also help you.