PHP Conference Japan 2024

imagesetpixel

(PHP 4, PHP 5, PHP 7, PHP 8)

imagesetpixelРисование точки

Описание

imagesetpixel(
    GdImage $image,
    int $x,
    int $y,
    int $color
): bool

imagesetpixel() рисует точку (пиксел) на заданных координатах.

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

image

Объект GdImage, который возвращает одна из функций, создающих изображения, например, imagecreatetruecolor().

x

x-координата.

y

y-координата.

color

Идентификатор цвета, созданный функцией imagecolorallocate().

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

Функция возвращает true в случае успешного выполнения или false, если возникла ошибка.

Список изменений

Версия Описание
8.0.0 Параметр image теперь ожидает экземпляр класса GdImage; раньше параметр ждал корректный gd-ресурс (resource).

Примеры

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

Рисование "случайных" точек, дающее в результате фрактальное изображение.

<?php

$x
= 200;
$y = 200;

$gd = imagecreatetruecolor($x, $y);

$corners[0] = array('x' => 100, 'y' => 10);
$corners[1] = array('x' => 0, 'y' => 190);
$corners[2] = array('x' => 200, 'y' => 190);

$red = imagecolorallocate($gd, 255, 0, 0);

for (
$i = 0; $i < 100000; $i++) {
imagesetpixel($gd, round($x), round($y), $red);
$a = rand(0, 2);
$x = ($x + $corners[$a]['x']) / 2;
$y = ($y + $corners[$a]['y']) / 2;
}

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

?>

Вывод приведённого примера будет похож на:

Вывод примера: imagesetpixel()

Смотрите также

Добавить

Примечания пользователей 24 notes

up
7
d [AT] sprid [DOT] de
19 years ago
This code does generate a RGB-cube (with or without borders). Because its only rendering the visible pixels its clearly fast (approx 1 up to 2 seconds). With changing the $order-variable you can see the cube from different perspectives. Entering double or tribble values (like rrg or ggg) will give you other specs of single channels. Send any sugestions to my email.

<?php
$borders
= true;
$order = 'rgb';

set_time_limit(0);
$img = imageCreateTrueColor(510, 510);

$bg = imageColorAllocate($img, 255, 255, 255);
$black = imageColorAllocate($img, 255, 255, 255);

for (
$r=0; $r<256; $r++) {
for (
$g=0; $g<256; $g++) {
for (
$b=0; $b<256; $b++) {
$rN = ${$order{0}};
$gN = ${$order{1}};
$bN = ${$order{2}};

$col = imageColorAllocate($img, $rN, $gN, $bN);
imagesetpixel($img, $b+($r*0.5)+(255/4), $g+($r*0.5)+(255/4), $col);
if (
$r < 255 && $g > 0) break;
}
}

if (
$borders) {
imagesetpixel($img, ($r*0.5+(255/4)), ($r*0.5)+(255/4), $black);
imagesetpixel($img, ($r*0.5)+255+(255/4), ($r*0.5)+(255/4), $black);
imagesetpixel($img, ($r*0.5)+(255/4), ($r*0.5)+255+(255/4), $black);
}
}

if (
$borders) {
imageline($img, 255/4, 255/4, 255+(255/4), 255/4, $black);
imageline($img, 255/4, 255/4, 255/4, 255+(255/4), $black);
imageline($img, 255*0.5+(255/4), 255*0.5+(255/4), 255*0.5+(255/4), 255*0.5 + 509*0.5+(255/4), $black);
imageline($img, 255*0.5+(255/4), 255*0.5+(255/4), 255*0.5 + 509*0.5+(255/4), 255*0.5+(255/4), $black);
imageline($img, 255*0.5+(255/4), 255*0.5 + 509*0.5+(255/4), 255*0.5 + 509*0.5+(255/4), 255*0.5 + 509*0.5+(255/4), $black);
imageline($img, 255*0.5 + 509*0.5+(255/4), 255*0.5+(255/4), 255*0.5 + 509*0.5+(255/4), 255*0.5 + 509*0.5+(255/4), $black);
}

header("Content-Type: image/png");
imagepng($img);
imagedestroy($img);
?>
up
6
guy032 at gmail dot com
12 years ago
making images with white (or close to white) background transprent

<?
function FloodFill($im, $x, $y)
{
$rgb = imagecolorat($im, $x, $y);
$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> 8) & 0xFF;
$b = $rgb & 0xFF;

$counter=0;
$counter2=0;
if($r >= 245){ $counter++;}
if($g >= 245){ $counter++;}
if($b >= 245){ $counter++;}
if($r >= 240){ $counter2++;}
if($g >= 240){ $counter2++;}
if($b >= 240){ $counter2++;}

if($counter >= 1 && $counter2 == 3){
$background = imagecolorallocate($im, 180, 0, 255);
imagesetpixel($im, $x, $y, $background);

FloodFill ($im, $x, $y+1);
FloodFill ($im, $x+1, $y);
FloodFill ($im, $x, $y-1);
}
}

$src = $_GET["src"];
$im = imagecreatefromjpeg($src);

// Draw border
$border = imagecolorallocate($im, 180, 0, 255);
drawBorder($im, $border, 1);

// Draw a border
function drawBorder($im, $color, $thickness = 1)
{
$x1 = 0;
$y1 = 0;
$x2 = ImageSX($im) - 1;
$y2 = ImageSY($im) - 1;

for($i = 0; $i < $thickness; $i++)
{
ImageRectangle($im, $x1++, $y1++, $x2--, $y2--, $color);
}
}

$rgb = imagecolorat($im, 0, 0);
FloodFill($im, 0, 0);
$color = imagecolorallocate($im, 180, 0, 255);
imagecolortransparent($im, $color);
header("Content-type: image/png");
imagepng($im);
imagedestroy($im);
?>
up
2
odin<spam inside(C)>dtdm.org
20 years ago
Just a simple implementation of the Bresenham algorythm (educational purpose....)

You can find more about this and many other tutorials for gfx there: http://brand107.home.comcast.net/pc-gpe/

<?php

/****************************************************
Bresenham Line Algorythm PHP/GD implementation
****************************************************/
function line($im,$x1,$y1,$x2,$y2,$color){

$deltax=abs($x2-$x1);
$deltay=abs($y2-$y1);

if (
$deltax>$deltay) {
$numpixels=$deltax+1;
$d=(2*$deltay)-$deltax;
$dinc1=$deltay << 1; $dinc2=($deltay-$deltax) << 1;
$xinc1=1; $xinc2=1;
$yinc1=0; $yinc2=1;
} else {
$numpixels=$deltay+1;
$d=(2*$deltax)-$deltay;
$dinc1=$deltax << 1; $dinc2=($deltax-$deltay)<<1;
$xinc1=0; $xinc2=1;
$yinc1=1; $yinc2=1;
}

if (
$x1>$x2) {
$xinc1=-$xinc1;
$xinc2=-$xinc2;
}

if (
$y1>$y2) {
$yinc1=-$yinc1;
$yinc2=-$yinc2;
}
$x=$x1;
$y=$y1;

for (
$i=0;$i<$numpixels;$i++) {
imagesetpixel($im,$x,$y,$color);
if (
$d<0) {
$d+=$dinc1;
$x+=$xinc1;
$y+=$yinc1;
} else {
$d+=$dinc2;
$x+=$xinc2;
$y+=$yinc2;
}
}
return ;
}

?>
up
1
mail AT kkapsner DOT de
14 years ago
It IS posible to "delete" pixels from an image in PHP natively - the key-function is imageAlphaBlending:
<?php

$image
= imageCreateTrueColor(101, 101);
imageSaveAlpha($image, true);

# draw a red cycle with alpha blending
$red = imageColorAllocateAlpha($image, 255, 0, 0, 30);
imageFilledEllipse($image, 50, 50, 100, 100, $red);

# disable alpha blending for deletion
imageAlphaBlending($image, false);

# paint with a complete opaque color
$trans = imageColorAllocateAlpha($image, 0, 0, 0, 127);

# you can clear every shape you like
imageFilledRectangle($image, 30, 30, 70, 70, $trans);

# enable alpha blending again
imageAlphaBlending($image, true);

# draw a green rectangle with alpha blending
$green = imageColorAllocateAlpha($image, 0, 255, 0, 40);
imageFilledRectangle($image, 40, 20, 90, 80, $green);

header("Content-Type: image/png");
imagePNG($image);

?>
up
1
bpgordon at gmail dot com
19 years ago
This code converts a block of text to an image so that each character in the block defines one pixel in the image and each line in the block (delimited by \n's) builds one whole row of pixels in the image.
Usage: Place a 0 to create a white pixel. Place a 1 to create a black pixel.
Example: Entering the following digits (including the line breaks) will create a 3x3 square with a 1-pixel white border.
00000
01110
01110
01110
00000

<?php
if (isset($_POST["sendtxt"])) {
header("Content-type: image/png");
$splitted = explode("\n", $_POST["sendtxt"]);
foreach (
$splitted as $tcurkey => $curval) $tsplitted[$tcurkey] = rtrim($curval);
$splitted = $tsplitted; //referencing isn't working for some reason...
$image = imagecreate(strlen($splitted[1]), count($splitted));
$white = imagecolorallocate($image, 0xFF, 0xFF, 0xFF); // don't delete this line
$black = imagecolorallocate($image, 0x00, 0x00, 0x00);
foreach(
$splitted as $curkey => $opelement) {
$subsplitten = preg_split("//", $opelement);
foreach(
$subsplitten as $subcurkey => $subopelement) {
if (
$subopelement == "1" || $subopelement == ".") imagesetpixel($image, $subcurkey-1, $curkey, $black);
}
}
imagepng($image);
imagedestroy($image);
} else {
echo <<<end
<table width="1" border="0"><td>
<form method="post" action="#">
<textarea cols="30" rows="7" name="sendtxt"></textarea><br>
<input type="submit" value="render">
</form></td></table>
end; }
?>
up
0
gerben at gerbs dot net
6 years ago
Note that you don't have to use imagecolorallocate to draw pixels. Instead, you can assign colors directly, which is much faster as well:
<?php
imagesetpixel
($img, $x, $y, $r << 16 | $g << 8 | $b);
?>
up
0
CR@SH
10 years ago
imagesetpixel ($image, $x, $y, IMG_COLOR_BRUSHED);
up
0
cyberhorse at users dot sourceforge dot net
14 years ago
Given an image $src and mask $mask, this applies the mask over the image, using different levels of transparency properly.

<?php
function image_mask(&$src, &$mask) {
imagesavealpha($src, true);
imagealphablending($src, false);
// scan image pixels
for ($x = 0; $x < imagesx($src); $x++) {
for (
$y = 0; $y < imagesy($src); $y++) {
$mask_pix = imagecolorat($mask,$x,$y);
$mask_pix_color = imagecolorsforindex($mask, $mask_pix);
if (
$mask_pix_color['alpha'] < 127) {
$src_pix = imagecolorat($src,$x,$y);
$src_pix_array = imagecolorsforindex($src, $src_pix);
imagesetpixel($src, $x, $y, imagecolorallocatealpha($src, $src_pix_array['red'], $src_pix_array['green'], $src_pix_array['blue'], 127 - $mask_pix_color['alpha']));
}
}
}
}
?>

If your mask is reversed, change 127 - $mask_pix_color['alpha'] with just $mask_pix_color['alpha']
up
0
aelitadelarobia at gmail dot com
15 years ago
another gradient example that can do horizontal or vertical gradients

<?php
$width
=$_GET['width'];
$height=$_GET['height'];
$starts=explode(",",$_GET['startcolor']);
$ends=explode(",",$_GET['endcolor']);
$rstart=$starts[0];
$gstart=$starts[1];
$bstart=$starts[2];
$rend=$ends[0];
$gend=$ends[1];
$bend=$ends[2];
$r=$rstart;
$g=$gstart;
$b=$bstart;
$bigger=imagecreatetruecolor($width,$height);
for (
$y=0;$y<=265;$y++) {
if (
$mode == 'horiz') { //if doing a horizontal gradient, reset to the starting color every row
$r=$rstart;
$g=$gstart;
$b=$bstart;
}
for (
$x=0;$x<=464;$x++) {
imagesetpixel($bigger,$x,$y,imagecolorallocate($bigger,$r,$g,$b));
if (
$mode=="horiz") {
if (
$r != $rend) {
$r=$r+(($rend-$rstart)/$width);
}
if (
$g != $gend) {
$g=$g+(($gend-$gstart)/$width);
}
if (
$b != $bend) {
$b=$b+(($bend-$bstart)/$width);
}
}
}
if (
$mode == "vert") {
if (
$r != $rend) {
$r=$r+(($rend-$rstart)/$height);
}
if (
$g != $gend) {
$g=$g+(($gend-$gstart)/$height);
}
if (
$b != $bend) {
$b=$b+(($bend-$bstart)/$height);
}
}
}
header("Content-type: image/jpeg");
header('Content-Disposition: inline; filename="gradient.jpg"');

imagejpeg($bigger,NULL,99);
imagedestroy($bigger);
?>
up
0
Scott Evernden (doctor3d at gmail)
15 years ago
Re: imagecreatefromtga() .. I just did some testing with what I think are valid Targa-24 and Targa-32 bit images, and modified the inner logic as follows:

<?php
if ($bytes_per_pixel == 2) // TARGA 16 - ARRRRRGG GGGBBBBB
{
$word = fileint($data, $pointer, 2);
$r = ($word & 0x7C00) >> 7;
$g = ($word & 0x03E0) >> 2;
$b = ($word & 0x001F) << 3;
$a = ($word & 0x8000) ? 127 : 0;
$color = imagecolorallocatealpha($image, $r, $g, $b, $a);
imagesetpixel($image, $x, $y, $color); }
else if (
$bytes_per_pixel == 3) // TARGA 24 - BBBBBBBB GGGGGGGG RRRRRRRR
{
$r = fileint($data, $pointer, 1);
$b = fileint($data, $pointer+1, 1);
$g = fileint($data, $pointer+2, 1);
$color = imagecolorallocate($image, $r, $g, $b);
imagesetpixel($image, $x, $y, $color);
}
else if (
$bytes_per_pixel == 4) // TARGA 32 - BBBBBBBB GGGGGGGG RRRRRRRR AAAAAAAA
{
$b = fileint($data, $pointer, 1);
$g = fileint($data, $pointer+1, 1);
$r = fileint($data, $pointer+2, 1);
$a = (255 - fileint($data, $pointer+3, 1)) >> 1;
$color = imagecolorallocatealpha($image, $r, $g, $b, $a);
imagesetpixel($image, $x, $y, $color);
}
?>

The red and blue tint issue seems to be fixed by this...
up
0
Scott Evernden (doctor3d at gmail)
16 years ago
My last note doesn't do alpha properly, so make the following change to the appropriate lines:

$r = ($word & 0x7C00) >> 7;
$g = ($word & 0x03E0) >> 2;
$b = ($word & 0x001F) << 3;
$a = ($word & 0x8000) ? 127 : 0;
$color = imagecolorallocatealpha($image, $r, $g, $b, $a);
imagesetpixel($image, $x, $y, $color);
up
0
Scott Evernden (doctor3d at gmail)
16 years ago
here's my version of imagecreatefromtga() that's been tested to work for targa 16 .. adapted from offering by zehao dot chang at gmail dot com

function imagecreatefromtga($filename)
{
$data = file_get_contents($filename);

// Extract header information
$string_length = fileint($data, 1, 1);
$data_type = fileint($data, 2, 1);
$width = fileint($data, 12, 2);
$height = fileint($data, 14, 2);
$bits_per_pixel = fileint($data, 16, 1);

$bytes_per_pixel = (int) $bits_per_pixel / 8;

// Currently only supporting RGB Data type
switch ($data_type) // Header information taken from http://astronomy.swin.edu.au/~pbourke/dataformats/tga/
{
case 2: // Uncompressed RGB image
break;
case 0: // No attached image data
case 1: // Uncompressed color-mapped image
case 3: // Uncompressed black and white image
case 9: // Runlength encoded color-mapped image
case 10: // Runlength encoded RGB image
case 11: // Compressed black and white image
case 32: // Compressed color-mapped data, using Huffman, Delta, and runlength encoding
case 33: // Compressed color-mapped data, using Huffman, Delta, and runlength encoding. 4-pass quadtree-type process
default:
return NULL; // No support for any of these types
}

// Compute things we need from the header information
$pointer = 18 + $string_length;
$x = 0; $y = $height - 1;

$image = imagecreatetruecolor($width, $height);

while ($pointer < strlen($data))
{
if ($bytes_per_pixel == 2) // TARGA 16 - ARRRRRGG GGGBBBBB
{
$word = fileint($data, $pointer, 2);
$r = ($word & 0x7C00) >> 10;
$g = ($word & 0x03E0) >> 5;
$b = ($word & 0x001F);
imagesetpixel($image, $x, $y, $r << 19 | $g << 11 | $b << 3);
}
else if ($bytes_per_pixel == 3) // TARGA 24 - RRRRRRRR GGGGGGGG BBBBBBBB
{
imagesetpixel($image, $x, $y, fileint($data, $pointer, 3));
}
else if ($bytes_per_pixel == 4) // TARGA 32 - AAAAAAAA RRRRRRRR GGGGGGGG BBBBBBBB
{
imagesetpixel($image, $x, $y, fileint($data, $pointer + 1, 3));
}

if (++$x == $width)
{
$y--;
$x = 0;
}
$pointer += $bytes_per_pixel;
}

return $image;
}

function fileint($data, $pos, $len)
{
return base_convert(bin2hex(strrev(substr($data, $pos, $len))), 16, 10);
}
up
0
zehao dot chang at gmail dot com
18 years ago
Here's my stab at the imagecreatefromtga function. I used code from send at mail dot 2aj dot net and others below as a basis, and added support for targa 16, targa 24 and targa 32. However, I only support uncompressed RBG data type as that's the only one I need. (I removed the return_array feature since you can simply use imagesx() and imagesy() to get the image size).

Please note that I have not tested this with a targa 16 since I don't have one handy at the moment.

<?php

function imagecreatefromtga( $filename )
{
$handle = fopen( $filename, 'rb' );
$data = fread( $handle, filesize( $filename ) );
fclose( $handle );

// Extract header information
$string_length = base_convert( bin2hex( substr($data,1,1) ), 16, 10 );
$data_type = base_convert( bin2hex( substr($data,2,1) ), 16, 10 );
$width = base_convert( bin2hex( strrev( substr($data,12,2) ) ), 16, 10 );
$height = base_convert( bin2hex( strrev( substr($data,14,2) ) ), 16, 10 );
$bits_per_pixel = base_convert( bin2hex( substr($data,16,1) ), 16, 10 );

// Currenly I'm only supporting RGB Data type
switch( $data_type ) // Header information taken from http://astronomy.swin.edu.au/~pbourke/dataformats/tga/
{
case
2: // Uncompressed RGB image
break;
case
0: // No attached image data
case 1: // Uncompressed color-mapped image
case 3: // Uncompressed black and white image
case 9: // Runlength encoded color-mapped image
case 10: // Runlength encoded RGB image
case 11: // Compressed black and white image
case 32: // Compressed color-mapped data, using Huffman, Delta, and runlength encoding
case 33: // Compressed color-mapped data, using Huffman, Delta, and runlength encoding. 4-pass quadtree-type process
default:
return
NULL; // No support for any of these types
}

// Compute things we need from the header information
$pointer = 18 + $string_length;
$bytes_per_pixel = (int) $bits_per_pixel/8;
$x = 0; $y = $height;

$image = imagecreatetruecolor($width, $height);

while (
$pointer < strlen($data) )
{
if(
$bytes_per_pixel == 2 ) // TARGA 16 - ARRRRRGG GGGBBBBB
{
$low_byte = bin2hex( strrev( substr($data, $pointer, $bytes_per_pixel)));
$high_byte = bin2hex( strrev( substr($data, $pointer, $bytes_per_pixel)));
$r = base_convert( ($high_byte & 0x7C)>>2, 16, 10);
$g = base_convert( (($high_byte & 0x03)<<3) | (($low_byte & 0xE0)>>5), 16, 10);
$b = base_convert( $low_byte & 0x1F, 16, 10);
imagesetpixel( $image, $x, $y, $r<<16 | $g<<8 | $b);
}
else if(
$bytes_per_pixel == 3 ) // TARGA 24 - RRRRRRRR GGGGGGGG BBBBBBBB
{
imagesetpixel( $image, $x, $y, base_convert( bin2hex( strrev( substr($data, $pointer, $bytes_per_pixel))), 16, 10));
}
else if(
$bytes_per_pixel == 4 ) // TARGA 32 - AAAAAAAA RRRRRRRR GGGGGGGG BBBBBBBB
{
imagesetpixel( $image, $x, $y, base_convert( bin2hex( strrev( substr($data, $pointer, $bytes_per_pixel-1))), 16, 10));
}

if(++
$x == $width)
{
$y--;
$x=0;
}
$pointer += $bytes_per_pixel;
}

return
$image;
}

?>
up
0
T. Dekker
19 years ago
In reply to weitheism at gmail.com:

You should probably have used ImageAlphaBlending($image, false); in your early attempts. This way any paint/fill operation replaces the alpha value of the destination.
up
0
chris at drunkenpirates dot co dot uk
21 years ago
<?php

/*
An example combining the use of ImageColorAllocate, Imagesetpixel, Imagecopyresized and some basic Trig

By chris@drunkenpirates.co.uk

*/

Header("Content-type: image/png");

$height = 128;
$width = 128;

$imA = ImageCreate($width, $height);
$imB = ImageCreate($width*4, $height*4);
$bckA = ImageColorAllocate($imA, 0,0,0);
$bckB = ImageColorAllocate($imB, 0,0,0);

//GENERATE GRAY SCALE PALLETE

for($c=0;$c<256;$c++){
ImageColorAllocate($imA, $c, $c, $c);
}

//PRODUCE DATA

$m=rand(0,10);
for(
$c=0;$c<128;$c++){
$s= (sin( deg2rad($c*360*$m/128) )+1)*127;
$col_arr[$c]=$s;
}
for(
$y=0;$y<$height;$y++){
for(
$x=0;$x<$width;$x++){
$imgA[$x][$y]=$col_arr[$x];
}
}
for(
$y=0;$y<$height;$y++){
for(
$x=0;$x<$width;$x++){
$imgB[$x][$y]=$col_arr[$y];
}
}

//SET PIXELS

for($y=0;$y<$height;$y++){
for(
$x=0;$x<$width;$x++){
$imgC[$x][$y]=$imgA[$x][$y]+$imgB[$x][$y];
$s=$imgC[$x][$y]/2;
Imagesetpixel($imA,$x,$y,$s);
}
}

//RESIZE IMAGE FOR DISPLAY

Imagecopyresized ($imB, $imA, 0, 0, 0, 0, $width*4, $height*4, $width, $width);
ImagePNG($imB);
?>
up
0
dino at nordmark dot dk
22 years ago
The example above diden't work, because of some errors.
This should work and it's also faster because there is only one 512*512 loop. (but it is still very slow)

<?
$filename="lena.raw";
$width=512;
$height=512;
$fp=fopen($filename, "r");
$contents=fread($fp,filesize($filename));
fclose($fp);

$image=imagecreate($width,$height);

// create greyscale palette because the image is limited to 256 colors
for ($i=0;$i<256;$i++){ ImageColorAllocate($image,$i,$i,$i);}

// This is slow, but probably the only way
for ($i=0;$i<512;$i++){
for ($j=0;$j<512;$j++){
imagesetpixel ($image,$i,$j,ord($contents[$i+$j*512]));
}
}

imagepng($image,"result.png");
imagedestroy($image);

echo "<img src=result.png></img>";
?>

--

Dino Patti
up
-1
caffinated
15 years ago
Want to have some fun with this function? How about edge detection! (ported from http://bitecode.co.uk/2008/07/edge-detection-in-python/)

<?php
function edge($input, $output)
{
$in_im = imageCreateFromJpeg($input);
$gx = array(array(-1, 0, 1), array(-2, 0, 2), array(-1, 0, 1));
$gy = array(array(-1, -2, -1), array(0, 0, 0), array(1, 2, 1));
$x = imagesx($in_im);
$y = imagesy($in_im);
$out_im = imagecreatetruecolor($x, $y);
$colors = array(255 => imagecolorallocate($out_im, 255, 255, 255));
for (
$row = 1; $row < $x; $row++)
{
for (
$col = 1; $col < $y; $col++)
{
$eyedropper =imagecolorat($in_im, $x, $y);
$color =imagecolorsforindex($in_im, $eyedropper);
$pxval = ($color['red'] + $color['green'] + $color['blue']) / 3;
$pixel_gx = $pixel_gy = 0;
for (
$i = -1; $i < 2; $i++)
{
for (
$j = -1; $j < 2; $j++)
{
$eyedropper =imagecolorat($in_im, $row+$i, $col+$j);
$color =imagecolorsforindex($in_im, $eyedropper);
$val = ($color['red'] + $color['green'] + $color['blue']) / 3;
$pixel_gx += $gx[$i+1][$j+1] * $val;
$pixel_gy += $gy[$i+1][$j+1] * $val;
}
}
$pixel = sqrt($pixel_gx * $pixel_gx + $pixel_gy * $pixel_gy);
$pixel = abs(255 - (int)$pixel);
if (!isset(
$colors[$pixel])) $colors[$pixel] = imagecolorallocate($out_im, $pixel, $pixel, $pixel);
imageSetPixel($out_im, $row, $col, $colors[$pixel]);
}
}
imagejpeg($out_im,$output, 75);
}

edge('input.jpg', 'output.jpg');

?>
up
-1
CPHaxer
15 years ago
Sorry for the long intro of my function, but i just want to tell how it works and - how silly sometimes the ideas are to make such functions. Have fun ;D

<?php

//@FunctionName: drawPlot
//@Parameters: drawPlot(img &$image, int $red, int $green, int $blue, int $x, int $y)
//
// img $image
// The Image it will draw on. The Image will be modified; there is no return value.
//
// int $red, int $green, int $blue
// The Colorvalues to draw with
//
// int $x, int $y
// The Location to draw the Plot.
// And this is the Mainpart, because $x and $y
// NEED NOT be rounded!
// If you want to make a Plot at [253.643891, 482];
// It will draw the Plot there. Exact at the Coordinates.
// You could use this to make smooth lines.
// They have rational Coordinates, too.
//
//@Author: Alexander Rath (*Feb 9th, 1996 ; 13 Years old)
//
//@Idea: We have in Math Geometrie now. And as the only Computerfreak
// In the class, i asked me: "How would it be, to mirror something
// At a NOT FLAT LINE."
// So I started thinking about it. First i tought about degresses - Nah!
// Then i saw:
// A point to mirror, has the SHORTEST way to the Line;
// so i just needed to make the result smooth.
// Unlike the other ways to draw pixels.
// ~I started developing this:
// PS: Sorry for bad english ( I am german )

//Lets create a TrueColor Image Resource
$image = imagecreatetruecolor(640, 480);

//Lets make it Alpha
imagealphablending($image, true);
imagesavealpha($image, true);

//...with White Background to draw on.
imagefilledrectangle($image, 0, 0, 640, 480, imagecolorallocate($image, 255, 255, 255));

//This is my little "Example"-Script
for($x = 0; $x <= 640; $x = $x + 0.01) {
$y = $x / (tan($x) + 1);
drawPlot($image, 0, 0, 0, $x, $y);
}

header("Content-type: image/png");
imagepng($image);

function
drawPlot(&$func_image, $func_red, $func_green, $func_blue, $func_x, $func_y) {
$func_Right = $func_x - floor($func_x);
$func_Left = 1 - $func_Right;

$func_Bottom = $func_y - floor($func_y);
$func_Top = 1 - $func_Bottom;

$func_RightAlpha = $func_Right * 127;
$func_LeftAlpha = $func_Left * 127;

$func_LeftTop = $func_LeftAlpha * $func_Top;
$func_RightTop = $func_RightAlpha * $func_Top;
$func_LeftBottom = $func_LeftAlpha * $func_Bottom;
$func_RightBottom = $func_RightAlpha * $func_Bottom;

$func_x = floor($func_x);
$func_y = floor($func_y);

imagesetpixel($func_image, $func_x, $func_y, imagecolorallocatealpha($func_image, $func_red, $func_green, $func_blue, 127 - $func_LeftTop));
imagesetpixel($func_image, $func_x + 1, $func_y, imagecolorallocatealpha($func_image, $func_red, $func_green, $func_blue, 127 - $func_RightTop));
imagesetpixel($func_image, $func_x + 1, $func_y + 1, imagecolorallocatealpha($func_image, $func_red, $func_green, $func_blue, 127 - $func_RightBottom));
imagesetpixel($func_image, $func_x, $func_y + 1, imagecolorallocatealpha($func_image, $func_red, $func_green, $func_blue, 127 - $func_LeftBottom));
}

?>

Have fun ;D
up
-1
mm
15 years ago
@ Scott Evernden

Scott, your function works great for uncompressed TGA image files, except the results for TGA 32 with alpha don't come out right, at least in my tests. If the alpha is all white, the resulting image comes out with a red tint. If black, the resulting image has a blue tint. I don't know how to make it just ignore the alpha, but that would be handy...
up
-1
Gusts Kaksis
17 years ago
This code generate a simple colortable - not a very acurate one (it would be good to define fade of color - more fading)

<?php
set_time_limit
(200);
/*
Custommize this to see some nice changes:
*/
$width = 360; // degrees
$height = 18; // byte
$offset = -60; // offset of color hue

/*
Main programm:
Here comes transformations - width to degrees and height to intesity
*/
$w2deg = $width/360;
$h2byte = $height/255;
$byte2deg = 255/360;
$im = imagecreatetruecolor($width,$height);
for (
$x = 0; $x < $width; $x ++){
/*
Transform X to degrees
*/
$x_pos = $x/$w2deg;
/*
Intensity position (where max intensity is 255) on 360 degree scale.
0 = red
1 = green
2 = blue
*/
$rgb_pos[0] = sin(deg2rad($x_pos) - deg2rad($offset + 0));
$rgb_pos[1] = sin(deg2rad($x_pos) - deg2rad($offset + 120));
$rgb_pos[2] = sin(deg2rad($x_pos) - deg2rad($offset + 240));
/*
Calculate intesity at current point 0 - 255
*/
$rgb_col[0] = 127 + 127 * $rgb_pos[0];
$rgb_col[1] = 127 + 127 * $rgb_pos[1];
$rgb_col[2] = 127 + 127 * $rgb_pos[2];

/*
White -> color -> Black loop
*/
for ($y = 0; $y < $height; $y ++){
/*
Transform Y to intensity (-255 to 255)
*/
$y_pos = -255 + ($y/$h2byte) * 2;
$rgb_out[0] = $rgb_col[0] - $y_pos;
$rgb_out[1] = $rgb_col[1] - $y_pos;
$rgb_out[2] = $rgb_col[2] - $y_pos;

/*
If we go over 255 or under 0 we normalize it
*/
foreach($rgb_out as $key => $col){
if (
$col > 255){
$rgb_out[$key] = 255;
} else if (
$col < 0){
$rgb_out[$key] = 0;
}
}
/*
Put a pixel
*/
$col = imagecolorallocate($im,$rgb_out[0],$rgb_out[1],$rgb_out[2]);
imagesetpixel($im,$x,$y,$col);
}
}
/*
Test output
*/
imagejpeg($im,'colortable.jpg');
echo
'<img src="colortable.jpg">';
?>
up
-1
Brian Vaughn [php at boynamedbri dot com]
19 years ago
I looked, but was unable to find any example code to watermark an image with a watermark that contained alpha transparency. So the following class does just that. As a parameter, it takes 2 image objects: the main image, and the watermark image (which can be a gif, png, whatever) - and optionally, an alpha setting (0-100% alpha for the watermark image). It then creates and returns a new image with the alpha-transparent watermark imposed, center-aligned, over the larger image.

<?php
class watermark{

function
create_watermark( $dst_img, $watermark_img, $alpha = 100 ) {
$alpha /= 100; # convert 0-100% user-friendly alpha to decimal

# calculate our images dimensions
$dst_img_w = imagesx( $dst_img );
$dst_img_h = imagesy( $dst_img );
$watermark_img_w = imagesx( $watermark_img );
$watermark_img_h = imagesy( $watermark_img );

# create new image to hold merged changes
$return_img = imagecreatetruecolor( $dst_img_w, $dst_img_h );
# $return_img = imagecreate( $dst_img_w, $dst_img_h );

# determine center position coordinates
$dst_img_min_x = floor( ( $dst_img_w / 2 ) - ( $watermark_img_w / 2 ) );
$dst_img_max_x = ceil( ( $dst_img_w / 2 ) + ( $watermark_img_w / 2 ) );
$dst_img_min_y = floor( ( $dst_img_h / 2 ) - ( $watermark_img_h / 2 ) );
$dst_img_max_y = ceil( ( $dst_img_h / 2 ) + ( $watermark_img_h / 2 ) );

# walk through main image
for( $y = 0; $y < $dst_img_h; $y++ ) {
for(
$x = 0; $x < $dst_img_w; $x++ ) {
$return_color = NULL;

# determine the correct pixel location within our watermark
$watermark_x = $x - $dst_img_min_x;
$watermark_y = $y - $dst_img_min_y;

# fetch color information for both of our images
$dst_rgb = imagecolorsforindex( $dst_img, imagecolorat( $dst_img, $x, $y ) );

# if our watermark has a non-transparent value at this pixel intersection
# and we're still within the bounds of the watermark image
if ( $watermark_x >= 0 && $watermark_x < $watermark_img_w &&
$watermark_y >= 0 && $watermark_y < $watermark_img_h ) {
$watermark_rbg = imagecolorsforindex( $watermark_img, imagecolorat( $watermark_img, $watermark_x, $watermark_y ) );

# using image alpha, and user specified alpha, calculate average
$watermark_alpha = round( ( ( 127 - $watermark_rbg['alpha'] ) / 127 ), 2 );
$watermark_alpha = $watermark_alpha * $alpha;

# calculate the color 'average' between the two - taking into account the specified alpha level
$avg_red = $this->get_ave_color( $dst_rgb['red'], $watermark_rbg['red'], $watermark_alpha );
$avg_green = $this->get_ave_color( $dst_rgb['green'], $watermark_rbg['green'], $watermark_alpha );
$avg_blue = $this->get_ave_color( $dst_rgb['blue'], $watermark_rbg['blue'], $watermark_alpha );

# calculate a color index value using the average RGB values we've determined
$return_color = $this->imagegetcolor( $return_img, $avg_red, $avg_green, $avg_blue );

# if we're not dealing with an average color here, then let's just copy over the main color
} else {
$return_color = imagecolorat( $dst_img, $x, $y );

}
# END if watermark

# draw the appropriate color onto the return image
imagesetpixel( $return_img, $x, $y, $return_color );

}
# END for each X pixel
} # END for each Y pixel

# return the resulting, watermarked image for display
return $return_img;

}
# END create_watermark()

# average two colors given an alpha
function get_ave_color( $color_a, $color_b, $alpha ) {
return
round( ( ( $color_a * ( 1 - $alpha ) ) + ( $color_b * $alpha ) ) );
}
# END get_ave_color()

# return closest pallette-color match for RGB values
function imagegetcolor($im, $r, $g, $b) {
$c=imagecolorexact($im, $r, $g, $b);
if (
$c!=-1) return $c;
$c=imagecolorallocate($im, $r, $g, $b);
if (
$c!=-1) return $c;
return
imagecolorclosest($im, $r, $g, $b);
}
# EBD imagegetcolor()

} # END watermark API
?>
up
-1
weitheism at gmail.com
19 years ago
I was looking for a way to actually DELETE pixels or squares or parts of an image from an image resource, and at first I thought imagesetpixel would do the trick. Unfortunately, it merely paints over that one pixel, and as far as I knew, php didn't have any native way of deleting sections out of your image - so this little method should take care of deleting rectangular parts of your pictures!

function deleteRectangle(&$oldImage,$leftX,$leftY,$rightX,$rightY)
{
// Since php has no native way of delete parts of images
// We have to divide the image into four different parts and then copy them manually to a new
// image

$xSize = imagesx($oldImage);
$ySize = imagesy($oldImage);

// Divides the image into four sections to copy
$imagesection = array();
$imagesection[] = array(0,0,$leftX,$ySize);
$imagesection[] = array($leftX,0,$rightX+1,$leftY);
$imagesection[] = array($leftX,$rightY+1,$rightX+1,$ySize);
$imagesection[] = array($rightX+1,0,$xSize,$ySize);

// Create the new, copied image
$newImage = imagecreatetruecolor($xSize,$ySize);
// Vital for transparency
imagesavealpha($newImage,true);

// Fills the background a transparent color
$transparentBackground = imagecolorallocatealpha($newImage,255,255,255,127);
imagefill($newImage,0,0,$transparentBackground);

// Copies each of the four imagesections into their respective old positions
for($i = 0;$i<count($imagesection);$i++)
imagecopyresampled($newImage,$oldImage, $imagesection[$i][0],$imagesection[$i][1], $imagesection[$i][0],$imagesection[$i][1], $imagesection[$i][2]-$imagesection[$i][0], $imagesection[$i][3]-$imagesection[$i][1], $imagesection[$i][2]-$imagesection[$i][0], $imagesection[$i][3]-$imagesection[$i][1]);

// Alternately you can cycle through each pixel in an image and see if that pixel is an the area
// but that could be more intensive
imagedestroy($oldImage);

// Sets the old image equal to the new, cleared image
$oldImage = $newImage;
}

It was made with a transparent background in mind, but you could easily change that by changeing imagecreatetruecolor to imagecreate and deleting the code that deals with transparency. Hope it helps!
up
-1
richard at mf2fm dot co dot uk
20 years ago
Here is a function that takes an image ($im) and returns it with the contrast maximised...

<?php
function contrast($im) {
$brightness=0;
$maxb=0;
$minb=255;
$imagesize=getimagesize($im);
$w=$imagesize[0];
$h=$imagesize[1];
for (
$x=0; $x<$w; $x++) {
for (
$y=0; $y<$h; $y++) {
$rgb=imagecolorat($im, $x, $y);
$rgb=imagecolorsforindex($im, $rgb);
$grey=0.2125*$rgb['red']+
0.7154*$rgb['green']+
0.0721*$rgb['blue'];
$brightness+=$grey;
if (
$grey>$maxb) $maxb=$grey;
if (
$grey<$minb) $minb=$grey;
}
}
$brightness=$brightness/($w*$h);
$minb=$brightness/($brightness-$minb);
$maxb=(255-$brightness)/($maxb-$brightness);
$contrast=min($minb, $maxb);
for (
$x=0; $x<$w; $x++) {
for (
$y=0; $y<$h; $y++) {
$rgb=imagecolorat($im, $x, $y);
$rgb=imagecolorsforindex($im, $rgb);
imagesetpixel($im, $x, $y,
65536*floor(min($rgb['red']*$contrast, 255))+
256*floor(min($rgb['green']*$contrast, 255))+
floor(min($rgb['blue']*$contrast, 255)));
}
}
return (
$im);
}
?>

An example of usage might be:
<?php
$imagefile
="/path/filename";
$image=imagecreatefromjpeg($imagefile);
$image=contrast($image);
imagejpeg($image, $imagefile);
?>
up
-2
Anonymous
16 years ago
This snippet creates a gradient images depending on the value of RGB components. Gradients allow your page to have a shadow effect.

<?php
try{
if(!
$image=imagecreatetruecolor(50,10)){
throw new
Exception('Error creating image');
}

for(
$y=0;$y<10;++$y)
{
$color=imagecolorallocate($image, 75+($y*5),75+($y*11),75+($y*9));
for(
$x=0;$x<50;++$x)
{
imagesetpixel($image,$x,$y,$color);
}
}

//header("Content-type: image/jpeg");
imagejpeg($image,'footerShadow.jpg');
// free memory
imagedestroy($image);

}
catch(
Exception $e){
echo
$e->getMessage();
exit();
}
?>
To Top