GD and Image 函数
在线手册:中文  英文

imagecreatefrompng

(PHP 4, PHP 5)

imagecreatefrompng由文件或 URL 创建一个新图象。

说明

resource imagecreatefrompng ( string $filename )

imagecreatefrompng() 返回一图像标识符,代表了从给定的文件名取得的图像。

Tip

如已启用fopen 包装器,在此函数中, URL 可作为文件名。关于如何指定文件名详见 fopen()。各种 wapper 的不同功能请参见 支持的协议和封装协议,注意其用法及其可提供的预定义变量。

参数

filename

PNG 图像的路径。

返回值

成功后返回图象资源,失败后返回 FALSE

范例

Example #1 处理创建 PNG 过程中的错误

<?php
function LoadPNG($imgname)
{
    
/* Attempt to open */
    
$im = @imagecreatefrompng($imgname);

    
/* See if it failed */
    
if(!$im)
    {
        
/* Create a blank image */
        
$im  imagecreatetruecolor(15030);
        
$bgc imagecolorallocate($im255255255);
        
$tc  imagecolorallocate($im000);

        
imagefilledrectangle($im0015030$bgc);

        
/* Output an error message */
        
imagestring($im155'Error loading ' $imgname$tc);
    }

    return 
$im;
}

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

$img LoadPNG('bogus.image');

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

以上例程的输出类似于:

imagecreatefrompng() 例子

注释

Warning

Windows 版本的 PHP 在 4.3.0 版之前不支持通过此函数访问远程文件,即使已经启用 allow_url_fopen.


GD and Image 函数
在线手册:中文  英文

用户评论:

eneroth3 (2013-01-08 12:41:27)

It seems like the colors gets distorted when using certain bit depths. I get strange blue and black colors when trying to open an 8 bit image while 32 bits works perfectly

flood at itnews-bg dot com (2010-09-29 15:58:03)

Hey,

I just want to add for those of you who're having problem creating thumbs from png files - when you're using the "imagepng()" function put it in a variable. If you don't put it you'll probably be wondering why you're page will offer you to download itself rather than resizing it.

Example:

<?php
    
public function resizeFile($fileInfo)
    {
        
$image $fileInfo['name'];
        
$uploadedfile $fileInfo['full'];

        if (
$image) {

            
$filename stripslashes($fileInfo['name']);
            
$extension $fileInfo['ext'];
            
$extension strtolower($extension);

            
$size filesize($fileInfo['full']);

            if (
$size $this->maxSize 1024) {
                die(
'You have exceeded the size limit!');
            }

            
$uploadedfile $fileInfo['full'];
            
$src imagecreatefromstring($uploadedfile);

            list(
$width$height) = getimagesize($uploadedfile);

            
$newwidth 130;
            
$newheight = ($height $width) * $newwidth;
            
$tmp imagecreatetruecolor($newwidth$newheight);

            
imagecopyresampled($tmp$src0000$newwidth$newheight$width$height);

            
$filenameThumb "images/thumbs/" $fileInfo['name'];

            if(
$extension == ("jpg" || "jpeg"))
                
imagejpeg($tmp$filenameThumb100);
            else if(
$extension == "png")
                
// Disallow png display - this will create an image but won't display it!
                
$tmpPng imagePNG($tmp$filenameThumb100);
            else
                
imagegif($tmp$filenameThumb100);

            
imagedestroy($src);
            
imagedestroy($tmp);
        }
        else
        {
            die(
"Fatal error.");
        }
    }
?>

admin at wdfa dot co dot uk (2009-04-17 15:06:02)

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.

CPHaxer (2009-04-05 09:23:29)

This PHP-Script checks a Picture of a Sky and tells you how Cloudy it is.
The best thing is, if you enter the Path to a Webcam Picture, which is often updated and where its Webcam is showing [ONLY] the Sky.
BTW: At the Blue_Color Array you can enter the RGB-Values of a Pixel of your Sky. Its optional, but if you enter it, the Analisations will be more prectise.
The Percession Variable controls which Pixels get scanned.
If you have large Pictures, enter a high Number there.
http://pastebin.com/f582d5286
PS: Sorry I need to give you Pastebin Link. The Note is to big else :s

