Skip to content
PHP imagecreatefrompng Function: Syntax, Parameters, Return Value, and Example Usage

PHP imagecreatefrompng Function: Syntax, Parameters, Return Value, and Example Usage

This article explains the PHP imagecreatefrompng function, detailing its syntax, parameters, return values, and provides a complete example that loads a PNG file, handles errors, creates a blank image, draws a rectangle, and outputs the result as a PNG image.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community

The imagecreatefrompng function creates a new image resource from a PNG file or URL.

Syntax : resource imagecreatefrompng(string $filename) It returns an image identifier representing the loaded image on success, or FALSE on failure.

Parameter

filename : Path to the PNG image file.

Return value

On success, an image resource is returned; on failure, FALSE is returned.

Example

<?php
function LoadPNG($imgname)
{
    // Attempt to open
    $im = @imagecreatefrompng($imgname);
    // See if it failed
    if (!$im) {
        // Create a blank image
        $im = imagecreatetruecolor(150, 30);
        $bgc = imagecolorallocate($im, 255, 255, 255);
        $tc = imagecolorallocate($im, 0, 0, 0);
        imagefilledrectangle($im, 0, 0, 150, 30, $bgc);
        // Output an error message
        imagestring($im, 1, 5, 5, 'Error loading ' . $imgname, $tc);
    }
    return $im;
}
header('Content-Type: image/png');
$img = LoadPNG('bogus.image');
imagepng($img);
imagedestroy($img);
?>

This example demonstrates loading a PNG file, handling a failure by creating a placeholder image with an error message, sending the appropriate header, outputting the image as PNG, and finally freeing the image resource.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendPNGimage-processinggd-library
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.