1

I found this code here at the stack (Creating a thumbnail from an uploaded image), and it works fine for images (png, jpeg, jpg) but when i try with the same built-in function it just doesn't work with gif's (http://php.net/manual/en/function.imagecreatefromgif.php). Furthermore whenever you upload an image and use the function to resize the image the resized image's background is black.

So my questions are

  1. what do i do to prevent the background from turning black?
  2. how do i extend the function so it also covers gif's?

    function createThumbnail($type,$image_name,$new_width,$new_height,$uploadDir,$moveToDir){
    $path = $uploadDir . $image_name;
    $mime = getimagesize($path);
    if($mime['mime']=='image/png') { 
        $src_img = imagecreatefrompng($path);
    }
    if($mime['mime']=='image/gif') { 
        $src_img = imagecreatefromgif($path);
    }
    if($mime['mime']=='image/jpg' || $mime['mime']=='image/jpeg' || $mime['mime']=='image/pjpeg') {
        $src_img = imagecreatefromjpeg($path);
    }   
    $old_x      =   imageSX($src_img);
    $old_y      =   imageSY($src_img);
    $thumb_w    =   $new_width;
    $thumb_h    =   $new_height;
    $dst_img    =   ImageCreateTrueColor($thumb_w,$thumb_h);
    imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y); 
    // New save location
    $image_name_new = explode(".", $image_name);
    if ($type == 1){
        $image_name = $image_name_new[0] . "_thumb." . $image_name_new[1];
    } else if ($type == 2){
        $image_name = $image_name_new[0] . "_image." . $image_name_new[1];
    }
    $new_thumb_loc = $moveToDir . $image_name;
    if($mime['mime']=='image/png') {
        $result = imagepng($dst_img,$new_thumb_loc,8);
    }
    if($mime['mime']=='image/gif') {
        $result = imagegif($dst_img,$new_thumb_loc,8);
    }
    if($mime['mime']=='image/jpg' || $mime['mime']=='image/jpeg' || $mime['mime']=='image/pjpeg') {
        $result = imagejpeg($dst_img,$new_thumb_loc,80);
    }
    imagedestroy($dst_img); 
    imagedestroy($src_img);return $result;}
    
Umar Abdullah
  • 1,282
  • 1
  • 19
  • 37

0 Answers0