imagecreatefrompng
(PHP 4, PHP 5)
imagecreatefrompng — Create a new image from file or URL
Описание
imagecreatefrompng() returns an image identifier representing the image obtained from the given filename.
imagecreatefrompng() returns an empty string on failure. It also outputs an error message, which unfortunately displays as a broken link in a browser. To ease debugging the following example will produce an error PNG:
Пример #1 Example to handle an error during creation
<?php
function LoadPNG($imgname)
{
$im = @imagecreatefrompng($imgname); /* Attempt to open */
if (!$im) { /* See if it failed */
$im = imagecreatetruecolor(150, 30); /* Create a blank image */
$bgc = imagecolorallocate($im, 255, 255, 255);
$tc = imagecolorallocate($im, 0, 0, 0);
imagefilledrectangle($im, 0, 0, 150, 30, $bgc);
/* Output an errmsg */
imagestring($im, 1, 5, 5, "Error loading $imgname", $tc);
}
return $im;
}
header("Content-Type: image/png");
$img = LoadPNG("bogus.image");
imagepng($img);
?>
Результатом выполнения данного примера будет что-то подобное:
Для этой функции вы можете использовать URL в качестве имени файла, если была включена опция "fopen wrappers". Смотрите более подробную информацию об определении имени файла в описании функции fopen(), а также список поддерживаемых протоколов URL в List of Supported Protocols/Wrappers.
Список параметров
- filename
-
Path to the PNG image
Возвращаемые значения
Returns an image resource identifier on success, FALSE on errors.
Примечания
Версии PHP для Windows до PHP 4.3.0 не поддерживают возможность использования удаленных файлов этой функцией даже в том случае, если опция allow_url_fopen включена.
- PHP Руководство
- Функции по категориям
- Индекс функций
- Справочник функций
- Обработка и генерация изображений
- Обработка изображений и GD
- gd_info
- getimagesize
- getimagesizefromstring
- image_type_to_extension
- image_type_to_mime_type
- image2wbmp
- imageaffine
- imageaffinematrixconcat
- imageaffinematrixget
- imagealphablending
- imageantialias
- imagearc
- imagechar
- imagecharup
- imagecolorallocate
- imagecolorallocatealpha
- imagecolorat
- imagecolorclosest
- imagecolorclosestalpha
- imagecolorclosesthwb
- imagecolordeallocate
- imagecolorexact
- imagecolorexactalpha
- imagecolormatch
- imagecolorresolve
- imagecolorresolvealpha
- imagecolorset
- imagecolorsforindex
- imagecolorstotal
- imagecolortransparent
- imageconvolution
- imagecopy
- imagecopymerge
- imagecopymergegray
- imagecopyresampled
- imagecopyresized
- imagecreate
- imagecreatefromgd2
- imagecreatefromgd2part
- imagecreatefromgd
- imagecreatefromgif
- imagecreatefromjpeg
- imagecreatefrompng
- imagecreatefromstring
- imagecreatefromwbmp
- imagecreatefromwebp
- imagecreatefromxbm
- imagecreatefromxpm
- imagecreatetruecolor
- imagecrop
- imagecropauto
- imagedashedline
- imagedestroy
- imageellipse
- imagefill
- imagefilledarc
- imagefilledellipse
- imagefilledpolygon
- imagefilledrectangle
- imagefilltoborder
- imagefilter
- imageflip
- imagefontheight
- imagefontwidth
- imageftbbox
- imagefttext
- imagegammacorrect
- imagegd2
- imagegd
- imagegif
- imagegrabscreen
- imagegrabwindow
- imageinterlace
- imageistruecolor
- imagejpeg
- imagelayereffect
- imageline
- imageloadfont
- imagepalettecopy
- imagepalettetotruecolor
- imagepng
- imagepolygon
- imagepsbbox
- imagepsencodefont
- imagepsextendfont
- imagepsfreefont
- imagepsloadfont
- imagepsslantfont
- imagepstext
- imagerectangle
- imagerotate
- imagesavealpha
- imagescale
- imagesetbrush
- imagesetinterpolation
- imagesetpixel
- imagesetstyle
- imagesetthickness
- imagesettile
- imagestring
- imagestringup
- imagesx
- imagesy
- imagetruecolortopalette
- imagettfbbox
- imagettftext
- imagetypes
- imagewbmp
- imagewebp
- imagexbm
- iptcembed
- iptcparse
- jpeg2wbmp
- png2wbmp
Коментарии
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($imgPng, true);
imageSaveAlpha($imgPng, true);
/* Output image to browser */
header("Content-type: image/png");
imagePng($imgPng);
?>
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");
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.
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 + 4, SEEK_CUR);
}
return false;
}
?>