|
 |
imagecopymerge (PHP 4 >= 4.0.1, PHP 5) imagecopymerge -- Copy and merge part of an image Descriptionbool imagecopymerge ( resource dst_im, resource src_im, int dst_x, int dst_y, int src_x, int src_y, int src_w, int src_h, int pct )
Copy a part of src_im onto
dst_im starting at the x,y coordinates
src_x, src_y with
a width of src_w and a height of
src_h. The portion defined will be copied
onto the x,y coordinates, dst_x and
dst_y.
The two images will be merged according to pct
which can range from 0 to 100. When pct = 0,
no action is taken, when 100 this function behaves identically
to imagecopy() for pallete images, while it
implements alpha transparency for true colour images.
Замечание: This function was added in PHP 4.0.6
imagecopymerge
yonzie at gmail dot com
05-Jun-2006 06:39
Watermarking for the complete idiot (that would be me, then)
My task: Image gallery, automatic resizing, watermarking, etc.
I was having huge trouble getting transparency right, but it has finally clicked. This is what worked for me:
First, I created a picture in Photoshop with a transparent background.
I then copied my logo (except for the background) onto this new transparent picture.
"Image > Mode > Indexed color" and "File > Save for Web". Ignore all the stuff about dithering, just make sure there's a checkmark in "Transparency" and PNG-8 is selected. Save and upload.
// Set up
$file = "path/to/picture.jpg"; // Picture to resize
$mark = "path/to/watermark.png"; // The watermark to use.
$newfile = "path/to/new/picture.jpg"; // The resized and watermarked picture that we'll end up with. Make sure this directory is writeable.
list( $sourcewidth, $sourceheight ) = getimagesize($file); // Size of source photo for resizing
list( $markwidth, $markheight ) = getimagesize($mark); // Size of source photo for resizing
$width = 800; // Width of picture after resizing
$height = 600; // Height of picture after resizing
// Load pictures
$source = imagecreatefromjpeg( $file ); // Source photo
$watermark = imagecreatefrompng( $mark ); // This is our watermark.
// Resizing
$resized = imagecreatetruecolor( $width, $height ); // Create memory space for resized picture
imagecopyresampled( $resized, $source, 0, 0, 0, 0, $width, $height, $sourcewidth, $sourceheight ); // Resize the source picture with a proper algorithm to avoid jaggies. Use imagezopyresized if you are in a hurry.
// Watermarking
imagecopymerge( $resized, $watermark, 10, $bigheight-$markheight-10, 0, 0, $markwidth, $markheight, 65 ); // Note 65% transparency of the NON-TRANSPARENT parts of the picture. This will put the watermark at the bottom-left corner of the picture, 10px from the edge.
// Saving
imagejpeg( $resized, "$newfile" ) or die ( 'Could not save picture! Please check permissions.' ); // Save file on disk
// Cleaning up
imagedestroy( $watermark ); // Clear memory
imagedestroy( $source ); // Clear memory
imagedestroy( $resized ); // Clear memory
bram at bldesign dot org
07-Apr-2006 12:03
I was trying to write a function to watermark images, but the results weren't great, so I decided to write my own dodge and burn functions. Dodging brightens the destination image according to the source image, burning darkens. Dodging with black or burning with white do nothing, so those can basically be used as transparency.
In both cases, the function will copy the entire $src image to $dst at location $dstx, $dsty with intensity $pct. $src and $dst should be handles to true color images.
function imagecopydodge($dst,$src,$dstx,$dsty,$pct)
{
$w = imagesx($src);
$h = imagesy($src);
$i = 0; $j = 0; $k = 0; $rgb = 0;
$d = array(); $s = array();
for ($i=0; $i<$h; $i++) {
for ($j=0; $j<$w; $j++) {
$rgb = imagecolorat($dst,$dstx+$j,$dsty+$i);
$d[0] = ($rgb >> 16) & 0xFF;
$d[1] = ($rgb >> 8) & 0xFF;
$d[2] = $rgb & 0xFF;
$rgb = imagecolorat($src,$j,$i);
$s[0] = ($rgb >> 16) & 0xFF;
$s[1] = ($rgb >> 8) & 0xFF;
$s[2] = $rgb & 0xFF;
$d[0] += min($s[0],0xFF-$d[0])*$pct/100;
$d[1] += min($s[1],0xFF-$d[1])*$pct/100;
$d[2] += min($s[2],0xFF-$d[2])*$pct/100;
imagesetpixel(
$dst, $dstx+$j, $dsty+$i,
imagecolorallocate($dst,$d[0],$d[1],$d[2])
);
}
}
}
function imagecopyburn($dst,$src,$dstx,$dsty,$pct)
{
$w = imagesx($src);
$h = imagesy($src);
$i = 0; $j = 0; $k = 0; $rgb = 0;
$d = array(); $s = array();
for ($i=0; $i<$h; $i++) {
for ($j=0; $j<$w; $j++) {
$rgb = imagecolorat($dst,$dstx+$j,$dsty+$i);
$d[0] = ($rgb >> 16) & 0xFF;
$d[1] = ($rgb >> 8) & 0xFF;
$d[2] = $rgb & 0xFF;
$rgb = imagecolorat($src,$j,$i);
$s[0] = ($rgb >> 16) & 0xFF;
$s[1] = ($rgb >> 8) & 0xFF;
$s[2] = $rgb & 0xFF;
$d[0] -= max($d[0]-$s[0],0)*$pct/100;
$d[1] -= max($d[1]-$s[1],0)*$pct/100;
$d[2] -= max($d[2]-$s[2],0)*$pct/100;
imagesetpixel(
$dst, $dstx+$j, $dsty+$i,
imagecolorallocate($dst,$d[0],$d[1],$d[2])
);
}
}
}
jylyn at hotmail dot com
22-Feb-2006 01:49
A few corrections to the code supplied by nick at prient:
$iTemplate should be $iBackground
$iWorking should be $iSource
After fixing those two I found the script really useful, thanks!
nick at prient dot co dot uk
01-Nov-2005 02:15
Task: Rotate a large image, then reduce it in size and place it on a small background (i.e. as an Inset).
Problem: If you resize the image first, the rotation becomes hugely aliased... So, it makes sense to rotate it first, then shrink it.
Unfortunately, when you resample the image, you lose the background color (at least, some of it may change), so you can no longer set transparancy as you require. If instead you resize the image (rather than resample), again, the aliasing looks bad.
Solution: Resize the background - make it bigger. Then add the original (large) inset, and resize the whole thing back to normal.
<?php
$resizePercentage = 0.25;
$iSource = ImageCreateFromJpeg($source_file);
$iBackground = ImageCreateFromJpeg($background_file);
...
$cBackground = ImageColorClosest($iSource, 255, 0, 255);
ImageColorTransparent($iSource, $cBackground);
$iBackground = ImageResize($iTemplate, ImageSX($iBackground ) / $resizePercentage, ImageSY($iBackground ) / $resizePercentage);
ImageCopyMerge($iBackground , $iSource,
((ImageSX($iBackground ) - ImageSX($iSource)) / 2),
((ImageSY($iBackground ) - ImageSY($iSource)) / 2) - 25, 0, 0, ImageSX($iWorking), ImageSY($iSource), 100);
$iBackground = ImageResize($iTemplate, ImageSX($iBackground ) * $resizePercentage, ImageSY($iBackground ) * $resizePercentage);
header("Content-Type: image/png");
ImagePng($iBackground);
exit();
function ImageResize($pImage, $t_width, $t_height) {
$iCanvas = @ImageCreateTrueColor($t_width, $t_height);
$s_width = ImageSX($pImage);
$s_height = ImageSY($pImage);
ImageCopyResampled($iCanvas, $pImage, 0, 0, 0, 0, $t_width, $t_height, $s_width, $s_height);
return $iCanvas;
}
?>
Ascent [at] WebAQ.com
24-May-2005 02:41
First you need make 0~9 gif format images and background image.
<?php
$rands = rand(1000,9999);
session_start();
$_SESSION['random_image_number_check'] = $rands;
$bg = './random_image_bg.jpg';
$numimgp = './random_image_number_%d.gif';
$numimg1 = sprintf($numimgp,substr($rands,0,1));
$numimg2 = sprintf($numimgp,substr($rands,1,1));
$numimg3 = sprintf($numimgp,substr($rands,2,1));
$numimg4 = sprintf($numimgp,substr($rands,3,1));
$ys1 = rand(-4,4);
$ys2 = rand(-4,4);
$ys3 = rand(-4,4);
$ys4 = rand(-4,4);
$bgImg = imageCreateFromJPEG($bg);
$nmImg1 = imageCreateFromGIF($numimg1);
$nmImg2 = imageCreateFromGIF($numimg2);
$nmImg3 = imageCreateFromGIF($numimg3);
$nmImg4 = imageCreateFromGIF($numimg4);
imageCopyMerge($bgImg, $nmImg1, 10, $ys1, 0, 0, 20, 30, 50);
imageCopyMerge($bgImg, $nmImg2, 30, $ys2, 0, 0, 20, 30, 50);
imageCopyMerge($bgImg, $nmImg3, 50, $ys3, 0, 0, 20, 30, 50);
imageCopyMerge($bgImg, $nmImg4, 70, $ys4, 0, 0, 20, 30, 50);
header("Content-type: image/jpg");
ImageJPEG($bgImg,"",100);
imagedestroy($bgImg);
imagedestroy($nmImg1);
imagedestroy($nmImg2);
imagedestroy($nmImg3);
imagedestroy($nmImg4);
?>
enjoy!
Steve
23-May-2005 11:03
Building upon backglancer's and stefan's posts below, the following script will lay a 24-bit PNG watermark over any image.
To prepare a 24-bit watermark, I recommend creating a white logo or text over a transparent background in Photoshop. Save this as a 24-bit PNG via 'Save for the Web...'. Be sure to set the transparency of the logo layer in Photoshop itself. 30-40% is a good setting.
Once the assets are prepared, throw the full or relative server paths at the watermark function below:
/******************************************************************/
function watermark($sourcefile, $watermarkfile) {
#
# $sourcefile = Filename of the picture to be watermarked.
# $watermarkfile = Filename of the 24-bit PNG watermark file.
#
//Get the resource ids of the pictures
$watermarkfile_id = imagecreatefrompng($watermarkfile);
imageAlphaBlending($watermarkfile_id, false);
imageSaveAlpha($watermarkfile_id, true);
$fileType = strtolower(substr($sourcefile, strlen($sourcefile)-3));
switch($fileType) {
case('gif'):
$sourcefile_id = imagecreatefromgif($sourcefile);
break;
case('png'):
$sourcefile_id = imagecreatefrompng($sourcefile);
break;
default:
$sourcefile_id = imagecreatefromjpeg($sourcefile);
}
//Get the sizes of both pix
$sourcefile_width=imageSX($sourcefile_id);
$sourcefile_height=imageSY($sourcefile_id);
$watermarkfile_width=imageSX($watermarkfile_id);
$watermarkfile_height=imageSY($watermarkfile_id);
$dest_x = ( $sourcefile_width / 2 ) - ( $watermarkfile_width / 2 );
$dest_y = ( $sourcefile_height / 2 ) - ( $watermarkfile_height / 2 );
// if a gif, we have to upsample it to a truecolor image
if($fileType == 'gif') {
// create an empty truecolor container
$tempimage = imagecreatetruecolor($sourcefile_width,
$sourcefile_height);
// copy the 8-bit gif into the truecolor image
imagecopy($tempimage, $sourcefile_id, 0, 0, 0, 0,
$sourcefile_width, $sourcefile_height);
// copy the source_id int
$sourcefile_id = $tempimage;
}
imagecopy($sourcefile_id, $watermarkfile_id, $dest_x, $dest_y, 0, 0,
$watermarkfile_width, $watermarkfile_height);
//Create a jpeg out of the modified picture
switch($fileType) {
// remember we don't need gif any more, so we use only png or jpeg.
// See the upsaple code immediately above to see how we handle gifs
case('png'):
header("Content-type: image/png");
imagepng ($sourcefile_id);
break;
default:
header("Content-type: image/jpg");
imagejpeg ($sourcefile_id);
}
imagedestroy($sourcefile_id);
imagedestroy($watermarkfile_id);
}
backglancer in the hotmail
17-May-2005 02:44
I was about to kill myself....
any one of you trying to merge a SEMI transparent png...
use imagecopy :)
<?
$flag = imagecreatefrompng('flags/images/flagWhiteFill.png');
$mask = imagecreatefrompng('flags/images/flag_transparent.png');
imagealphablending($flag, 1);
imagealphablending($mask, 1);
imagecopy($flag, $mask, 0,0,0,0,25,43);
Header("Content-type: image/jpeg");
imagepng($flag);
?>
ImageSaveAlpha(resource, bool); made the transparent color - not transparent... dunno why :)
barbarina_sv at libero dot it
17-May-2005 01:55
I needed to draw a "pointer" image over a map, but had some problems with png image transparency.
So I created a png image with white background (not transparent) and merged it on my map, after defining white color as transparent:
<?php
$src_file = 'source.jpg';
list($src_w, $src_h, $src_t, $src_a) = getimagesize($src_file);
$ptr_file = 'pointer.png'; list($ptr_w, $ptr_h, $ptr_t, $ptr_a) = getimagesize($ptr_file);
$dst_w = 400;
$dst_h = 200;
$ptr_x = 195;
$ptr_y = 70;
$srcImage = imageCreateFromJpeg($src_file) or die ('failed imageCreateFromJpg');
$dstImage = imageCreateTrueColor($dst_w, $dst_h) or die ('failed imageCreateTrueColor');
imageCopyResampled($dstImage, $srcImage, 0, 0, 0, 0, $dst_w, $dst_h, $src_w, $src_h) or die ('failed imageCopyResampled');
$ptrImage = imageCreateFromPng($ptr_file) or die ('failed imageCreateFromPng');
$ptr_white = imageColorAllocate($ptrImage,255,255,255);
imageColorTransparent($ptrImage,$ptr_white);
imageCopyMerge($dstImage, $ptrImage, $ptr_x, $ptr_y, 0, 0, $ptr_w, $ptr_h, 100) or die ('failed imageCopyMerge');
imageJpeg($dstImage,'',100) or die ('failed imageJpeg');
imageDestroy($srcImage) or die ('failed imageDestroy(1)');
imageDestroy($dstImage) or die ('failed imageDestroy(2)');
imageDestroy($ptrImage) or die ('failed imageDestroy(3)');
?>
ingrid
04-Apr-2005 02:16
I found on the internet about a thousand copies of this "imageCopyMerge" script of Stefan.
Most of them had a copyright notice of the copyist added, but none of them had added what a starting user of PHP scripting really needs: The lines to be used in a HTML page, where the result of the script will be visible:
<?php
$sourcefile = "ORIGFILE.jpg";
$insertfile = "watermark.jpg";
$targetfile = "foto.jpg";
$transition = 30;
$pos=7;
require("watermark.php");
mergePix($sourcefile, $insertfile, $targetfile, $pos, $transition);
echo "<img src=\"$targetfile\">";
?>
I was so lucky to get these lines from someone on the internet, after I posted my question all over the world.
Most other people that replied, referred to the bookstore. But I had first read halve the (this) PHP manual, and had not found it.
Just a suggestion, but I know it will help many people getting started with PHP: When you put your scripts here, why not add those few lines needed to incorporate it into a HTML page?
jtacon at php dot net
14-Dec-2004 05:36
This example shows how to use imageCopyMerge to create a water mark function with four random positions (the corners).
<?php
function waterMark($fileInHD, $wmFile, $transparency = 50, $jpegQuality = 90, $margin = 5) {
$wmImg = imageCreateFromGIF($wmFile);
$jpegImg = imageCreateFromJPEG($fileInHD);
$wmX = (bool)rand(0,1) ? $margin : (imageSX($jpegImg) - imageSX($wmImg)) - $margin;
$wmY = (bool)rand(0,1) ? $margin : (imageSY($jpegImg) - imageSY($wmImg)) - $margin;
imageCopyMerge($jpegImg, $wmImg, $wmX, $wmY, 0, 0, imageSX($wmImg), imageSY($wmImg), $transparency);
ImageJPEG($jpegImg, $fileInHD, $jpegQuality);
}
waterMark('myImage.jpg','waterMark.gif');
?>
HTH.
Javier Tacn.
claudio dot gaetani at gdldesign dot it
09-May-2004 11:04
This function is intended to serve as an example for the "imageCopyMerge"-"ImageCopyResized", "ImageColorTransparent" functions.
I hope it will help.
This function pick an image, square cut it resampled at the size requested and finishing merge the result with another one to obtain a circular image result. I have a problem to obtain an thumbnail that respect the colors and at the same time where cutted in a circular form, I hope this solution can gives you a clue to obtain a free form images, I use this one also to create multicutted images.
<?php
$generalsrc="$image"; $final_thumbwidth ="125";
$final_thumbheight ="125";
$abc = imagecreatefromjpeg("$generalsrc");
$def = imagecreatetruecolor($final_thumbwidth, $final_thumbheight);
$src_mx = round((imagesx($abc) / 2)-"0.1"); $src_my = round((imagesy($abc) / 2)-"0.1"); $src_x = ($src_mx * 2);
$src_y = ($src_my * 2);
$src_sq = ($src_x >= $src_y)?$src_y:$src_x; $pl = ($src_x >= $src_y)?"1":"2"; $strt_pntx = ($pl=="1")?round(($src_my / 2)-"0. 1"):"0"; $strt_pnty = ($pl=="2")?round(($src_mx / 2)-"0. 1"):"0"; imagecopyresized($def, $abc, 0, 0, $strt_pntx, $strt_pnty, $final_thumbwidth, $final_thumbheight, $src_sq, $src_sq);
$overlay_img = imagecreatefromPNG("circle_125.png"); $src_w = "ImageSX($overlay_img)";
$src_h = "ImageSY($overlay_img)";
$can_img = imagecreatetruecolor($src_w, $src_h);
$black = ImageColorAllocate ($overlay_img, 0, 0, 0);
ImageColorTransparent($overlay_img , $black);
imagecopy($can_img, $def, 0,0,0,0, $src_w, $src_h);
imagecopymerge($can_img, $overlay_img , 0,0,0,0, ImageSX($overlay_img), ImageSY($overlay_img),100); ImageJPEG($can_img,"merge_$generalsrc",100);
imagedestroy($overlay_img);
imagedestroy($can_img);
ImageDestroy($abc);
ImageDestroy($def);
print "<HTML><HEAD><TITLE>test</TITLE></HEAD><BODY>
original:<hr><img src=\"$generalsrc\" width=\"300\"><br><br><br>new:<hr><img src=\"merge_$generalsrc\">
<br>width = $src_x
<br>height = $src_y
<br>mdlw = $src_mx
<br>mdlh = $src_my
<br>sqr = $src_sq
<br>pl = $pl
<br>start point x = $strt_pntx
<br>start point y = $strt_pnty
</BODY></HTML>";
?>
bjorn AT smokingmedia DOT com
26-May-2003 11:10
in addition to stefan's posting:
i found that if you use imagecopymerge with png-24 files with an alpha channel, it doesn't work use imagecopy instead.
it seems that imagecopymerge doesn't respect the alpha channel the way it should (a bug??).
some sample code here to place an image (image.png) on a backgroundcolor or backgroundimage.
<?php
$im = "image.png";
$bg = "ffddee"; $out = "png"; function colordecode($hex){
$code[r] = hexdec(substr($hex, 0 ,2));
$code[g] = hexdec(substr($hex, 2 ,2));
$code[b] = hexdec(substr($hex, 4 ,2));
return $code;
} $image_id = imageCreateFromPNG($im);
$im_X = ImageSX($image_id);
$im_Y = ImageSY($image_id);
$backgroundimage = imagecreatetruecolor($im_X, $im_Y);
$code = colordecode($bg);
$backgroundcolor = ImageColorAllocate($backgroundimage, $code[r], $code[g], $code[b]);
ImageFilledRectangle($backgroundimage, 0, 0, $im_X, $im_Y, $backgroundcolor);
ImageAlphaBlending($backgroundimage, true);
imagecopy($backgroundimage, $image_id, 0, 0, 0, 0, $im_X, $im_Y);
if($output == "jpg"){
Header( "Content-type: image/jpeg");
ImageJPEG($backgroundimage);
}
else{
Header( "Content-type: image/png");
ImagePNG($backgroundimage);
}
ImageDestroy($backgroundimage);
ImageDestroy($image_id);
?>
feisty at feistyenterprises dot com
06-Nov-2002 12:15
Yep, that worked a charm.
Since imageCopyMergeGray() is identical, it works just as well for that.
If you want to convert an image to greyscale, use imageCopyMergeGray() with the same image as source and destination, set the pict to 0, et voila!
jonny at sanriowasteland dot net
29-Sep-2002 05:36
If you need to merge 2 png's (or presumably 2 gifs) with different color palettes, I have found this is the function to use. Just set pct to 99, and you are rocking. With pct set to 100, or imagecopy for that matter, the palette seems to go wonky. (It probably just uses the palette of the source image. but don't quote me on that).
stefan dot wehowsky at profilschmiede dot de
26-Jul-2001 09:32
This function is intended to serve as an example for the "imageCopyMerge"-function.
I hope it will help some of the less experienced php-coders here.
I wrote it to mark objects of a real estate broker as "sold" by copying the "sold"-picture right into the picture of the house.
<?php
function mergePix($sourcefile,$insertfile, $targetfile, $pos=0,$transition=50)
{
$insertfile_id = imageCreateFromJPEG($insertfile);
$sourcefile_id = imageCreateFromJPEG($sourcefile);
$sourcefile_width=imageSX($sourcefile_id);
$sourcefile_height=imageSY($sourcefile_id);
$insertfile_width=imageSX($insertfile_id);
$insertfile_height=imageSY($insertfile_id);
if( $pos == 0 )
{
$dest_x = ( $sourcefile_width / 2 ) - ( $insertfile_width / 2 );
$dest_y = ( $sourcefile_height / 2 ) - ( $insertfile_height / 2 );
}
if( $pos == 1 )
{
$dest_x = 0;
$dest_y = 0;
}
if( $pos == 2 )
{
$dest_x = $sourcefile_width - $insertfile_width;
$dest_y = 0;
}
if( $pos == 3 )
{
$dest_x = $sourcefile_width - $insertfile_width;
$dest_y = $sourcefile_height - $insertfile_height;
}
if( $pos == 4 )
{
$dest_x = 0;
$dest_y = $sourcefile_height - $insertfile_height;
}
if( $pos == 5 )
{
$dest_x = ( ( $sourcefile_width - $insertfile_width ) / 2 );
$dest_y = 0;
}
if( $pos == 6 )
{
$dest_x = $sourcefile_width - $insertfile_width;
$dest_y = ( $sourcefile_height / 2 ) - ( $insertfile_height / 2 );
}
if( $pos == 7 )
{
$dest_x = ( ( $sourcefile_width - $insertfile_width ) / 2 );
$dest_y = $sourcefile_height - $insertfile_height;
}
if( $pos == 8 )
{
$dest_x = 0;
$dest_y = ( $sourcefile_height / 2 ) - ( $insertfile_height / 2 );
}
imageCopyMerge($sourcefile_id, $insertfile_id,$dest_x,$dest_y,0,0,$insertfile_width,$insertfile_height,$transition);
imagejpeg ($sourcefile_id,"$targetfile");
}
| |