0

Possible Duplicate:
Remove white background from an image and make it transparent

I currently have a code that removes the white background from an image, it looks like this:

function transparent_background($filename, $color) 
{
    $img = imagecreatefrompng($_SERVER['DOCUMENT_ROOT'].'/'.$filename);
    $colors = explode(',', $color);
    $remove = imagecolorallocate($img, $colors[0], $colors[1], $colors[2]);
    imagecolortransparent($img, $remove);
    imagepng($img, $_SERVER['DOCUMENT_ROOT'].'/'.$filename);
}

transparent_background('test.png', '255,255,255');

However, once it exports, the edge is very rough. This is what it looks like (note that this is just part of my image):

http://img211.imageshack.us/img211/97/2125c773e32c432b91e1127.png

I added a black background behind that image to show the edge better. So is there a way that I can add a line to the function or edit the function so the edges are smoother/anti-aliased? Thanks!

Community
  • 1
  • 1
  • There is nothing drawn in your code, could it be that the rough edge is in the original picture, just not visible because there is no dark background? – AndreKR Jan 03 '13 at 20:50
  • @AndreKR My code removes the white background from a specific PNG image on my server, and makes the white background transparent. However, the output edge is very rough and I was wondering if there was a way to make it smoother. – user1930449 Jan 03 '13 at 20:54
  • You might get a hint or two from my answer here or from other answers to the same question: http://stackoverflow.com/a/8042272/5987 – Mark Ransom Jan 03 '13 at 21:06

2 Answers2

1

There is no easy way to do this. The edge of the original image was anti-aliased to the white background. When you remove the pure white, you're left with a lot of pixels near the edge that are close to white. When you see those pixels against a dark color, they're going to stand out and look "rough". You won't get a smooth edge against a transparent background if it's not in the source image.

glomad
  • 5,539
  • 2
  • 24
  • 38
  • Maybe do a flood fill with a special color, remove all other colors, blur the resulting mask and overlay it to smooth the edges. – AndreKR Jan 03 '13 at 20:57
0

The final result of the output is being determined by the initial image quality of the image you are importing. PHP can only anti-alias elements that are drawn on an image.

One solution, a total sledgehammer approach, would be to resample the image up, and then down again. Your results will vary depending on the image in question, and it will almost always be not good.

The best solution for your particular problem is to use better quality imported images in the first place.

Ian Atkin
  • 6,302
  • 2
  • 17
  • 24