luxian.m [at] gmail [dot] com (2008-09-16 05:36:57)

Don't forget about imagealphablending() and imagesavealpha() if you're working with [semi]transparent png.

<?php
$file 
'semitransparent.png'// path to png image
$img imagecreatefrompng($file); // open image
imagealphablending($imgtrue); // setting alpha blending on
imagesavealpha($imgtrue); // save alphablending setting (important)
?>

anders jenbo pc dk (2007-10-05 04:44:18)

Some testing shows that i am able to load images that are 0.8Mpixels with a 8MB memory limit.

anders jenbo pc dk (2007-10-04 07:47:30)

This function seams to take up twise the memory when running then the final alocated size.
Memory limit is set to 8M but i get and error saying it tryed to alocate 2288640 and a memory check just befor the function runs sayes that it it at 3106120 witch is only 5.1M, if i change the order of the program and load the png befor the additional 3M is used i have no issues.

marcos at assl-site dot net (2007-02-28 12:23:27)

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");

dane.tschi _AT_ NOSPAM gmx [dot] at (2006-11-11 10:46:11)

I had a problem with PNG files.
My source files were PNG-8 files and i wanted to add some drawings to the Image with alpha blending, but it was not possible only by doing imagecolorallocatealpha() and imagefilledellipse() for example.
I noticed that it was only working for PNG-24 images, but i don't want to use them, because they are to big for my website, but PNG-8 files would be much greater.
My result is that the image has to be converted to PNG-24 after loading and converted back to PNG-8 before saving/output.
This is the script:

<?php
    
// Load Image and get it's size
    
$size getimagesize("png8image.png");
    
$im imagecreatefrompng("png8image.png");

    
// Convert the Image to PNG-24
    
$im_tc imagecreatetruecolor($size[0],$size[1]);
    
imagecopy($im_tc,$im,0,0,0,0,$size[0],$size[1]);
    
imagedestroy($im);
    
    
//Now do what ever you want, all alpha-operation do work
    
$color imagecolorallocatealpha ($im_tc,255,255,255,75);
    
imagefilledellipse ($im_tc,10,10,6,4,$color);

    
//And now convert it back to PNG-8
    
$im_result imagecreate($size[0],$size[1]);
    
imagecopy($im_result,$im_tc,0,0,0,0,$size[0],$size[1]);
    
imagedestroy($im_tc);
    
    
//And save it
    
imagepng($im_result,"png8image.png");    
?>

jboyd1189 at yahoo dot com (2006-07-05 14:49:23)

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.

alext82 at hotmail dot com (2006-05-31 05:54:33)

I was having trouble with
$black = imagecolorallocate($im, 0, 0, 0);
, as it would always display grey letters.
this solved it however:
$black = imagecolorresolve($im, 0, 0, 0);
this regarding this function.
imagettftext($im, 11, 7, 55, 60, $black, $font, $string);
I hope this helps.

hendrikjan dot vanmeerveld at gmail dot com (2006-05-01 03:23:10)

Another usefull note for those using ImageCreateFromPng:
PHP and GD do not recognize grayscale/alpha images.
So if you use grayscale images with transparency between 0% and 100%, then save the image as RGB.
At least this is true for PHP Version 4.4.2-1 and in 5.1.2-1 with pictures made with GIMP 2.2.8.

ketay [AT] comcast [DOT] net (2005-09-05 00:33:18)

A correction... If you are to set it to FALSE, then not only does it add the transparency to wherever you put it, but it takes the transparency out of the TTF files. Setting it to TRUE however, keeps your transparency both in your PNG file, and in any TTF text you make apply to the image.

rf at i---i dot org (2004-11-02 03:47:08)

