PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, July 26, 2022

[FIXED] How can you use PHP GD imagecrop on a PNG whilst maintaining transparency?

 July 26, 2022     crop, image, php, png, transparency     No comments   

Issue

Whenever I call PHP GD's imagecrop() on a PNG with transparency it is turning the transparent part black instead of maintaining it.

I have recently written a function to scale transparent PNGs whilst maintaining the transparency (see below), so I understand about using imagecopyresampled etc.

function scale_png($image, $resize_w = FALSE, $resize_h = FALSE, $alpha = 127)
{
    $src_w = imagesx($image);
    $src_h = imagesy($image);
    if (! $resize_w) {$resize_w = $src_w;}
    if (! $resize_h) {$resize_h = $src_h;}
    $output = imagecreatetruecolor($resize_w, $resize_h);
    imagealphablending($output, FALSE);
    imagesavealpha($output, TRUE);
    $transparent = imagecolorallocatealpha($output, 255, 255, 255, $alpha);
    imagefilledrectangle($output, 0, 0, $resize_w, $resize_h, $transparent);
    imagecopyresampled($output, $image, 0, 0, 0, 0, $resize_w, $resize_h, $src_w, $src_h);

    return $output;
}

This function above is working fine, but when I also try to do imagecrop() on the same PNG this is when I get the black background.

Is there any easy way of performing this crop successfully? I can't seem to find any good examples.

I would rather not have to write another complex function like the one above in order to crop the image out using x, y, w, h and imagecopyresampled() if possible, as it's a major ball ache.

Any GD boffins out there care to impart their valued knowledge on me?


Solution

The way I understand there is nothing complicated here, you have to save the alpha channels before performing the crop.

$img = imagecreatefrompng("./cover.png");
imagealphablending($img, false);
imagesavealpha($img, true);
$resource = imagecrop($img, ['x' => 0, 'y' => 0, 'width' => 500, 'height' => 500]);


Answered By - imal hasaranga perera
Answer Checked By - Cary Denson (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing