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
?>
Resim İşleme ve GD
- Giriş
- Yapılandırma/Kurulum
- Öntanımlı Sabitler
- Örnekler
- GD ve Resim İşlevleri
- gd_info — Kurulu GD kütüphanesi hakkında bilgi verir
- getimagesize — Bir resmin boyutlarını döndürür
- getimagesizefromstring — Get the size of an image from a string
- image_type_to_extension — Resim türü ile ilgili dosya uzantısını döndürür
- image_type_to_mime_type — getimagesize, exif_read_data, exif_thumbnail, exif_imagetype ile döndürülen resim türü ile ilgili MIME türünü döndürür
- image2wbmp — Bir dosyaya veya tarayıcıya bir WBMP resmi çıktılar
- imagealphablending — Bir resim için harmanlama kipini etkinleştirir
- imageantialias — Kenar yumuşatma işlevlerini uygulatır
- imagearc — Bir yay çizer
- imagechar — Yatay olarak bir karakter çizer
- imagecharup — Düşey olarak bir karakter çizer
- imagecolorallocate — Bir resim için bir renk ayırır
- imagecolorallocatealpha — Bir resim için alfa kanallı bir renk ayırır
- imagecolorat — Bir pikselin renk indisini döndürür
- imagecolorclosest — Belirtilen rengin en yakın benzerinin indisini döndürür
- imagecolorclosestalpha — Alfası ile birlikte belirtilen rengin en yakın benzerinin renk indisini verir
- imagecolorclosesthwb — En yakın renk sıcaklığına, beyaz ve siyahlığa sahip renk indisini verir
- imagecolordeallocate — Bir rengi tanımsız yapar
- imagecolorexact — Belirtilen rengin indisini döndürür
- imagecolorexactalpha — Alfası ile birlikte belirtilen rengin indisini verir
- imagecolormatch — Bir resmin paletli sürümünün renklerini gerçek renkli sürümünün renkleriyle aynı yapar
- imagecolorresolve — Belirtilen rengin veya en yakın benzerinin indisini döndürür
- imagecolorresolvealpha — Alfası ile birlikte belirtilen rengin veya en yakın benzerinin renk indisini verir
- imagecolorset — Bir palet indisi için renk tanımlar
- imagecolorsforindex — Bir renk indisinin renk bilgisini döndürür
- imagecolorstotal — Bir resim paletindeki renk sayısını döndürür
- imagecolortransparent — Bir rengi şeffaflaştırır
- imageconvolution — Bir konum ve katsayı ile 3x3'lük bir evrişim matrisini uygular
- imagecopy — Bir resim parçasını kopyalar
- imagecopymerge — Bir resmi kopyalar ve karıştırır
- imagecopymergegray — Bir resmi kopyalar ve gri tonlama ile karıştırır
- imagecopyresampled — Resmin bir parçasını örnekleyerek kopyalar ve boyutlandırır
- imagecopyresized — Resmin bir parçasını kopyalar ve boyutlandırır
- imagecreate — Yeni bir paletli resim oluşturur
- imagecreatefromgd2 — Bir GD2 dosyasından veya URL'sinden yeni bir resim oluşturur
- imagecreatefromgd2part — Bir GD2 parça dosyasından veya URL'sinden yeni bir resim oluşturur
- imagecreatefromgd — Bir GD dosyasından veya URL'sinden yeni bir resim oluşturur
- imagecreatefromgif — Bir GIF dosyasından veya URL'sinden yeni bir resim oluşturur
- imagecreatefromjpeg — Bir JPEG dosyasından veya URL'sinden yeni bir resim oluşturur
- imagecreatefrompng — Bir PNG dosyasından veya URL'sinden yeni bir resim oluşturur
- imagecreatefromstring — Belirtilen dizgeden yeni bir resim oluşturur
- imagecreatefromwbmp — Bir WBMP dosyasından veya URL'sinden yeni bir resim oluşturur
- imagecreatefromxbm — Bir XBM dosyasından veya URL'sinden yeni bir resim oluşturur
- imagecreatefromxpm — Bir XPM dosyasından veya URL'sinden yeni bir resim oluşturur
- imagecreatetruecolor — Yeni bir gerçek renkli resim oluşturur
- imagedashedline — Kesikli çizgi çizer
- imagedestroy — Bir resmi bellekten siler
- imageellipse — Bir elips çizer
- imagefill — Resmi boyar
- imagefilledarc — Bir yay çizer ve içini doldurur
- imagefilledellipse — İçi dolu bir elips çizer
- imagefilledpolygon — İçi dolu bir çokgen çizer
- imagefilledrectangle — İçi dolu bir dikdörtgen çizer
- imagefilltoborder — Belli bir bölgeyi belli bir renge boyar
- imagefilter — Bir resme bir süzgeç uygular
- imagefontheight — Yazı tipi yüksekliğini döndürür
- imagefontwidth — Yazı tipi genişliğini döndürür
- imageftbbox — Bir FreeType2 yazı tipi ile yazılacak bir metnin çerçevesini hesaplar
- imagefttext — Bir metni bir resme bir FreeType 2 yazı tipini kullanarak yazar
- imagegammacorrect — Bir GD resmine gamma düzeltmesi uygular
- imagegd2 — Tarayıcıya veya bir dosyaya bir GD2 resmi çıktılar
- imagegd — Tarayıcıya veya bir dosyaya bir GD resmi çıktılar
- imagegif — Bir dosyaya veya tarayıcıya bir GIF resmi çıktılar
- imagegrabscreen — Ekran görüntüsünü yakalar
- imagegrabwindow — Bir pencereyi yakalar
- imageinterlace — Geçişimliliği açıp kapar
- imageistruecolor — Bir resmin gerçek renkli olup olmadığını bulur
- imagejpeg — Tarayıcıya veya bir dosyaya bir JPEG resmi çıktılar
- imagelayereffect — PHP ile gelen libgd'nin katmanlama etkisini kullanmak için alfa harmanlama seçeneğini ayarlar
- imageline — Bir çizgi çizer
- imageloadfont — Yeni bir bit eşlemli yazı tipi yükler
- imagepalettecopy — Paleti bir resimden diğerine kopyalar
- imagepng — Tarayıcıya veya bir dosyaya bir PNG resmi çıktılar
- imagepolygon — Çokgen çizer
- imagepsbbox — Bir PostScript Type1 yazı tipi ile yazılan bir metnin çerçevesini döndürür
- imagepsencodefont — Bir yazı tipinin karakter kodlamasını değiştirir
- imagepsextendfont — Bir PS yazı tipini genişletir veya daraltır
- imagepsfreefont — Bir PostScript Type 1 yazı tipi tarafından kullanılan belleği serbest bırakır
- imagepsloadfont — Bir dosyadan bir PostScript Type 1 yazı tipi yükler
- imagepsslantfont — Bir yazı tipini eğer
- imagepstext — PostScript Type1 yazı tiplerini kullanarak bir resmin üzerine bir metin çizer
- imagerectangle — Bir dikdörtgen çizer
- imagerotate — Bir resmi belirtilen açıya göre döndürür
- imagesavealpha — PNG resimleri kaydederken (tek renkli şeffaflığın tersine) alfa kanalı bilgisinin kaydedilip kaydedilmeyeceğini belirtir
- imagesetbrush — Çizgi çizmek için fırça resmi oluşturur
- imagesetpixel — Bir pikselin rengini değiştirir
- imagesetstyle — Çizgi tarzını ayarlar
- imagesetthickness — Çizgi kalınlığını ayarlar
- imagesettile — Resmi doldurmak için döşemeyi etkin kılar
- imagestring — Bir dizgeyi yatay olarak yazar
- imagestringup — Bir dizgeyi 90 derece döndürülmüş olarak yazar
- imagesx — Resmin genişliğini döndürür
- imagesy — Resmin yüksekliğini döndürür
- imagetruecolortopalette — Bir gerçek renkli resmi bir paletli resme dönüştürür
- imagettfbbox — TrueType yazıtipi kullanılan bir metnin çerçevesini döndürür
- imagettftext — Metni resme TrueType yazı tipi ile yazar
- imagetypes — Kurulu PHP'nin desteklediği resim türlerini döndürür
- imagewbmp — Resmi bir dosyaya veya tarayıcıya çıktılar
- imagexbm — Bir XBM resmini tarayıcıya veya dosyaya çıktılar
- iptcembed — İkil IPTC verisini bir JPEG resminin içine gömer
- iptcparse — Bir ikil IPTC bloğunu tekil etiketlere böler
- jpeg2wbmp — Bir JPEG dosyasını WBMP dosyasına dönüştürür
- png2wbmp — Bir PNG dosyasını WBMP dosyasına dönüştürür
herbert dot walde at googlemail dot com
04-Jan-2012 04:41
donatj at gmail dot com
12-Jul-2011 07: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
27-Apr-2011 04: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 01: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 02: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 01: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
07-Sep-2009 09: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 06: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 07: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
23-Oct-2008 12: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