***CORRECTION*** to 07-Jun-2004 01:14
imageAlphaBlending must be false, NOT TRUE
$imgPng = imageCreateFromPng($strImagePath);
imageAlphaBlending($imgPng, false); <<<FALSE
imageSaveAlpha($imgPng, true);

(2004-06-07 04:14:13)

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); 
?>

csaba at alum dot mit dot edu (2004-05-31 22:57:48)

This is a another case of someone (IE) thinking they know better than you what you want.  If you are of a mind to generate a complicated (read takes a long time) image incrementally, you might do it by having an IFRAME which calls to the image generating PHP script.  That munches for a bit, saves the file, returns to the client (remembering we're in the iframe so the user doesn't see all this) (with appropriate state information in <input type=hidden ...> fields) which kicks off an <body onLoad='docInit()' ...> whose purpose is to set the src attribute of the png image to the saved file (so the user sees the changes), and then resubmit the iframe (the image isn't in the iframe so the iframe can be hidden) to repeat the process.  Very nifty.

However, IE 6 has decided that it is far better to use a cached version of an image even on a local machine, where it can readily see that it changed, rather than to go to the source.  And, since it's a file, you can't so easily set headers on it.  This means that your incremental updates may not show any updates.

I solved this by (1) having Apache rewrite every .png request to a single .php file:
RewriteRule ^(.*).png$ pngPassThru.php?file=$1.png [QSA,L,NC]

(2) All pngPassThru.php does is to return the .png file with "don't cache me" headers.  Avoid leading/trailing spaces in pngPassThru.php.  The headers might be simplified - I've collected them from various sources and am not sure which ones could be eliminated.  But this is working for me on IE 6:
<?php
header
("Content-type: image/png");
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Last-Modified: " gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0"false);
header("Pragma: no-cache");
$file=@$_GET['file'];
$sizefilesize($file); 
header("Content-Length: $size bytes"); 
readfile($file);
?>

Csaba Gabor

aniakovas at yahoo dot co dot uk (2004-04-27 06:13:20)

Hey guys,
It has been my experience that the image type of a png file is best set to:-
image/x-png
This may be a peculiarity of the server I'm working on, which is running Apache/FreeBSD
Ania

polak_sg at hotmail dot com (2002-11-05 07:02:30)

don't forget to write the header into your function file!!
header ("Content-type: image/png");

wyvern at greywyvern.com (2002-10-05 08:45:03)

Make sure when coding image serving scripts that you avoid using the full "http://" URL of the image whenever possible. Use "../imagename" etc.
Loading URL's from your own site will double your used bandwidth, as the script grabbing the image will count against it as well as sending it to the browser.

robross at comcast dot net (2002-02-26 16:47:32)

This color table issue is actually a bit more complicated.
From my testing, it would appear that whatever colors you have specified in the color table for your picture in the first nth number of spots, those colors will automatically be given to the first "n" colors you attempt to use in your CreateImagefromPNG.
So, for example, if you need to create dynamic black and red text in your image, the first three spots in the color table for your background image should be white, black and red (in this order).
This can be a pain, but it is the only way to ensure that your images look as intended in all browsers.

netfiend at mediaone dot net (2001-05-23 16:04:55)

I've noticed a couple of things with the ImageCreateFromPng function that may be useful if your having problems.
1st thing I noticed is that the PNG file you are creating from needs to be indexed and less than 256 colors.
Secondly, you need to reduce the color depth by 1 for each color you plan on generating in php... I.E. if you plan on drawing 50 different colors on the screen with php you need to allocate space for them by reducing the origional image's color depth to 205 colors (I was pulling my hair out on this one for a while because the wrong colors were showing up in the output).
Also, if you are saving the image as a PNG you need to allocate the 1st color as white.. The reason for this is that Internet Explorer seems to interpret the first color in an indexed PNG as white no matter what color it is... (Figured this out when all my pretty black text was turning up as white in I.E. and was normal in Netscape; allocated the first color in the image as white and the problem went away.)
-- hope this helps.

易百教程