I needed a quick and dirty script (that I took a few minutes to clean up and throw together in a class) that can take a basic JPEG and turn it into a transparent PNG around the edges. I called it “Transparentize” — only because I couldn’t find any proper term for this.
I looked into PHP GD library’s imagefill function but it wasn’t quite giving me the results I needed. It only filled for exact colours, and in a JPEG with millions of colours, there are a number of variations of what the average set of eyes perceives as “white.” I need something where a threshold could be specified and find the edges of an image on a high contract background (for example, a basic black square on a white background).
How it works
Now I knew ahead of time that the images I was transparentizing were of pretty basic shapes, so I kept this in mind. My small script starts from the top image and processes from left to right until it reaches the contrasted edge of the object (as defined by the threshold) and then makes its way from right to left on the same Y axis. Here are some example results with varying thresholds:
|Original Image||Threshold: 1||Threshold: 50||Threshold: 145|
What needs to be done
Firstly, it could certainly use some sort of anti-aliasing, but I haven’t yet looked into this. I experimented a bit, but it might take some deeper research.
Secondly, it only works with images of a basic shape (like a box), it won’t work with more complex images that overlap their own background (like the letter ‘C’). I didn’t need this for my purposes, but if I have time I’ll write it out.