GD2 - Copying two transparent images results in black background - php

This is blowing my mind. I want to merge 2 transparent PNGs.
One is a circle ($source) generated on the fly from a square image.
The second is a map marker ($marker) with a transparent circle to fit the first behind.
imagepng($source); and imagepng($marker); outputs just as one might expect.
With transparent backgrounds.
I then create an empty transparent image the size of the marker to place them both together:
//NEW BLANK TRANSPARENT IMAGE
$dest = imagecreatetruecolor(50, 61);
$transparent = imagecolorallocatealpha($dest, 0, 0, 0, 127);
imagefill($dest, 0, 0, $transparent);
imagealphablending($dest, true);
imagesavealpha($dest,true);
//COPY THE CIRCLE
imagecopy($dest, $source, 5, 5, 0, 0, 41, 41);
//AND THE MARKER ON TOP
imagecopy($dest, $marker, 0, 0, 0, 0, 50, 61);
In the result, the circle appears as a black square with the circle inside.
I tried a lot of combinations of imagealphablending and imagesavealpha both on $source and $dest and nothing seems to work.
How can I remove the black square and leave the $source transparent in the result as it is before the merge?

The problem here was:
To generate the circle on the fly, I was creating a circular mask and making everything else transparent making it red and then making red transparent.
This is incompatible with imagesavealpha(true) as it says the gd engine exactly to ignore transparent colors and save the whole alpha channel instead.
When merging both images, the color once transparent is now black.
The solution to my case was to analise it pixel per pixel and copy it to a blank image if it's inside the circle using the circular equation.

Related

Merge two PNG images with PHP. Output image CHANGES and wrong opacity

