Skip to content
Advertisement

PHP – Black background after resizing transparent png and gif

I am using the below code to resize images. When transparent images, (png/gif) are uploaded the new images created have black background. How can i make the background white after resizing? pls help

    $info = pathinfo($_FILES['file']['name']);
    $ext = $info['extension']; // get the extension of the file
    $newname = "testing".".".$ext; 
    $target = 'uploads/'.$newname;
    move_uploaded_file( $_FILES['file']['tmp_name'], $target);;
    $filename=$newname;
    if($ext=='jpg'||$ext=='jpeg') 
    {
        $im = imagecreatefromjpeg('uploads/'.$filename);
    } 
    else if ($ext=='gif') 
    {
        $im = imagecreatefromgif('uploads/'.$filename);
    } 
    else if ($ext=='png') 
    {
        $im = imagecreatefrompng('uploads/'.$filename);
    }
    $ox = imagesx($im);
    $oy = imagesy($im);
    $nm = imagecreatetruecolor(245, 184);
    imagealphablending( $nm, FALSE );
    imagesavealpha( $nm, TRUE );
    imagecopyresized($nm, $im, 0,0,0,0,245,184,$ox,$oy);
    imagejpeg($nm,  'uploads/' . $filename);

Advertisement

Answer

Try using

  imagecolortransparent 

in your code.

http://www.php.net/manual/en/function.imagecolortransparent.php

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement