(PHP 4, PHP 5)
imagecopy — Kopiert einen Bildausschnitt
Kopiert einen Teil des Quellbildes src_im nach dst_im. Der zu kopierende Teil wird angegeben über die x/y-Koordinaten src_x und src_y. Die Breite wird in src_w und die Höhe in src_h angegeben. Der Ausschnitt wird an die x/y-Koordinaten dst_x und dst_y kopiert.
There is function to crop blank edges from image.
<?php
/**
* $image image cursor (from imagecreatetruecolor)
* $backgound image curosr (from imagecolorallocate)
* $paddng int
*/
function imageCrop($image, $background = false, $padding = 0) {
if($background)
$background = imagecolorallocate($image, 255, 255, 255);
$top = imageSY($image);
$left = imageSX($image);
$bottom = 0;
$right = 0;
for ($x = 0 ; $x < imagesx($image) ; $x++) {
for ($y = 0 ; $y < imagesy($image) ; $y++) {
// if there match
if(imagecolorat($image, $x, $y) != $background) {
if($x < $left)
$left = $x;
if($x > $right)
$right = $x;
if($y > $bottom)
$bottom = $y;
if($y < $top)
$top = $y;
}
}
}
$right++;
$bottom++;
// create new image with padding
$img = imagecreatetruecolor($right-$left+$padding*2,$bottom-$top+$padding*2);
// fill the background
imagefill($img, 0, 0, $background);
// copy
imagecopy($img, $image, $padding, $padding, $left, $top, $right-$left, $bottom-$top);
// destroy old image cursor
imagedestroy($image);
return $img;
}
?>
I have created a PHP function which performs the standard 9-Slice scaling technique. This is extremely useful for thumbnail shadow scaling, and anything involving skinning. Feel free to pick apart and use
Note: instead of specifying margins, my 9-slicing routine uses a centered-rectangle concept... as input you provide the image (as a resource), the x and y coords of the rectangle, and the width and height of the rectangle.
The $src_im parameter should be an image resource. This script was written for 9-slicing translucent PNG images, and has only been tested with translucent PNG images, however it should work with other image types (possibly requiring some modification)
so if your source image was 400 x 400, you needed a 24 pixel margin on all sides, and your target size was 800 x 500, you would use the following parameters:
<?php
$im = NineSlice($im, 24, 24, 352, 352, 800, 500)
?>
<?php
/* 9-Slice Image Slicing Script by Sam Kelly (DuroSoft: http://www.durosoft.com) */
function NineSlice($src_im, $rect_x, $rect_y, $rect_w, $rect_h, $target_w, $target_h)
{
$src_w = imagesx($src_im);
$src_h = imagesy($src_im);
$im = CreateBlankPNG($target_w, $target_h);
imagealphablending($im,true);
$left_w = $rect_x;
$right_w = $src_w - ($rect_x + $rect_w);
$left_src_y = ceil($rect_h / 2) - 1 + $rect_y;
$right_src_y = $left_src_y;
$left_src_x = 0;
$right_src_x = $left_w + $rect_w;
$top_src_x = ceil($rect_w / 2) - 1 + $rect_x;
$bottom_src_x = $top_src_x;
$bottom_src_y = $rect_y + $rect_h;
$bottom_h = $src_h - $bottom_src_y;
$left_tile = CreateBlankPNG($left_w, 1);
imagecopy($left_tile, $src_im, 0, 0, 0, $left_src_y, $left_w, 1);
$right_tile = CreateBlankPNG($right_w, 1);
imagecopy($right_tile, $src_im, 0, 0, $right_src_x, $right_src_y, $right_w, 1);
$top_tile = CreateBlankPNG(1, $rect_y);
imagecopy($top_tile, $src_im, 0, 0, $top_src_x, 0, 1, $rect_y);
$bottom_tile = CreateBlankPNG(1, $bottom_h);
imagecopy($bottom_tile, $src_im, 0, 0, $bottom_src_x, $bottom_src_y, 1, $bottom_h);
$inner_tile = CreateBlankPNG(4, 4);
imagecopy($inner_tile, $src_im, 0, 0, ceil($src_w / 2) - 1, ceil($src_h / 2) - 1, 4, 4);
imagecopy($im, $src_im, 0, 0, 0, 0, $left_w, $rect_y);
imagecopy($im, $src_im, 0, $target_h - $bottom_h, 0, $bottom_src_y, $rect_x, $bottom_h);
imagecopy($im, $src_im, $target_w - $right_w, 0, $right_src_x, 0, $right_w, $rect_y);
imagecopy($im, $src_im, $target_w - $right_w, $target_h - $bottom_h, $src_w - $right_w, $bottom_src_y, $right_w, $bottom_h);
imagesettile($im, $top_tile);
imagefilledrectangle($im, $left_w, 0, $target_w - $right_w - 1, $rect_y, IMG_COLOR_TILED);
imagesettile($im, $left_tile);
imagefilledrectangle($im, 0, $rect_y, $left_w, $target_h - $bottom_h - 1, IMG_COLOR_TILED);
$right_side = CreateBlankPNG($right_w, $target_h - $rect_y - $bottom_h);
imagesettile($right_side, $right_tile);
imagefilledrectangle($right_side, 0, 0, $right_w, $target_h - $rect_y - $bottom_h, IMG_COLOR_TILED);
imagecopy($im, $right_side, $target_w - $right_w, $rect_y, 0, 0, $right_w, $target_h - $rect_y - $bottom_h);
$bottom_side = CreateBlankPNG($target_w - $right_w - $left_w, $bottom_h);
imagesettile($bottom_side, $bottom_tile);
imagefilledrectangle($bottom_side, 0, 0, $target_w - $right_w - $left_w, $bottom_h, IMG_COLOR_TILED);
imagecopy($im, $bottom_side, $right_w, $target_h - $bottom_h, 0, 0, $target_w - $right_w - $left_w, $bottom_h);
imagedestroy($left_tile);
imagedestroy($right_tile);
imagedestroy($top_tile);
imagedestroy($bottom_tile);
imagedestroy($inner_tile);
imagedestroy($right_side);
imagedestroy($bottom_side);
return $im;
}
function CreateBlankPNG($w, $h)
{
$im = imagecreatetruecolor($w, $h);
imagesavealpha($im, true);
$transparent = imagecolorallocatealpha($im, 0, 0, 0, 127);
imagefill($im, 0, 0, $transparent);
return $im;
}
?>
Regarding the image_flip function discussed in the notes here, don't forget to support transparency.
AFTER:
$imgdest = imagecreatetruecolor($width, $height);
ADD:
imagealphablending($imgdest, false);
imagesavealpha($imgdest, true);
In another post here it mentioned you didn't have to use the imagesavealpha function, but I found without it the background transparency can turn the background canvas black.
This is based on the Skew function from designerkamal at gmail dot com.
This is a function for skewing images in PHP with anti-aliasing. It works with alpha PNG images.
Warning: the bigger the image you skew, the longer it will take to process. It's about 3 times longer than without anti-aliasing.
<?php
// $img: handle of an image
// $skew_val: level of skew to apply (0 being none, 1 being 45°)
function imageskewantialiased($img, $skew_val)
{
$width = imagesx($img);
$height = imagesy($img);
$height2 = $height + ($width * $skew_val);
// See below for definition of imagecreatealpha
$imgdest = imagecreatealpha($width, $height2);
// Process the image
for($x = 0, $level = 0; $x < $width - 1; $x++)
{
$floor = floor($level);
// To go faster, some lines are being copied at once
if ($level == $floor)
imagecopy($imgdest, $img, $x, $level, $x, 0, 1, $height - 1);
else
{
$temp = $level - $floor;
// The first pixel of the line
// We get the color then apply a fade on it depending on the level
$color1 = imagecolorsforindex($img, imagecolorat($img, $x, 0));
$alpha = $color1['alpha'] + ($temp * 127);
if ($alpha < 127)
{
$color = imagecolorallocatealpha($imgdest, $color1['red'], $color1['green'], $color1['blue'], $alpha);
imagesetpixel($imgdest, $x, $floor, $color);
}
// The rest of the line
for($y = 1; $y < $height - 1; $y++)
{
// Merge this pixel and the upper one
$color2 = imagecolorsforindex($img, imagecolorat($img, $x, $y));
$alpha = ($color1['alpha'] * $temp) + ($color2['alpha'] * (1 - $temp));
if ($alpha < 127)
{
$red = ($color1['red'] * $temp) + ($color2['red'] * (1 - $temp));
$green = ($color1['green'] * $temp) + ($color2['green'] * (1 - $temp));
$blue = ($color1['blue'] * $temp) + ($color2['blue'] * (1 - $temp));
$color = imagecolorallocatealpha($imgdest, $red, $green, $blue, $alpha);
imagesetpixel($imgdest, $x, $floor + $y, $color);
}
$color1 = $color2;
}
// The last pixel of the line
$color1 = imagecolorsforindex($img, imagecolorat($img, $x, $height - 1));
$alpha = $color1['alpha'] + ((1 - $temp) * 127);
if ($alpha < 127)
{
$color = imagecolorallocatealpha($imgdest, $color1['red'], $color1['green'], $color1['blue'], $alpha);
imagesetpixel($imgdest, $x, $floor + $height - 1, $color);
}
}
// The line is finished, the next line will be lower
$level += $skew_val;
}
// Finished processing, return the skewed image
return $imgdest;
}
// Creates a new image of the size specified with a blank background (transparent)
function imagecreatealpha($width, $height)
{
// Create a normal image and apply required settings
$img = imagecreatetruecolor($width, $height);
imagealphablending($img, false);
imagesavealpha($img, true);
// Apply the transparent background
$trans = imagecolorallocatealpha($img, 0, 0, 0, 127);
for ($x = 0; $x < $width; $x++)
{
for ($y = 0; $y < $height; $y++)
{
imagesetpixel($img, $x, $y, $trans);
}
}
return $img;
}
// Here's an example of how to use it
imagepng(imageskewantialiased(imagecreatefrompng('test.png'), 0.15), 'skew.png');
?>
Simple and basic image cropping:
<?php
// Original image
$filename = 'someimage.jpg';
// Get dimensions of the original image
list($current_width, $current_height) = getimagesize($filename);
// The x and y coordinates on the original image where we
// will begin cropping the image
$left = 50;
$top = 50;
// This will be the final size of the image (e.g. how many pixels
// left and down we will be going)
$crop_width = 200;
$crop_height = 200;
// Resample the image
$canvas = imagecreatetruecolor($crop_width, $crop_height);
$current_image = imagecreatefromjpeg($filename);
imagecopy($canvas, $current_image, 0, 0, $left, $top, $current_width, $current_height);
imagejpeg($canvas, $filename, 100);
?>
I have a few remarks om the mirror-function:
The cases horizontal and vertical are switched.
1 = vertical and 2 = horizontal.
When I used it there appeared a black lining of 1 pixel on the side or on the top of the picture.
To remove it the function becomes as follows:
<?php
function ImageFlip ( $imgsrc, $mode )
{
$width = imagesx ( $imgsrc );
$height = imagesy ( $imgsrc );
$src_x = 0;
$src_y = 0;
$src_width = $width;
$src_height = $height;
switch ( $mode )
{
case '1': //vertical
$src_y = $height -1;
$src_height = -$height;
break;
case '2': //horizontal
$src_x = $width -1;
$src_width = -$width;
break;
case '3': //both
$src_x = $width -1;
$src_y = $height -1;
$src_width = -$width;
$src_height = -$height;
break;
default:
return $imgsrc;
}
$imgdest = imagecreatetruecolor ( $width, $height );
if ( imagecopyresampled ( $imgdest, $imgsrc, 0, 0, $src_x, $src_y , $width, $height, $src_width, $src_height ) )
{
return $imgdest;
}
return $imgsrc;
}
?>
concerning the previous post of Borszczuk and the function to mirror images:
There´s a way better (and faster) method for this task with imagecopyresampled.
<?php
define ( 'IMAGE_FLIP_HORIZONTAL', 1 );
define ( 'IMAGE_FLIP_VERTICAL', 2 );
define ( 'IMAGE_FLIP_BOTH', 3 );
function ImageFlip ( $imgsrc, $mode )
{
$width = imagesx ( $imgsrc );
$height = imagesy ( $imgsrc );
$src_x = 0;
$src_y = 0;
$src_width = $width;
$src_height = $height;
switch ( (int) $mode )
{
case IMAGE_FLIP_HORIZONTAL:
$src_y = $height;
$src_height = -$height;
break;
case IMAGE_FLIP_VERTICAL:
$src_x = $width;
$src_width = -$width;
break;
case IMAGE_FLIP_BOTH:
$src_x = $width;
$src_y = $height;
$src_width = -$width;
$src_height = -$height;
break;
default:
return $imgsrc;
}
$imgdest = imagecreatetruecolor ( $width, $height );
if ( imagecopyresampled ( $imgdest, $imgsrc, 0, 0, $src_x, $src_y, $width, $height, $src_width, $src_height ) )
{
return $imgdest;
}
return $imgsrc;
}
?>
Here is some simple code for resizing an uploaded image and inserting a watermark (from a 24-bit PNG) on the bottom right of it. In this case, the water mark was a diagnol band that said "SOLD" across it. The code that verifies the uploaded image is the correct type has been omitted:
<?PHP
//Load and resize the image
$uploaded = imagecreatefromjpeg($_FILES['file']['tmp_name']);
$image = imagecreatetruecolor(IMAGE_WIDTH, IMAGE_HEIGHT);
imagecopyresampled($image, $uploaded, 0, 0, 0, 0, IMAGE_WIDTH, IMAGE_HEIGHT, imagesx($uploaded), imagesy($uploaded));
imagealphablending($image,true); //allows us to apply a 24-bit watermark over $image
//Load the sold watermark
$sold_band = imagecreatefrompng('../images/sold_band.png');
imagealphablending($sold_band,true);
//Apply watermark and save
$image = image_overlap($image, $sold_band);
imagecopy($image,$sold_band,IMAGE_WIDTH - SOLD_WIDTH,IMAGE_HEIGHT - SOLD_HEIGHT,0,0,SOLD_WIDTH,SOLD_HEIGHT);
$success = imagejpeg($image,'../images/sold/'.$id.'.jpg',85);
imagedestroy($image);
imagedestroy($uploaded);
imagedestroy($sold_band);
?>
I had the same problem as Jeff, but his solution didn't work for me. I made this script, and it seems to work:
<?php
$img = imagecreatefromgif('in.gif');
$w = imagesx($img);
$h = imagesy($img);
$trans = imagecolortransparent($img);
if($trans >= 0) {
$rgb = imagecolorsforindex($img, $trans);
$oldimg = $img;
$img = imagecreatetruecolor($w,$h);
$color = imagecolorallocate($img,$rgb['red'],$rgb['green'],$rgb['blue']);
imagefilledrectangle($img,0,0,$w,$h,$color);
imagecopy($img,$oldimg,0,0,0,0,$w,$h);
}
imagegif($img,'out.gif');
?>
I came across the problem of having a page where any image could be uploaded, then I would need to work with it as a true color image with transparency. The problem came with palette images with transparency (e.g. GIF images), the transparent parts changed to black (no matter what color was actually representing transparent) when I used imagecopy to convert the image to true color.
To convert an image to true color with the transparency as well, the following code works (assuming $img is your image resource):
<?php
//Convert $img to truecolor
$w = imagesx($img);
$h = imagesy($img);
if (!imageistruecolor($img)) {
$original_transparency = imagecolortransparent($img);
//we have a transparent color
if ($original_transparency >= 0) {
//get the actual transparent color
$rgb = imagecolorsforindex($img, $original_transparency);
$original_transparency = ($rgb['red'] << 16) | ($rgb['green'] << 8) | $rgb['blue'];
//change the transparent color to black, since transparent goes to black anyways (no way to remove transparency in GIF)
imagecolortransparent($img, imagecolorallocate($img, 0, 0, 0));
}
//create truecolor image and transfer
$truecolor = imagecreatetruecolor($w, $h);
imagealphablending($img, false);
imagesavealpha($img, true);
imagecopy($truecolor, $img, 0, 0, 0, 0, $w, $h);
imagedestroy($img);
$img = $truecolor;
//remake transparency (if there was transparency)
if ($original_transparency >= 0) {
imagealphablending($img, false);
imagesavealpha($img, true);
for ($x = 0; $x < $w; $x++)
for ($y = 0; $y < $h; $y++)
if (imagecolorat($img, $x, $y) == $original_transparency)
imagesetpixel($img, $x, $y, 127 << 24);
}
}
?>
And now $img is a true color image resource
Here is an upgrade of that cool wave function: Double the size of the image, wave it, then resample it down again. This makes even nicer, anti aliased waves.
// So easy and nice!
function wave_region($img, $x, $y, $width, $height,$amplitude = 4.5,$period = 30)
{
// Make a copy of the image twice the size
$mult = 2;
$img2 = imagecreatetruecolor($width * $mult, $height * $mult);
imagecopyresampled ($img2,$img,0,0,$x,$y,$width * $mult,$height * $mult,$width, $height);
// Wave it
for ($i = 0;$i < ($width * $mult);$i += 2)
{
imagecopy($img2,$img2,
$x + $i - 2,$y + sin($i / $period) * $amplitude, // dest
$x + $i,$y, // src
2,($height * $mult));
}
// Resample it down again
imagecopyresampled ($img,$img2,$x,$y,0,0,$width, $height,$width * $mult,$height * $mult);
imagedestroy($img2);
}
To use it in a full image:
wave_region ($oImage,0,0,imagesx($oImage),imagesy($oImage));
This function does not resize the image. src_w and src_h are only used to define the portion of src_img that are going to be copied.
That is, it will copy src_img from coordinates src_x, src_y until src_w, src_h, and paste them on the dst_img starting from dst_x and dst_y.
If you wish to resize the image before copying it, check out
ImageCopyResized (though note it is slightly slower when you don't need to resize the image).
Id just like to make a clarification
imagecopy ( resource dst_im, resource src_im, int dst_x, int dst_y, int src_x, int src_y, int src_w, int src_h )
width of src_w and a height of src_h
Will not resize an image when resource src_im and resource dst_im are both defined
this may be a error with gd I believe I am running v2
While replying to a post in a support forum I noticed something odd about imagecopy(). The first snippet (should) create an image object, allocate a colour resource within that image, fill the background with the allocated colour and then copy another, cropped to fit, image onto it.
<?php
// create a new image resource
$temp = imagecreatetruecolor( $width, $height );
$white = imagecolorallocate( $temp, 255, 255, 255 );
//fill the background with white
imagefill( $temp, 0, 0, $white );
//copy the image into new a resource
imagecopy($temp, $this->Image, 0, 0, $crop_top, $crop_left, $width, $height);
?>
But this produces a black background. I noticed taking away the imagefill() call yields the same results. The solution was to call imagefill() after the imagecopy(). Thinking linearly I would have guessed this to cover the previously copied image in white but it doesn't. I guess GD uses a layer system? Is this correct?
<?php
// create a new image resource
$temp = imagecreatetruecolor( $width, $height );
$white = imagecolorallocate( $temp, 255, 255, 255 );
// copy image into new resource
imagecopy( $temp, $this->Image, 0, 0, $crop_top, $crop_left, $width, $height );
//fill the background with white (not sure why it has to be in this order)
imagefill( $temp, 0, 0, $white );
?>
I am using php 5.1.4 with the bundled GD (2.0.28)
I've made a little function to wave images:
<?php
// So easy and nice!
function wave_region($img, $x, $y, $width, $height,$grade=5){
for ($i=0;$i<$width;$i+=2){
imagecopy($img,$img,
$x+$i-2,$y+sin($i/10)*$grade, //dest
$x+$i,$y, //src
2,$height);
}
}
?>
More functions at http://www.sphoera.com
Basic way to implement a "crop" feature : given an image (src), an offset (x, y) and a size (w, h).
crop.php :
<?php
$w=$_GET['w'];
$h=isset($_GET['h'])?$_GET['h']:$w; // h est facultatif, =w par défaut
$x=isset($_GET['x'])?$_GET['x']:0; // x est facultatif, 0 par défaut
$y=isset($_GET['y'])?$_GET['y']:0; // y est facultatif, 0 par défaut
$filename=$_GET['src'];
header('Content-type: image/jpg');
header('Content-Disposition: attachment; filename='.$src);
$image = imagecreatefromjpeg($filename);
$crop = imagecreatetruecolor($w,$h);
imagecopy ( $crop, $image, 0, 0, $x, $y, $w, $h );
imagejpeg($crop);
?>
Call it like this :
<img src="crop.php?x=10&y=20&w=30&h=40&src=photo.jpg">
I used this to watermark images. This is the function I wrote:
<?php
function watermark($url,$logo){
$bwidth = imagesx($url);
$bheight = imagesy($url);
$lwidth = imagesx($logo);
$lheight = imagesy($logo);
$src_x = $bwidth - ($lwidth + 5);
$src_y = $bheight - ($lheight + 5);
ImageAlphaBlending($url, true);
ImageCopy($url,$logo,$src_x,$src_y,0,0,$lwidth,$lheight);
}
?>
Usage:
<?php
//$current_image would be your image the watermark is overlayed onto. Make sure it's imagecreatefrom*** to work.
watermark($current_image,$watermark_image);
?>
Hope this helps someone.
Here's an alternative image-flipping function which is simpler than either of the ones I've seen in the docs here. It takes the source image and the mode (zero for horizontal, nonzero for vertical) and returns the flipped image.
<?php
function imageflip($image, $mode) {
$w = imagesx($image);
$h = imagesy($image);
$flipped = imagecreate($w, $h);
if ($mode) {
for ($y = 0; $y < $h; $y++) {
imagecopy($flipped, $image, 0, $y, 0, $h - $y - 1, $w, 1);
}
} else {
for ($x = 0; $x < $w; $x++) {
imagecopy($flipped, $image, $x, 0, $w - $x - 1, 0, 1, $h);
}
}
return $flipped;
}
?>
Skewing images in PHP...
<?php
function Skew($src, $dest, $skew_val)
{
$imgsrc = imagecreatefromgif($src);
$width = imagesx($imgsrc);
$height = imagesy($imgsrc);
$imgdest = imagecreatetruecolor($width, $height+($height*$skew_val));
$trans = imagecolorallocate($imgdest,0,0,0);
$temp=0;
for($x=0 ; $x<$width ; $x++)
{
for($y=0 ; $y<$height ; $y++)
{
imagecopy($imgdest, $imgsrc, $x, $y+$temp, $x, $y, 1, 1);
imagecolortransparent($imgdest,$trans);
}
$temp+=$skew_val;
}
imagepng($imgdest, $dest);
imagedestroy($imgsrc);
imagedestroy($imgdest);
}
Skew("img.gif", "img2.png","1");
print "<img src='img.gif'>";
print "<br><br>";
print "<img src='img2.png'>";
?>
The source's palette is added to the destination's palette when merged, and when the destination already has 256 colors on it, the source image is altered to use those colors. Truecolor images always take up 256 colors when merged with palette images, so if you're planning to add any additional images after doing so, you can use imagetruecolortopalette() on the truecolor image before merging it to reduce how much palette space it takes, and avoid losing colors in future merges to the same destination. Example - imagetruecolortopalette($truecolorimg, FALSE, 128);
Here a function to make holes into images:
// Set the alpha channel for a part of an image (it ignores the canvas alpha atm).
// $img_canvas - 32-bit true color image w/ alpha channel
// $img_mask - 8-bit gray scale image (white parts will be masked transparent in the canvas).
// This relies on the current pixel format:
// (high byte) -> (alpha channel} {red} {green} {blue} <- (low byte)
function mask($img_canvas, $img_mask, $dst_x, $dst_y)
{
$old_blendmode = imagealphablending($img_canvas, FALSE);
$width = imagesx($img_mask);
$heigth = imagesy($img_mask);
$mask_x = 0;
$x = $dst_y;
while ($mask_x<$width)
{
$mask_y = 0;
$y = $dst_y;
while ($mask_y<$heigth)
{
imagesetpixel($img_canvas, $x, $y,
((imagecolorat($img_mask, $mask_x, $mask_y) >> 1) << 24) | (imagecolorat($img_canvas, $x, $y) & 0x00FFFFFF));
++$mask_y;
++$y;
}
++$mask_x;
++$x;
}
imagealphablending($img_canvas, $old_blendmode);
}
simple image combination srcipt, ie. if u want to create one huuuge signature from more small ones
<?php
// config --
$src = array ("http://www.google.com/images/logo_sm.gif", "http://sk2.php.net/images/php.gif");
$under = 0; // combine images underneath or not?
// -- end of config
$imgBuf = array ();
$maxW=0; $maxH=0;
foreach ($src as $link)
{
switch(substr ($link,strrpos ($link,".")+1))
{
case 'png':
$iTmp = imagecreatefrompng($link);
break;
case 'gif':
$iTmp = imagecreatefromgif($link);
break;
case 'jpeg':
case 'jpg':
$iTmp = imagecreatefromjpeg($link);
break;
}
if ($under)
{
$maxW=(imagesx($iTmp)>$maxW)?imagesx($iTmp):$maxW;
$maxH+=imagesy($iTmp);
}
else
{
$maxW+=imagesx($iTmp);
$maxH=(imagesy($iTmp)>$maxH)?imagesy($iTmp):$maxH;
}
array_push ($imgBuf,$iTmp);
}
$iOut = imagecreate ($maxW,$maxH) ;
$pos=0;
foreach ($imgBuf as $img)
{
if ($under)
imagecopy ($iOut,$img,0,$pos,0,0,imagesx($img),imagesy($img));
else
imagecopy ($iOut,$img,$pos,0,0,0,imagesx($img),imagesy($img));
$pos+= $under ? imagesy($img) : imagesx($img);
imagedestroy ($img);
}
imagegif($iOut);
?>
An little addon to Borszczuk's great function.
I've added the imagealphablending, so it supports transperency prette nice! It worked with me (only tested with PNG files).
I'm not sure if the imagesavealpha($imgdest, true); should be added, but it works fine without! No problems so far...
Thanks Borszczuk! Great job...
The code with the addon:
<?php
define("IMAGE_FLIP_HORIZONTAL", 1);
define("IMAGE_FLIP_VERTICAL", 2);
define("IMAGE_FLIP_BOTH", 3);
function ImageFlip($imgsrc, $type)
{
$width = imagesx($imgsrc);
$height = imagesy($imgsrc);
$imgdest = imagecreatetruecolor($width, $height);
ImageAlphaBlending($imgdest, false);
switch( $type )
{
// mirror wzgl. osi
case IMAGE_FLIP_HORIZONTAL:
for( $y=0 ; $y<$height ; $y++ )
imagecopy($imgdest, $imgsrc, 0, $height-$y-1, 0, $y, $width, 1);
break;
case IMAGE_FLIP_VERTICAL:
for( $x=0 ; $x<$width ; $x++ )
imagecopy($imgdest, $imgsrc, $width-$x-1, 0, $x, 0, 1, $height);
break;
case IMAGE_FLIP_BOTH:
for( $x=0 ; $x<$width ; $x++ )
imagecopy($imgdest, $imgsrc, $width-$x-1, 0, $x, 0, 1, $height);
$rowBuffer = imagecreatetruecolor($width, 1);
for( $y=0 ; $y<($height/2) ; $y++ )
{
imagecopy($rowBuffer, $imgdest , 0, 0, 0, $height-$y-1, $width, 1);
imagecopy($imgdest , $imgdest , 0, $height-$y-1, 0, $y, $width, 1);
imagecopy($imgdest , $rowBuffer, 0, $y, 0, 0, $width, 1);
}
imagedestroy( $rowBuffer );
break;
}
return( $imgdest );
}
?>
Just a little function that allows you to change the foreground color of a transparent gif or png.
It's supposed to use only two-color images, becouse it convert all the colors to the specified one.
It works with .gif or .png as source, but writes only .png
function ColorReplace( $url )
{
# The new color and its channels
$NEW_COLOR = "#FF66FF";
$r = 0+("0x".substr( $NEW_COLOR, 1, 2));
$g = 0+("0x".substr( $NEW_COLOR, 3, 2));
$b = 0+("0x".substr( $NEW_COLOR, 5, 2));
# I read the kind of file from the extension
$tmp = pathinfo($url);
$extension =$tmp['extension'];
if( $extension == 'png' ) $oldIm = @imagecreatefrompng( $url );
elseif( $extension == 'gif' ) $oldIm = @imagecreatefromgif( $url );
# I replace EACH color in the palette with the new one
for( $i=0; $i < imagecolorstotal( $oldIm ); $i++ )
imagecolorset( $oldIm, $i, $r,$g,$b );
# Output the file in png format : each color is now NEW COLOR
# but transparency is preserved !!
header("Content-type: image/png");
imagepng($oldIm);
imagedestroy($oldIm);
}
I've written a handy function to add rounded corners to an image. All you need is four images (the corners) with alpha transparency, so they need to be PNGs. This code can be eventually reused to add corners of any kind, not necessarily to round an image. Corners can be of different sizes, as the actual dimension is calculated for each one of them.
function roundedimage($source, $destination) {
// Retrieve image informations
$info = getimagesize($source);
// Load image from file
switch ($info['mime']) {
case 'image/jpeg' :
$image = imagecreatefromjpeg($source);
break;
case 'image/png' :
$image = imagecreatefrompng($source);
break;
case 'image/gif' :
$image = imagecreatefromgif($source);
break;
default:
return FALSE;
}
// Set the alphablending to on
imagealphablending($image, true);
// Get the size of the image
$image_w = imagesx($image);
$image_h = imagesy($image);
// Overlay left top corner
$crnimage_nw = imagecreatefrompng("crn_nw.png");
$crnimage_nw_w = imagesx($crnimage_nw);
$crnimage_nw_h = imagesy($crnimage_nw);
imagecopy($image, $crnimage_nw, 0, 0, 0, 0,
$crnimage_nw_w, $crnimage_nw_h);
// Overlay right top corner
$crnimage_ne = imagecreatefrompng("crn_ne.png");
$crnimage_ne_w = imagesx($crnimage_ne);
$crnimage_ne_h = imagesy($crnimage_ne);
imagecopy($image, $crnimage_ne, $image_w - $crnimage_ne_w,
0, 0, 0, $crnimage_ne_w, $crnimage_ne_h);
// Overlay left bottom corner
$crnimage_sw = imagecreatefrompng("crn_sw.png");
$crnimage_sw_w = imagesx($crnimage_sw);
$crnimage_sw_h = imagesy($crnimage_sw);
imagecopy($image, $crnimage_sw, 0, $image_h - $crnimage_sw_h,
0, 0, $crnimage_sw_w, $crnimage_sw_h);
// Overlay right bottom corner
$crnimage_se = imagecreatefrompng("crn_se.png");
$crnimage_se_w = imagesx($crnimage_se);
$crnimage_se_h = imagesy($crnimage_se);
imagecopy($image, $crnimage_se, $image_w - $crnimage_se_w,
$image_h - $crnimage_se_h, 0, 0, $crnimage_se_w,
$crnimage_se_h);
// Output to the original format
switch ($info['mime']) {
case 'image/jpeg' :
// Quality is set to 100%, maybe you can pass it via a param
imagejpeg($image, $destination, 100);
break;
case 'image/png' :
imagepng($image, $destination);
break;
case 'image/gif' :
imagegif($image, $destination);
break;
}
// Cleanup
imagedestroy($image);
imagedestroy($crnimage_nw);
imagedestroy($crnimage_ne);
imagedestroy($crnimage_sw);
imagedestroy($crnimage_se);
}
<?
// **** counting of width - START
// possible rating 0..5
$max_rating = 5;
$image_rating_width = 52;
$sirka_null = $image_rating_width / $max_rating * $_REQUEST['rating'];
// **** counting of width sirky - END
$rating = imagecreatetruecolor(52,12);
$nula = imagecreatefromjpeg("0.jpg");
$full = imagecreatefromjpeg("5.jpg");
imagecopy($rating, $full, 0, 0 , 0, 0, $sirka_null, 12);
imagecopy($rating, $nula, $sirka_null, 0 , $sirka_null, 0, (52-$sirka_null+1), 12);
header("Content-Type: image/jpeg");
imagejpeg($rating);
imagedestroy($rating);
exit;
?>
0.jpg is equal in size to 5.jpg (foe example 5 stars in image)
0.jpg has 0 filled stars as rating
5.jpg has 5 filled stars as rating
my images have size 52x12 px
You just put them together by imagecopy function :-)
I got some comments to Mirror() function given below by lecoguic at yahoo dot fr. First, it's quite good example of coding-without-bit-of-design approach ;) Lecoguic loops by all pixels and copy it each by each. Not good. The *only* reason I could find this approach explained is that he wanted MIRROR_BOTH to be handled. So the code looks quite ok, but performs quite poor. Below is much faster flipping function, blitting whole strips at once so it much more faster. $imgsrc is imagehandle. Function returns image handle to newly created flipped image.
define("IMAGE_FLIP_HORIZONTAL", 1);
define("IMAGE_FLIP_VERTICAL", 2);
define("IMAGE_FLIP_BOTH", 3);
function ImageFlip($imgsrc, $type)
{
$width = imagesx($imgsrc);
$height = imagesy($imgsrc);
$imgdest = imagecreatetruecolor($width, $height);
switch( $type )
{
// mirror wzgl. osi
case IMAGE_FLIP_HORIZONTAL:
for( $y=0 ; $y<$height ; $y++ )
imagecopy($imgdest, $imgsrc, 0, $height-$y-1, 0, $y, $width, 1);
break;
case IMAGE_FLIP_VERTICAL:
for( $x=0 ; $x<$width ; $x++ )
imagecopy($imgdest, $imgsrc, $width-$x-1, 0, $x, 0, 1, $height);
break;
case IMAGE_FLIP_BOTH:
for( $x=0 ; $x<$width ; $x++ )
imagecopy($imgdest, $imgsrc, $width-$x-1, 0, $x, 0, 1, $height);
$rowBuffer = imagecreatetruecolor($width, 1);
for( $y=0 ; $y<($height/2) ; $y++ )
{
imagecopy($rowBuffer, $imgdest , 0, 0, 0, $height-$y-1, $width, 1);
imagecopy($imgdest , $imgdest , 0, $height-$y-1, 0, $y, $width, 1);
imagecopy($imgdest , $rowBuffer, 0, $y, 0, 0, $width, 1);
}
imagedestroy( $rowBuffer );
break;
}
return( $imgdest );
}
This function will put a truecolor png with transparency over a custom color backgorund.
The image will be gracefully blended with the background color using the alpha channel for each color.
In real world we'd just mix foreground and backgorund colors looking at their percentages (i.e. 20% of background + 80% of foreground)
Here we have to calculate this for each r, g and b value of each color, and we have to use 127 instead of 100, because alpha channel goes from 0 to 127.
Try it on a color-to-transparent gradient!
<?php
function pngcolorizealpha($file, $color) {
/*
Function: pngcolorizealpha
Author: CoD (cod at crescentofdarkness dot cjb dot net)
Summary: Blends a truecolor png image with a coloured background using alpha channel
Input:
--------------------------
$file - string - path to the png image
$color- string - color in hex notation, without the #
Output:
--------------------------
a png image
*/
// first of all let's convert the background color
$background = array(
'red' => hexdec(substr($color,0,2)),
'green' => hexdec(substr($color,2,2)),
'blue' => hexdec(substr($color,4,2))
);
$im1 = imagecreatefrompng($file) or die('Cannot Initialize new GD image stream');
$im2 = imagecreatetruecolor(imagesx($im1), imagesy($im1));
$col1 = imagecolorallocate($im2, $background['red'], $background['green'], $background['blue']);
imagefill($im2,0,0,$col1);
// for each color in the original png
for ($i=0; $i< imagecolorstotal($im1); $i++) {
// find r,g,b and alpha value
$foreground = imagecolorsforindex($im1, $i);
// blend fore and back colors using alpha value
$r = (($foreground['red'] / 127) * (127 - $foreground['alpha'])) + (($background['red'] / 127)* $foreground['alpha']);
$g = (($foreground['green'] / 127) * (127 - $foreground['alpha'])) + (($background['green'] / 127)* $foreground['alpha']);
$b = (($foreground['blue'] / 127) * (127 - $foreground['alpha'])) + (($background['blue'] / 127)* $foreground['alpha']);
// allocate this new color in the destination image
imagecolorallocate($im2, $r,$g,$b);
}
imagecopy($im2, $im1, 0, 0, 0, 0, imagesx($im1), imagesy($im1));
header ("Content-type: image/png");
imagepng($im2);
imagedestroy($im1);
imagedestroy($im2);
}
?>
Here is a function to flip an image using imagecopy, just replace SRC_IMAGE and DEST_IMAGE with your own filename
(works only for jpg source image)
<?
define("MIRROR_HORIZONTAL", 1);
define("MIRROR_VERTICAL", 2);
define("MIRROR_BOTH", 3);
function Mirror($src, $dest, $type)
{
$imgsrc = imagecreatefromjpeg($src);
$width = imagesx($imgsrc);
$height = imagesy($imgsrc);
$imgdest = imagecreatetruecolor($width, $height);
for ($x=0 ; $x<$width ; $x++)
{
for ($y=0 ; $y<$height ; $y++)
{
if ($type == MIRROR_HORIZONTAL) imagecopy($imgdest, $imgsrc, $width-$x-1, $y, $x, $y, 1, 1);
if ($type == MIRROR_VERTICAL) imagecopy($imgdest, $imgsrc, $x, $height-$y-1, $x, $y, 1, 1);
if ($type == MIRROR_BOTH) imagecopy($imgdest, $imgsrc, $width-$x-1, $height-$y-1, $x, $y, 1, 1);
}
}
imagejpeg($imgdest, $dest);
imagedestroy($imgsrc);
imagedestroy($imgdest);
}
Mirror(SRC_IMAGE, DEST_IMAGE, MIRROR_HORIZONTAL);
print "<img src='SRC_IMAGE'>";
print "<br><br>";
print "<img src='DEST_IMAGE'>";
?>
Although the following function doesn't use imagecopy(), I thought it might help in related tasks. Please see the code comments for details of it's operation. I made this function to assist in creating images using multiple "layers". For example if you wanted to dynamically create a logo image with seperate colors for say the logo itself and a glow around the logo, these steps would be followed:
-Using an image editor (like Photoshop), create a png-24 image with just the logo on a transparent background. The logo can be any color or multiple colors, but the final image created by this function will be of a single color.
-Create a similar image with just the glow (no logo)
-Create a background image
-Apply this colorize() function to the logo image and the glow image with your desired color for each.
-You can now use imagecopy() to merge all three into a single image ready for a browser.
Here's the code
<?php
/*======Colorize=====
(requires GD 2.0.1 or greater)
This function requires the following arguments:
$src_path = A string representing the relative path to the src image. Ex: "images/myimage.png". This
image must be a png-24 with an alpha channel.
$dest_path = A string representing the relative path to the image to be created.
$hex_color = A string representing a color in html format, including the # sign. Ex: "#D2E5FF"
This function examines the transparency of the source image, pixel by pixel, and creates a new
one-color image with this same "transparency map".
====================*/
function colorize($src_path, $dest_path, $hex_color) {
//get the png-24 image - it must have an alpha channel for this funciton to be effective
$src = imagecreatefrompng($src_path);
//get width
$w = imagesx($src);
//get height
$h = imagesy($src);
//create same size destination image
$dest = imagecreatetruecolor($w, $h);
//this must be set to false in order to be able to overwright the defualt black pixels of the background with our new
//transparent pixels. Otherwise our new pixel would just be applied on top of the black.
imagealphablending($dest, false);
//get decimal components of the passed hex color
$red = hexdec(substr($hex_color, 1, 2));
$green = hexdec(substr($hex_color, 3, 2));
$blue = hexdec(substr($hex_color, 5, 2));
for ($i = 0; $i < $h; $i++) { //this loop traverses each row in the image
for ($j = 0; $j < $w; $j++) { //this loop traverses each pixel of each row
//get the color & alpha info of the current pixel
$retrieved_color = imagecolorat($src, $j, $i);
//put this info into an array
$rgba_array = imagecolorsforindex($src, $retrieved_color);
//get the transparency of the pixel as a number from 0 (opaque) to 127 (transparent)
$alpha = $rgba_array['alpha'];
//allocate the color to paint. Note that we may continue to overwright this color since our image is not palleted
$color_to_paint = imagecolorallocatealpha($dest, $red, $green, $blue, $alpha);
//paint the pixel
imagesetpixel($dest, $j, $i, $color_to_paint);
}
}
//this allows the new transparency info to be saved with the image
imagesavealpha($dest, true);
//write the image to the destination file
imagepng($dest, $dest_path);
}
?>
I've found a convenient way to "blit" one image into another. Using the following Code you can copy one image into another, leaving out the pixels with the specified transparent color. I'm using PNG but by replacing all PNG functions by JPEG or GIF functions you are able to use those formats as well:
<?php
$background = imagecreatefrompng("background.png");
$insert = imagecreatefrompng("insert.png");
// Either a color at a specific point on the image
// imagecolortransparent($insert,imagecolorat($insert,0,0));
// or a specific color (the color I used is magenta, #ff00ff)
imagecolortransparent($insert,imagecolorexact($insert,255,0,255));
$insert_x = imagesx($insert);
$insert_y = imagesy($insert);
// As said above, you can't use imagecopy (bug?)
imagecopymerge($background,$insert,0,0,0,0,$insert_x,$insert_y,100);
// imagejpeg or imagepng doesn't matter here
imagejpeg($background,"",100);
?>
// Image Resize
function createthumb($IMAGE_SOURCE,$THUMB_X,$THUMB_Y,$OUTPUT_FILE){
$BACKUP_FILE = $OUTPUT_FILE . "_backup.jpg";
copy($IMAGE_SOURCE,$BACKUP_FILE);
$IMAGE_PROPERTIES = GetImageSize($BACKUP_FILE);
if (!$IMAGE_PROPERTIES[2] == 2) {
return(0);
} else {
$SRC_IMAGE = ImageCreateFromJPEG($BACKUP_FILE);
$SRC_X = ImageSX($SRC_IMAGE);
$SRC_Y = ImageSY($SRC_IMAGE);
if (($THUMB_Y == "0") && ($THUMB_X == "0")) {
return(0);
} elseif ($THUMB_Y == "0") {
$SCALEX = $THUMB_X/($SRC_X-1);
$THUMB_Y = $SRC_Y*$SCALEX;
} elseif ($THUMB_X == "0") {
$SCALEY = $THUMB_Y/($SRC_Y-1);
$THUMB_X = $SRC_X*$SCALEY;
}
$THUMB_X = (int)($THUMB_X);
$THUMB_Y = (int)($THUMB_Y);
$DEST_IMAGE = imagecreatetruecolor($THUMB_X, $THUMB_Y);
unlink($BACKUP_FILE);
if (!imagecopyresized($DEST_IMAGE, $SRC_IMAGE, 0, 0, 0, 0, $THUMB_X, $THUMB_Y, $SRC_X, $SRC_Y)) {
imagedestroy($SRC_IMAGE);
imagedestroy($DEST_IMAGE);
return(0);
} else {
imagedestroy($SRC_IMAGE);
if (ImageJPEG($DEST_IMAGE,$OUTPUT_FILE)) {
imagedestroy($DEST_IMAGE);
return(1);
}
imagedestroy($DEST_IMAGE);
}
return(0);
}
} # end createthumb
As you probably know 'gif' is a paletted image, that is why if you want to copy one 'gif' onto another 'gif' using ImageCopy you need to create a paletted destination image using (ImageCreate), not ImageCreateTrueColor.
If you want to copy a non-rectangular (hence transparent) image onto a background (for example, a pawn onto a chessboard) do the following:
First, create the pawn image pawn.png in your favorite graphics program. Do NOT make the image transparent, instead, give it a distinct solid background color. You will flag this color as transpernt inside PHP, otherwise imagecopy will not honor the transparency.
Then:
$board = imagecreatefrompng ("board.png");
$pawn = imagecreatefrompng ("pawn.png");
imagecolortransparent ($pawn, imagecolorat ($pawn, 0, 0));
imagecopy ($board, $pawn, $x, $y, 0, 0, $pawnWidth, $pawnHeight);
imagedestroy ($pawn);
One way 'round the even/odd image size problem would be to use bcdiv.
If you are getting an error when using ImageCopy(), be sure that both images are of the same type - either True Color or Palette.
GD 1.x can copy images of different types, but with GD 2.0 this will cause an error.
sorry - forgot to fill in my email...
Note that ImageCreateFromJPEG always creates a True Color Image.
You can use ImageCreateTrueColor() instead of Image Create() to solve this problem.
Want to make an image tile properly? This is accomplished by swapping all four quadrants of the image. Here is some sample code that uses imagecopy to do it:
<?php
function backgroundify(&$image) {
$ix = imagesx($image);
$iy = imagesy($image);
$ixhalf = floor($ix / 2); // DON'T USE ON IMAGES WITH ODD SIZES!
$iyhalf = floor($iy /2);
$panel_temp = ImageCreate ($ix, $iy) or die("Cannot Initialize new GD image stream");
imagecopy($panel_temp, $image, 0,0,0,0,$ix, $iy);
imagecopy($image, $panel_temp, 0,0,$ixhalf,$iyhalf, $ix-$ixhalf, $iy-$iyhalf); // move bottom right to top left
imagecopy($image, $panel_temp, $ixhalf,$iyhalf, 0,0,$ix-$ixhalf, $iy-$iyhalf); // top left to bottom right
imagecopy($image, $panel_temp, $ixhalf, 0,0,$iyhalf,$ix-$ixhalf, $iy-$iyhalf); // bottom left to topo right
imagecopy($image, $panel_temp, 0,$iyhalf, $ixhalf,0,$ix-$ixhalf, $iy-$iyhalf); // top left to bottom right
}
?>