imagecreatefrompng

(PHP 4, PHP 5)

imagecreatefrompngСоздает новое изображение из файла или URL

Описание

resource imagecreatefrompng ( string $filename )

imagecreatefrompng() возвращает идентификатор изображения, представляющего изображение полученное из файла с заданным именем.

Подсказка

Для этой функции вы можете использовать URL в качестве имени файла, если была включена опция fopen wrappers. Смотрите более подробную информацию об определении имени файла в описании функции fopen(). Смотрите также список поддерживаемых оберток URL, их возможности, замечания по использованию и список предопределенных констант в Поддерживаемые протоколы и обработчики (wrappers).

Список параметров

filename

Путь к изображению PNG.

Возвращаемые значения

Возвращает ресурс изображения в случае успеха, или FALSE в случае ошибки.

Примеры

Пример #1 Пример обработки ошибки при загрузке PNG

<?php
function LoadPNG($imgname)
{
    
/* Пытаемся открыть */
    
$im = @imagecreatefrompng($imgname);

    
/* Если не удалось */
    
if(!$im)
    {
        
/* Создаем пустое изображение */
        
$im  imagecreatetruecolor(15030);
        
$bgc imagecolorallocate($im255255255);
        
$tc  imagecolorallocate($im000);

        
imagefilledrectangle($im0015030$bgc);

        
/* Выводим сообщение об ошибке */
        
imagestring($im155'Ошибка загрузки ' $imgname$tc);
    }

    return 
$im;
}

header('Content-Type: image/png');

$img LoadPNG('bogus.image');

imagepng($img);
imagedestroy($img);
?>

Результатом выполнения данного примера будет что-то подобное:

Пример использования imagecreatefrompng()

Примечания

Внимание

Версии PHP для Windows до PHP 4.3.0 не поддерживают возможность использования удаленных файлов этой функцией даже в том случае, если включена опция allow_url_fopen.

Коментарии

Автор:
If you're trying to load a translucent png-24 image but are finding an absence of transparency (like it's black), you need to enable alpha channel AND save the setting. I'm new to GD and it took me almost two hours to figure this out.

<?php
$imgPng 
imageCreateFromPng($strImagePath);
imageAlphaBlending($imgPngtrue);
imageSaveAlpha($imgPngtrue);

/* Output image to browser */
header("Content-type: image/png");
imagePng($imgPng); 
?>
2004-06-07 07:14:13
http://php5.kiev.ua/manual/ru/function.imagecreatefrompng.html
I was having a terrible time with the imagecreatefrompng function as it was working perfectly for one image and not at all for another.  After many hours of frustration, I discovered that the problem was the image size (number of pixels).  It appears that the maximum number of pixels this function will process is 1,040,000.  So, be sure that the pixel resolution of the image (eg. 1040 x 1000) does not exceed this value.
2006-07-05 17:49:23
http://php5.kiev.ua/manual/ru/function.imagecreatefrompng.html
I had the same problem as jboyd1189 at yahoo dot com but I solve d it allocating more memory dynamically.

Usually the memory_limit var on php.ini is set to 8M. Unfortunately, the required amount of memory to manage a PNG image about 1000x1000 could be bigger !

The approach I used to solve the problem is:

1-Calculate the memory required by the image
2-Set the new memory_limit value 
3-Create the PNG image and thumbnail
4-Restore the original value

1-The following value works for me:
$required_memory = Round($width * $height * $size['bits']);

Note that for JPEG the requirements are not the same:
http://es2.php.net/manual/en/function.imagecreatefromjpeg.php#60241

2-Use somthing like: 
$new_limit=memory_get_usage() + $required_memory;
ini_set("memory_limit", $new_limit);

4-ini_restore ("memory_limit");
2007-02-28 14:23:27
http://php5.kiev.ua/manual/ru/function.imagecreatefrompng.html
When using imagecreatepng with alpha blending you will lose the blending.

To over come this use something like the following
<?php
$dstimage
=imagecreatetruecolor($width,$height);
$srcimage=imagecreatefrompng($src);
imagecopyresampled($dstimage,$srcimage,0,0,0,0$width,$height,$width,$height);
?>
Where $width and $height are the width and height of the $src image.

This will create a true colour image then copy the png image to this true colour image and retain alpha blending.
2009-04-17 18:06:02
http://php5.kiev.ua/manual/ru/function.imagecreatefrompng.html
Автор:
The image size (width x height) should not exceed INT_MAX ... It's still thrue on a 64 bits computer.
2015-10-14 02:00:46
http://php5.kiev.ua/manual/ru/function.imagecreatefrompng.html
I have this code: 

if (exif_imagetype($this->img_name) == IMAGETYPE_PNG) {
                try {
                   
                    $this->image = imagecreatefrompng($this->img_name);
                    Error::log('It is a png: '.$this->img_name);
                } catch (Exception $e) {
                    echo "The image file has some strange charachters. Probably not a png image?";
                    $this->image = '';
                    $this->img_name = '';
                }
            }

And I get this error in the error.log: 
PHP Unknown error:  imagecreatefrompng(): gd-png: fatal libpng error: Extra compressed data\n in Unknown on line 0

The file that I try to open is a generated .png image which I can open from gimp and Geeqie. 

What is the problem? Could you please help me?
2017-10-17 19:45:12
http://php5.kiev.ua/manual/ru/function.imagecreatefrompng.html
Because gd and imagick do not support animated PNG (at this moment), i wrote a simple function to determine if given PNG is APNG or not. It does not validate PNG, only checks whenever "acTL" chunk appears before "IDAT" like the specification says: https://wiki.mozilla.org/APNG_Specification

<?php

function is_apng(string $filename): bool
{
   
$f = new \SplFileObject($filename'rb');
   
$header $f->fread(8);
    if (
$header !== "\x89PNG\r\n\x1A\n") {
        return 
false;
    }
    while (!
$f->eof()) {
       
$bytes $f->fread(4);
        if (
strlen($bytes) < 4) {
            return 
false;
        }
       
$length unpack('N'$bytes)[1];
       
$chunkname $f->fread(4);
        switch (
$chunkname) {
            case 
'acTL':
                return 
true;
            case 
'IDAT':
                return 
false;
        }
       
$f->fseek($length 4SEEK_CUR);
    }
    return 
false;
}

?>
2021-08-02 10:58:26
http://php5.kiev.ua/manual/ru/function.imagecreatefrompng.html

    Поддержать сайт на родительском проекте КГБ