Diagnosing the Black Image Problem in PHP Resizers
Your current ImgResizer class handles JPEGs perfectly because imagecreatefromjpeg() successfully loads the source data into a GD resource, and imagejpeg() correctly dumps it back out. The failure with PNG files isn't a logic error in your scaling math; it is a fundamental mismatch between your loader function and your output function.
When you pass a PNG path to imagecreatefromjpeg(), PHP attempts to interpret the file as a JPEG stream. Since the binary headers of a PNG file do not match the JPEG specification, GD fails to initialize a valid image resource from that data. In many configurations, this silent failure results in an empty or uninitialized resource. When you subsequently call imagecopyresampled() on this broken source onto your new canvas ($tmp), nothing is actually copied. You are drawing transparency or null bytes into a truecolor context, which renders as black when saved with imagejpeg().
To support PNG input while maintaining the ability to output JPEGs (or other formats), you must implement a format-agnostic loader. The GD library provides a family of imagecreatefrom... functions for this exact purpose: imagecreatefrompng(), imagecreatefromgif(), and imagecreatefromwebp().
The most robust approach is to inspect the file's MIME type or its magic number before attempting to load it. This ensures that regardless of whether the user uploads a .jpg or a .png, you use the correct decoder.
Here is how you can refactor the loader logic:
function resize($newWidth, $targetFile) {
if (empty($newWidth) || empty($targetFile)) {
return false;
}
// Determine source format to load the correct resource
$srcType = getimagesize($this->originalFile);
if ($srcType === false) {
return false; // File not found or unreadable
}
// Create the source resource based on the file type
// imagecreatefromjpeg, imagecreatefrompng, etc.
$sourceHandler = null;
switch ($srcType[2]) { // $srcType[2] is the MIME media type (e.g., 'image/jpeg', 'image/png')
case 'image/jpeg':
$sourceHandler = imagecreatefromjpeg($this->originalFile);
break;
case 'image/png':
$sourceHandler = imagecreatefrompng($this->originalFile);
break;
case 'image/gif':
$sourceHandler = imagecreatefromgif($this->originalFile);
break;
default:
return false; // Unsupported format
}
if (!$sourceHandler) {
return false;
}
list($width, $height) = getimagesize($this->originalFile);
$newHeight = ($height / $width) * $newWidth;
// Create the destination canvas.
// If you want to preserve PNG transparency when saving as PNG, use 'truecolor' or specific palette flags.
$tmp = imagecreatetruecolor($newWidth, $newHeight);
// Perform the resampling
imagecopyresampled($tmp, $sourceHandler, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
if (file_exists($targetFile)) {
unlink($targetFile);
}
// Determine output format based on target file extension or desired behavior
$targetType = pathinfo($targetFile, PATHINFO_EXTENSION);
switch ($targetType) {
case 'jpg':
case 'jpeg':
imagejpeg($tmp, $targetFile, 95);
break;
case 'png':
// When saving PNGs, using 0 for compression level allows full transparency support.
// Using > 0 might cause issues with alpha channels depending on GD version.
imagepng($tmp, $targetFile);
break;
default:
return false;
}
// Free memory
imagedestroy($sourceHandler);
imagedestroy($tmp);
return true;
}
Critical Trade-offs and Pitfalls
The primary trade-off here is performance versus flexibility. Checking the MIME type adds a negligible overhead, but you must handle the cleanup explicitly. In your original code, $src and $tmp were never destroyed. While PHP's garbage collector will eventually reclaim this memory, holding onto large image resources in a loop (e.g., processing an upload folder) can lead to "out of memory" errors on shared hosting environments where memory_limit is strict. Always call imagedestroy() after you are done with the resource.
Another common mistake when switching formats is losing transparency. If you load a PNG with an alpha channel and save it as a JPEG using imagejpeg(), the transparent pixels become black (or white, depending on background settings). Conversely, if your goal is to resize a PNG and keep it as a PNG, ensure you do not pass a quality parameter to imagepng() that might strip transparency in older GD versions. Stick to the default parameters for PNG output unless specific compression is required.
By decoupling the input format from the processing logic and explicitly handling the output format via file extension, your resizer becomes truly universal. This pattern eliminates the "black image" bug entirely and future-proofs your script against new formats like WebP or AVIF if you decide to add them later.