views:

26

answers:

2

Hi,

I have a problem with an image library. I think I know the problem but I know very little about images and was hoping that someone could tell me what precisely is going wrong.

What I am trying to do is resize a .png and preserve the transparency. When I resize and save a .png image it looses its transparency and turns black.

I believe that the problem is with the imagecreatetruecolor function in the resize function. The documentation suggests this returns a black image. I don't think this is what I am after.

Could someone have a nosey and tell me if the problem does in fact lie with the resize function and how this should be fixed.

Thanks.

class ResizeImage {

    // Load Image
    function load($filename) {
        $image_info = getimagesize($filename);
        $this->image_type = $image_info[2];

        if( $this->image_type == IMAGETYPE_JPEG ) {
            $this->image = imagecreatefromjpeg($filename);
        } elseif( $this->image_type == IMAGETYPE_GIF ) {
            $this->image = imagecreatefromgif($filename);
        } elseif( $this->image_type == IMAGETYPE_PNG ) {
            $this->image = imagecreatefrompng($filename);
            imagealphablending($this->image, true);
            imagesavealpha($this->image, true);
        }
    }

        // Resize the image
        function resize($width,$height) {
        $new_image = imagecreatetruecolor($width, $height);
        imagecopyresampled($new_image, $this->image, 0, 0, 0, 0, $width, $height, $this->getWidth(), $this->getHeight());
        $this->image = $new_image;
    }

        // Save the image
    function save($filename, $image_type='', $compression=100, $permissions=null) {
        if ($image_type != '') {
            $this->image_type = $image_type;
        }

        if( $this->image_type == IMAGETYPE_JPEG ) {
            imagejpeg($this->image,$filename,$compression);
        } elseif( $this->image_type == IMAGETYPE_GIF ) {
            imagegif($this->image,$filename);
        } elseif( $this->image_type == IMAGETYPE_PNG ) {
            imagepng($this->image,$filename);
        }
        if( $permissions != null) {
            chmod($filename,$permissions);
        }
    }
A: 

try using imagesavealpha, for example:

function resize($width,$height) {
        $new_image = imagecreatetruecolor($width, $height);
        imagesavealpha($new_image, true);
        imagecopyresampled($new_image, $this->image, 0, 0, 0, 0, $width, $height, $this->getWidth(), $this->getHeight());
        $this->image = $new_image;
    }
Colin Pickard
+1  A: 

Try to use Primage class. Check example.

SeniorDev