Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-2 of 2 total  RSS 

PNG-24 Alpha support for IE

What so much webdesigners dream about!
Get alpha channel on web, that's possible with PNG-24 images and this trick.
BE CAREFUL: that seem to work only for 10 images per page.

  # Display PNG-24 images with alpha channel on IE
  # BE CAREFUL: with this trick, only 10 PNGs seems to be supported by IE
  # Don't forget to set the size of your div
  def transpng(id, png)
    '<style type="text/css">
      <!--
        ' + id + ' {
          background-image: url(' + png + ');
        }
      -->
    </style>
    <!--[if IE]>
    <style>
      ' + id + ' {
        background-image: none;
        filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src=' + png + ', sizingMethod=\'scale\');
      }
    </style>
    <![endif]-->'
  end

Using transparent gif/png with Image's blitting

pys60's Image class will load a transparent gif/png
just like a non-transparent one.
But its blit() method accept a mask paramenter.
I have talked about this in a previous snippet.

The missing link is to create a mask automatically
from the Image. It's typically the top-left pixel.
You can use Image's getpixel() which is undocumented.
I show typical use of getpixel here.

Combine them all, here's the automask function.
def automask(im):
    width, height = im.size
    mask = Image.new(im.size, '1') # black and white
    tran = im.getpixel((0,0))[0]   # transparent top-left
    for y in range(height):
        line = im.getpixel([(x, y) for x in range(width)])
        for x in range(width):
            if line[x] == tran:
                mask.point((x,y), 0)  # mask on the point
    return mask

An example usage
from graphics import Image

ship = Image.open('E:\\Images\\ship.gif')
mask = automask(ship)

canvas.blit(ship, mask=mask)  # don't forget to create canvas first

A Sprite class can be defined based on this too.
« Newer Snippets
Older Snippets »
Showing 1-2 of 2 total  RSS