I need to merge the following images, however my solution is not working.
My code is the following (I pass the URL of the images to the script via GET parameter)
<?php
$dest = imagecreatefrompng($_GET['img1']);
$src = imagecreatefrompng($_GET['img2']);
imagecopymerge($dest, $src, 0, 0, 0, 0, 1500, 1500, 50);
$white = imagecolorallocate($dest, 255, 255, 255);
imagecolortransparent($dest, $white);
header('Content-Type: image/png');
imagepng($dest);
?>
Both image are PNG with transparent background and both are 1500x1500.
First image:
Second image:
What I get:
Why can't I make the final image have the right opacity? I tried changing the last value of imagecopymerge() to 0 or 100 but in those cases I only get one image or another. I need them both, exactly overlapped on one another!
Also, if you look carefully around the gem in the final image, there is some extra blue color... how is this possible?
This is caused by setting the resulting image to use image transparency rather than per-pixel alpha-channel transparency by your call to imagecolortransparent which sets any white (#ffffff) pixels to 100% transparent.
The artefacts ('extra blue colour' and edge pixels) on the resulting image are caused by the alpha-channel transparency from the original images not being saved and the pixels (which were 100% transparent but not white) showing their original colour.
The 'washed out' look of your result comes from telling imagecopymerge to merge the two images with 50% transparency.
The solution is to use the correct alpha settings:
<?php
$dest = imagecreatefrompng($_GET['img1']);
$src = imagecreatefrompng($_GET['img2']);
imagesavealpha($dest, true);
imagecopy($dest, $src, 0, 0, 0, 0, 1500, 1500);
header('Content-Type: image/png');
imagepng($dest);

PHP GD and transparent images sometimes work

While reading up on the issues merging transparent images in PHP, it seems that everyone is in the "it works" or "it doesn't work" camps. I have found a way to demonstrate each case.
I wish to take a PNG, cut an ALPHA hole in it and then merge it on top of another image. In this case, I cut a hole in an image from google maps, and paste it over a red block. I have two images from google maps. One is of Manhattan and one is of my house. One works, and one does not. The only difference is one was "saved" via a browser.
If you run the code below, you will see the difference in outputs. Does anyone know why the same code would treat two PNG files completely differently? It must be the difference in the PNG files themselves, but then what would it be?
<?php
sometimesworks("https://maps.googleapis.com/maps/api/staticmap?center=40.714728,-73.998672&zoom=12&size=400x400&maptype=hybrid", "google");
sometimesworks("https://lh4.googleusercontent.com/UQvV_dpBa3_rVf25pvLXKD3OwzF4FtPnHBHkzdWqjCQ5mlFqcFfId9echIgDMv_xYRRYzLaKEXphw7g=w2447-h1106", "myhouse");
function sometimesworks($p_image, $p_prefix)
{
$image_top =imagecreatefrompng($p_image);
$brush = imagecolorallocate($image_top, 0, 0, 0); //create a black brush
imagefilledpolygon($image_top, explode(",", "10,10, 120,22, 80,280, 200, 191"), 4, $brush); //fill a polygon
imagecolortransparent($image_top, $brush); //turn the black to be transparent
imagepng($image_top, './'.$p_prefix.'.transparent.png'); //save the file to confirm that it is working.
//create a big red square
$image_bottom = imagecreatetruecolor(imagesx($image_top), imagesy($image_top));
$red = imagecolorallocate($image_bottom, 255, 0, 0);
imagefill($image_bottom, 0, 0, $red);
imagepng($image_bottom, './'.$p_prefix.'.red.png');
//merge the top onto the bottom.
$out = imagecreatetruecolor(imagesx($image_top), imagesy($image_top));
imagecopy($out, $image_bottom, 0, 0, 0, 0, imagesx($image_top), imagesy($image_top));
imagecopy($out, $image_top, 0, 0, 0, 0, imagesx($image_top), imagesy($image_top));
imagepng($out, './'.$p_prefix.'.out.png');
}
The issue with the above code is that the PNG files were of different type. One was a truecolor image and the other was a palette. The code to merge files differs depending on what is being done.
This is a good reference for the merging of "palette" based PNG files with transparency.

PHP GD library - Unexpected white spots found on overlaying one gd semi-transparent image over the other

Ive been working on this project for days now and for some reason just not able to get rid of an unexpected 1px by 1px (approx) white spot that apears in each and every tile that is processed.
Summary:
I am using an original image ( say original.jpeg ) as referance to create a mosaic image ( say mosaic.jpeg which is approx 1000px by 1000px ) by merging totegher much much smaller jpeg images ( aprox 10px by 10px ).
I have a data set of approx 20,000 tile images to work with.
Process so far
I have mapped the original.jpeg image to cut it up into 5px by 5px tiles, then found the average color of each tile and saved it for further use.
I have scanned all the (10x10) tile images and stored their individual average colors as well.
i have calculated which tile image would fit closest to which tile of the original image by using Weighted ref : euclidean distance from the site mentioned.
I have managed to use PHP gd library to create a new truecolor image with all the matching tiles placed in the right position ( thus effectively creating a mosaic of the original.jpeg image )
The Problem
I am not getting a clear mosaic i had expected, for some reason the tiles do not match properly.
The Workaround
Now due to lack of time i an using a quick fix where in i take the original image, give it some 50% opacity and overlay it on top of each tile while it is being placed into the final mosaic.
NOTE: Although i am effectively overlaying the original image over the mosaic image, im NOT doing it in one go. The overlaying HAS to happen at each tile level.
So in short : Before placing each tile at the correct position of the final mosaic, i do the following
1. get that particular section of the original image ( 5x5px )
2. expand it to match the final tile size ( 10x10px )
3. set transparency for the section
4. place it over the tile that will be placed
5. merge this new tile over the final mosaic at the corresponding position.
Here is the function i have created to overlay part of the image along with transparency set to it.
public function overlay($dImg, $sImg, $opacity = null) {
// set default Opacity if not specified
$opacity = (is_null($opacity)) ? $this->opacity : $opacity;
// get width, height of sourceImage
$sWidth = imagesx($sImg);
$sHeight = imagesy($sImg);
// get width height of final image
$dWidth = imagesx($dImg);
$dHeight = imagesy($dImg);
$image = imagecreatetruecolor($dWidth, $dHeight);
imagecopyresampled($image, $sImg, 0, 0, 0, 0, $dWidth, $dHeight, $sWidth, $sHeight);
$background = imagecolorallocatealpha($image, 255, 255, 255, 127);
imagefill($image, 0, 0, $background);
imagealphablending($image, true);
imagecopymerge($dImg, $image, 0, 0, 0, 0, $dWidth, $dHeight, $opacity);
imagedestroy($image);
return $dImg;
}
THE REAL PROBLEM
in theory all of this seems perfectly fine. But the results have their own say in the matter.
I noticed an unusual almost 1x1px white patch at the start of every tile of the final mosaic.
This white patch only appears when the transparency technique above is applied. It does not happen otherwise.
I am clueless as to why this is happening, Due to this white patch the entire image looks like it has white noise all over it and degrades the overall quality immensely.
Please guide me in any direction as to why something like this could be happening.
your problem lies on these two lines:
$background = imagecolorallocatealpha($image, 255, 255, 255, 127);
imagefill($image, 0, 0, $background);
you don't need those, because imagefill is used to fill an area that have same/similar color with the color located on the supplied coordinate, in your case 0, 0 (top left), when there is no adjacent similar color, then it just change the color at the given coordinate.
you can use imagefilledrectangle instead, but i still think you don't need that, just comment out those 2 lines and see the result if it match your requirement, if not, then go ahead use imagefilledrectangle
imagefilledrectangle

Why does this transparent PNG cause borders when combined using GD?

I am trying to create an image from an another image using PHP. Here is my code:
<?php
$width = 109;
$height = 109;
$image = imagecreatetruecolor($width, $height);
$source_under = imagecreatefrompng('ecloid_under.png');
$black = imagecolorallocate($image, 0x00, 0x00, 0x00);
imagecolortransparent($image, $black);
imagecopy($image, $source_under, 0, 0, 0, 0, $width, $height);
header('Content-type: image/png');
imagepng($image);
imagedestroy($image);
?>
So I am loading this image in $source_under
and copying it over a transparent blank "canvas" image. Here is the result of that operation:
As can be seen, there is a sort of black border around the whole initial image. I think this is due to the fact that initially, the "canvas" image is all black. So there is something wrong with the transparency and the anti-aliasing of the image.
This isn't the first time I have a similar problem, but last time the source image was the cause. This time around, opening it in Photoshop does not show any potential problems with it.
Does anyone know how to fix this?
Can you try to enable alpha blending on $image before you copy the original to it:
imagealphablending($image, true);
Second try would be to create a transparent color and to fill $image with that color before the copy.
$transparent = imagecolorallocatealpha($image, 0, 0, 0, 127);
imagefill($image, 0, 0, $transparent);
imagealphablending($image, true);
You have partial transparency around the edges of your source image. That makes it combine with the black of the canvas image (which you normally can't see because it's 100% transparent), giving the results you see. You could avoid this by making sure your entire alpha channel on the source image is either 100% or 0%, or by choosing a more appropriate base color for your canvas image (i.e. one that matches the background color scheme of your site).
Fabio Anselmo's comment would help in that GIFs don't have a real alpha channel -- GIF transparency is all-or-nothing -- so saving as one will accomplish the 100%-or-0% solution. Unless you're extremely careful it will also give you a "border" right there in the source image -- made up of whatever background color you have or select in the GIF conversion -- as a result of your image's antialiasing. (However, the interlacing part is irrelevant.)

Alphabet border in transparent background image is unwanted?

I am using this code to creating images with text written in it with transparent backgrounds.
<?php
// Set the content-type
header('Content-Type: image/gif');
// Create the image
$im = imagecreatetruecolor(400, 150);
// Create some colors
$black = imagecolorallocate($im, 0, 0, 0);
$acolor = imagecolorallocate($im, 153, 204, 153);
imagecolortransparent($im, $black);
// The text to draw
$text = 'Testing...';
// Replace path by your own font path
$font = 'arial.ttf';
// Add the text
imagettftext($im, 50, 0, 10, 100, $acolor, $font, $text);
// Using imagegif()
imagegif($im,"img.gif");
imagedestroy($im);
?>
But text which is written in img.gif has some unwanted color(Black) on borders of alphabets('e,s,n,g'). How can i finish that color.The generated image is
The arial font download site is http://code.google.com/p/ireader/downloads/detail?name=arial.ttf
The GIF format cannot handle alpha transparency. It can have only 100% transparent (= invisible), or 100% opaque (= visible) pixels.
Your text seems to have anti-aliased, soft edges.
Those edges aren't 100% transparent, but they're also not 100% opaque - they are a mixture of foreground and background. That makes them appear softer.
Because the GIF format can't deal with these nuances, the library uses a mixture of green and black to simulate a "weaker" green.
If you use the PNG format, the problem should go away: PNG supports alpha transparency. There are some issues that you need to look into if you still need to support IE6, but for every other browser, this will work fine straight away.

Categories