Resize images with transparency in php

前端 未结 2 696
鱼传尺愫
鱼传尺愫 2021-01-04 11:31

I have looked all over for how to correctly manage alpha when I\'m resizing a png. I\'ve managed to get it to keep transparency, but only for pixels that are completely tran

相关标签:
2条回答
  • 2021-01-04 11:44
    "They have not worked at all and I'm not sure why."
    

    Well you must have been doing something wrong. The code from the linked duplicate with a couple of lines added to load and save the image:

    $im = imagecreatefrompng(PATH_TO_ROOT."var/tmp/7Nsft.png");
    
    $srcWidth = imagesx($im);
    $srcHeight = imagesy($im);
    
    $nWidth = intval($srcWidth / 4);
    $nHeight = intval($srcHeight /4);
    
    $newImg = imagecreatetruecolor($nWidth, $nHeight);
    imagealphablending($newImg, false);
    imagesavealpha($newImg,true);
    $transparent = imagecolorallocatealpha($newImg, 255, 255, 255, 127);
    imagefilledrectangle($newImg, 0, 0, $nWidth, $nHeight, $transparent);
    imagecopyresampled($newImg, $im, 0, 0, 0, 0, $nWidth, $nHeight,
        $srcWidth, $srcHeight);
    
    imagepng($newImg, PATH_TO_ROOT."var/tmp/newTest.png");
    

    Produces the image:

    A resized PNG with transparency

    i.e. this question (and answer) are a complete duplicate.

    0 讨论(0)
  • 2021-01-04 11:48

    i have used simpleImage class for resizing image. You can re-size your image with maintaining aspect ratio. this class is using imagecreatetruecolor and imagecopyresampled core Php functions to re-size image

      $new_image = imagecreatetruecolor($width, $height);
      imagecopyresampled($new_image, $this->image, 0, 0, 0, 0, $width, $height, $this->getWidth(), $this->getHeight());
      $this->image = $new_image;
    

    find complete code at http://www.white-hat-web-design.co.uk/blog/resizing-images-with-php/

    0 讨论(0)
提交回复
热议问题