I have an image (jpg) with a white background. I want that background to be transparent, so I change the file format to png.

How do I now set the white as background?

I tried this as custom action:

imagecolortransparent ( $image->resource , imagecolorallocate ( $image->resource, 255, 255, 255 ) );

return $image

Comments

dman’s picture

That is near impossible with the tools available to us.
Have you tried magically removing the background in any image manipulation tool?
Either you use a magic wand (which we don't have) and then tweak the jaggies and fuzz, or you try a palette hack (like you did there) and get holes in the image where it's got white in. And JPEG white is not pure 255,255,255 anyway.

It's not something I know how to do with GD, and would be a lot of pixel squeezing.
It may not be impossible, but I don't have that algorithm.

There is a chance that something like this is possible in the 300 effects and flags that ImageMagic has but still, automatic results may be unreliable.

:-(

dman’s picture

Status: Active » Closed (works as designed)

Not something I can automate

dwatts3624’s picture

I've been reading up on this and haven't been able to find anything that's already been created for Drupal but have determined that it's possible through ImageMagick. On almost every site I design, there's a need to place logos on top of graphics (eg. photo, gradient, pattern, non-white color, etc.) and it's always an issue for end-users to remove the background offline in photoshop (or similar) or deal with a vector application.

There is a very long article on the subject here: http://www.imagemagick.org/Usage/masking/#bg_remove

Something like this seems like it would work for most logos:

convert file.png -bordercolor white -border 1x1 \
          -alpha set -channel RGBA -fuzz 20% \
          -fill none -floodfill +0+0 white \
          -shave 1x1    file_1.png

I'm guessing that the solution in Drupal is to use a custom ImageCache action; however, I'm not proficient enough in PHP to know how to apply the ImageMagick scripts provided in the article above to the ImageAPI.

...Even better, would be a script that would handle all file formats...

For instance:

1. for flat files do above and convert to transparent png (assuming this would just do nothing for an already transparent png)
2. for vector files, convert to transparent png

Any suggestions? Is there already something out there that does this?

dman’s picture

The code in custom_actions would be

$image->ops[] = "-bordercolor white -border 1x1 -alpha set -channel RGBA -fuzz 20% -fill none -floodfill +0+0 white -shave 1x1";
return $image;

... but on my version, I get
user error: ImageMagick reported error code 1. Message: convert: unrecognized option `-alpha'. in
.. same if I do it from commandline.

( Version: ImageMagick 6.2.8 06/11/08 ) OSX binary distro.

Results may vary if you have newer imagemagick I hope