In case your script is using output-buffering-functions somewhere, then you have to clear the buffer first ( with ob_clear() ), before outputting an image with a function like imagepng().
And you should make sure that no buffer will get send after outputing an image by using the ob_end_flush()-function.
Furthermore you should check if a buffer has already been flushed somewhere before. This can be done using the headers_sent()-function.
Here is the full solution:
<?php
if(headers_sent()){
die('Headers have been send somewhere within my script');
}
ob_clean(); //Clears the buffer
header('Content-type: image/png');
imagepng($img, NULL, 0, NULL);
ob_end_flush(); //Now we send the header and image plus we make sure that nothing will get send from now on (including possible shutdown-functions and __destruct()-methods) till the end of page-execution
?>
画像処理 (GD)
- 導入
- インストール/設定
- 定義済み定数
- 例
- GD および Image 関数
- gd_info — 現在インストールされているGDライブラリに関する情報を取得する
- getimagesize — 画像の大きさを取得する
- image_type_to_extension — 画像形式からファイルの拡張子を取得する
- image_type_to_mime_type — getimagesize, exif_read_data, exif_thumbnail, exif_imagetypeから返される 画像形式のMIMEタイプを取得する
- image2wbmp — 画像をブラウザあるいはファイルに出力する
- imagealphablending — イメージのブレンドモードを設定する
- imageantialias — アンチエイリアス機能を使用すべきかどうかを判断する
- imagearc — 部分楕円を描画する
- imagechar — 水平に文字を描画する
- imagecharup — 垂直に文字を描画する
- imagecolorallocate — 画像で使用する色を作成する
- imagecolorallocatealpha — 画像で使用する色を透過度を指定して作成する
- imagecolorat — ピクセルの色のインデックスを取得する
- imagecolorclosest — 指定した色に最も近い色のインデックスを取得する
- imagecolorclosestalpha — 指定した色+アルファ値に最も近い色のインデックスを取得する
- imagecolorclosesthwb — 色合い、白、黒を有する色のインデックスを得る
- imagecolordeallocate — イメージの色リソースを開放する
- imagecolorexact — 指定した色のインデックスを取得する
- imagecolorexactalpha — 指定した色+アルファ値のインデックスを取得する
- imagecolormatch — パレットイメージの色を True カラーイメージに近づける
- imagecolorresolve — 指定した色または出来るだけ近い色のインデックスを得る
- imagecolorresolvealpha — 指定した色+アルファ値または最も近い色のインデックスを取得する
- imagecolorset — 指定したパレットインデックスの色を設定する
- imagecolorsforindex — カラーインデックスからカラーを取得する
- imagecolorstotal — 画像パレットの色数を検出する
- imagecolortransparent — 透明色を定義する
- imageconvolution — div および offset の係数を使用し、3x3 の畳み込み配列を適用する
- imagecopy — 画像の一部をコピーする
- imagecopymerge — イメージの一部をコピー、マージする
- imagecopymergegray — グレースケールでイメージの一部をコピー、マージする
- imagecopyresampled — 再サンプリングを行いイメージの一部をコピー、伸縮する
- imagecopyresized — 画像の一部をコピーしサイズを変更する
- imagecreate — パレットを使用する新規画像を作成する
- imagecreatefromgd2 — GD2 ファイルまたは URL から新規イメージを生成する
- imagecreatefromgd2part — GD2 ファイルまたは URL の指定した部分から新規イメージを生成する
- imagecreatefromgd — GD ファイルまたは URL から新規イメージを生成する
- imagecreatefromgif — 新しい画像をファイルあるいは URL から作成する
- imagecreatefromjpeg — 新しい画像をファイルあるいは URL から作成する
- imagecreatefrompng — 新しい画像をファイルあるいは URL から作成する
- imagecreatefromstring — 文字列の中のイメージストリームから新規イメージを作成する
- imagecreatefromwbmp — 新しい画像をファイルあるいは URL から作成する
- imagecreatefromxbm — 新しい画像をファイルあるいは URL から作成する
- imagecreatefromxpm — 新しい画像をファイルあるいは URL から作成する
- imagecreatetruecolor — TrueColor イメージを新規に作成する
- imagedashedline — 破線を描画する
- imagedestroy — 画像を破棄する
- imageellipse — 楕円を描画する
- imagefill — 塗り潰す
- imagefilledarc — 楕円弧を描画し、塗りつぶす
- imagefilledellipse — 塗りつぶされた楕円を描画する
- imagefilledpolygon — 塗りつぶした多角形を描画する
- imagefilledrectangle — 塗りつぶした矩形を描画する
- imagefilltoborder — 特定色で塗りつぶす
- imagefilter — 画像にフィルタを適用する
- imagefontheight — フォントの高さを取得する
- imagefontwidth — フォントの幅を取得する
- imageftbbox — freetype2 によるフォントを用いたテキストを囲む箱を取得する
- imagefttext — FreeType 2 によるフォントを用いてイメージにテキストを描画する
- imagegammacorrect — GD イメージにガンマ補正を適用する
- imagegd2 — GD2 イメージをブラウザまたはファイルに出力する
- imagegd — GD イメージをブラウザまたはファイルに出力する
- imagegif — 画像をブラウザあるいはファイルに出力する
- imagegrabscreen — 画面全体をキャプチャする
- imagegrabwindow — ウィンドウをキャプチャする
- imageinterlace — インターレースを有効もしくは無効にする
- imageistruecolor — 画像が truecolor かどうか調べる
- imagejpeg — 画像をブラウザあるいはファイルに出力する
- imagelayereffect — アルファブレンディングフラグを設定し、 libgd にバンドルされているレイヤ効果を使用する
- imageline — 直線を描画する
- imageloadfont — 新しいフォントを読み込む
- imagepalettecopy — あるイメージから他のイメージにパレットをコピーする
- imagepng — PNG イメージをブラウザまたはファイルに出力する
- imagepolygon — 多角形を描画する
- imagepsbbox — PostScript Type1 フォントを用いてテキスト矩形のバウンディングボックスを指定する
- imagepsencodefont — フォントの文字エンコードベクトルを変更する
- imagepsextendfont — フォントを展開または圧縮する
- imagepsfreefont — PostScript Type 1 フォント用メモリを解放する
- imagepsloadfont — ファイルから PostScript Type 1 フォントをロードする
- imagepsslantfont — フォントを傾ける
- imagepstext — PostScript Type1 フォントを用いて画像の上に文字列を描く
- imagerectangle — 矩形を描画する
- imagerotate — 指定された角度で画像を回転する
- imagesavealpha — PNG 画像を保存する際に(単一色の透過設定ではない)完全な アルファチャネル情報を保存するフラグを設定する
- imagesetbrush — 線の描画用にブラシイメージを設定する
- imagesetpixel — 点を生成する
- imagesetstyle — 線描画用のスタイルを設定する
- imagesetthickness — 線描画用の線幅を設定する
- imagesettile — 塗りつぶし用のイメージを設定する
- imagestring — 文字列を水平に描画する
- imagestringup — 文字列を垂直に描画する
- imagesx — 画像の幅を取得する
- imagesy — 画像の高さを取得する
- imagetruecolortopalette — TrueColor イメージをパレットイメージに変換する
- imagettfbbox — TypeType フォントを使用したテキストの bounding box を生成する
- imagettftext — TrueType フォントを使用してテキストを画像に書き込む
- imagetypes — この PHP がサポートしている画像形式を返す
- imagewbmp — 画像をブラウザあるいはファイルに出力する
- imagexbm — XBM 画像をブラウザあるいはファイルに出力する
- iptcembed — バイナリ IPTC データを JPEG イメージに埋めこむ
- iptcparse — バイナリの IPTC ブロックのタグをパースする
- jpeg2wbmp — JPEG イメージファイルから WBMP イメージファイルに変換する
- png2wbmp — PNG イメージファイルから WBMP イメージファイルに変換する
herbert dot walde at googlemail dot com
04-Jan-2012 08:41
donatj at gmail dot com
12-Jul-2011 10:43
UTF-8 is fine with GD - as well as any other Unicode transformation format - you just need to ensure your saved file doesn't contain the dreaded byte order mark.
kurdtpage at gmail dot com
28-Apr-2011 07:53
When using GD, please make sure of the following things:
1. The file that is used to manipulate images is saved as ANSI format and not UTF-8
2. There is no space in front of the opening tag <?php
mac_doggie at hotmail dot com
28-May-2010 04:50
A way to read the color of a pixel:
<?php
$img = imagecreatefrompng("image1.png");
$w = imagesx($img);
$h = imagesy($img);
for($y=0;$y<$h;$y++) {
for($x=0;$x<$w;$x++) {
$rgb = imagecolorat($img, $x, $y);
$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> 8) & 0xFF;
$b = $rgb & 0xFF;
echo "#".str_repeat("0",2-strlen(dechex($r))).dechex($r).
str_repeat("0",2-strlen(dechex($g))).dechex($g).
str_repeat("0",2-strlen(dechex($b))).dechex($b).",";
}
echo "<br />\r\n";
}
?>
[EDIT BY thiago: merged two notes from same submitter.]
rmayo100 at yahoo dot com
18-May-2010 05:05
I use GD to create graphs of data that exists in my system. I use a link like this to place the graph image on my page:
<img src="image.php" name="Image">
And this works just fine. Image.php acquires the data to be graphed and creates a png image with it. (And is even able to do it very quickly.)
However, I would also like to have external access that data. Unfortunately, it's is acquired by the graphing function from a UDP broadcast stream and I have no idea how to make it available outside that file (or how to capture it twice, perhaps).
I've had exactly no luck trying to implement a global variable, I suspect, because global variables really aren't global and their scope doesn't span multiple files.
I don't know if this is the right venue for this post, but I'm stumped so far and I had to post it somewhere.
Thanks,
R.
mail at ecross dot nl
03-Apr-2010 04:31
hello there,
i made a function to create a gradient image.
description:
gradient(int image_width, int image_height,
int start_red, int start_green, int start_blue,
int end_red, int end_green, int end_blue,
bool vertical)
function:
<?php
function gradient($image_width, $image_height,$c1_r, $c1_g, $c1_b, $c2_r, $c2_g, $c2_b, $vertical=false)
{
// first: lets type cast;
$image_width = (integer)$image_width;
$image_height = (integer)$image_height;
$c1_r = (integer)$c1_r;
$c1_g = (integer)$c1_g;
$c1_b = (integer)$c1_b;
$c2_r = (integer)$c2_r;
$c2_g = (integer)$c2_g;
$c2_b = (integer)$c2_b;
$vertical = (bool)$vertical;
// create a image
$image = imagecreatetruecolor($image_width, $image_height);
// make the gradient
for($i=0; $i<$image_height; $i++)
{
$color_r = floor($i * ($c2_r-$c1_r) / $image_height)+$c1_r;
$color_g = floor($i * ($c2_g-$c1_g) / $image_height)+$c1_g;
$color_b = floor($i * ($c2_b-$c1_b) / $image_height)+$c1_b;
$color = ImageColorAllocate($image, $color_r, $color_g, $color_b);
imageline($image, 0, $i, $image_width, $i, $color);
}
# Prints out all the figures and picture and frees memory
header('Content-type: image/png');
if($vertical){$image = imagerotate($image, 90, 0);}
ImagePNG($image);
imagedestroy($image);
}
?>
jordan at jkdesign dot org
08-Sep-2009 12:09
Building on Ashley's example, here's an example of some code that grabs an existing image file and outputs an html img tag with the contents. I found it useful because I needed to not broadcast the filenames.
<?php
$file = 'images/01.png';
$image = imagecreatefrompng($file);
imagealphablending($image, false);
imagesavealpha($image, true);
// start buffering
ob_start();
imagepng($image);
$contents = ob_get_contents();
ob_end_clean();
echo "<img src='data:image/png;base64,".base64_encode($contents)."' />";
imagedestroy($image);
?>
scurvysquid at yahoo dot com
04-May-2009 09:08
to address Thomas' note about exif data, exif is only valid for .tiff and .jpg files. As always, it's up to the individual to make the call but I personally would prefer to create an abstraction layer to work for all images, and relying on exif data means you need to limit your allowed image types. I've heard some great things about the GD library and found them to all be true in my own use of it, losing the nominally useful data specific to jpegs and pngs is not a sufficient reason alone to convince me to use imagemagick instead.
Thomas
10-Dec-2008 11:05
You know, maybe this goes without saying, but I thought I would drop a note in here. When developing code to resize images, it is best not to use GD. When using the current GD methodologies, you are reading content from an image and manipulating it. By then writing that content to a brand new file, you are losing the EXIF data.
For purposes when you want to retain EXIF data, it is recommended that you compile in and use the PECL Imagick extension. It has great resizing methods built right in and the EXIF data is retained.
code at ashleyhunt dot co dot uk
24-Oct-2008 03:02
I have been looking to send the output from GD to a text string without proxying via a file or to a browser.
I have come up with a solution.
This code buffers the output between the ob_start() and ob_end() functions into ob_get_contents()
See the example below
<?php
// Create a test source image for this example
$im = imagecreatetruecolor(300, 50);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5, 'A Simple Text String', $text_color);
// start buffering
ob_start();
// output jpeg (or any other chosen) format & quality
imagejpeg($im, NULL, 85);
// capture output to string
$contents = ob_get_contents();
// end capture
ob_end_clean();
// be tidy; free up memory
imagedestroy($im);
// lastly (for the example) we are writing the string to a file
$fh = fopen("./temp/img.jpg", "a+" );
fwrite( $fh, $contents );
fclose( $fh );
?>
Enjoy!
Ashley
