.PNG Alpha editing

This is the place for queries that don't fit in any of the other categories.

.PNG Alpha editing

Postby tsutttra12 » Thu Jan 23, 2014 5:01 pm

Is there a recommended module for editing png's? I've Installed PIL but it looks to be for mainly converting. I want to go through an image and delete any pixels that have an alpha value under 150. Any Information about this implementation would be helpful.
Thanks
tsutttra12
 
Posts: 8
Joined: Fri Jan 17, 2014 4:44 pm

Re: .PNG Alpha editing

Postby Mekire » Fri Jan 24, 2014 2:08 am

This would be pretty easy to do with Pygame, though I imagine it would be a bit slow.
Honestly I too think that PIL probably would be able to do this.

-Mek
User avatar
Mekire
 
Posts: 987
Joined: Thu Feb 07, 2013 11:33 pm
Location: Amakusa, Japan

Re: .PNG Alpha editing

Postby stranac » Fri Jan 24, 2014 12:45 pm

Yeah, it's totally doable using PIL.
It would look something like this:
Code: Select all
img = Image.open('whatever.png').convert('RGBA')
pixels = img.getdata()

for r, g, b, a in pixels:
    if a < 150:
        # assuming deleting a pixel means making it fully transparent
        new_pixels.append((r, g, b, 0))
    else:
        new_pixels.append((r, g, b, a))

img.putdata(new_pixels)
img.save('new.png')

There might be a simpler, built-in way to do this, but I'm not really an expert...
Friendship is magic!

R.I.P. Tracy M. You will be missed.
User avatar
stranac
 
Posts: 1135
Joined: Thu Feb 07, 2013 3:42 pm

Re: .PNG Alpha editing

Postby stranac » Fri Jan 24, 2014 1:29 pm

I knew I had this somewhere...
Here's a function I sometimes use to convert all the white pixels to transparent.
It uses img.load() to get a modifiable sequence of the image's pixels, which are then modified.
Code: Select all
def make_transparent(original_name, new_name):
    img = Image.open(original_name).convert('RGBA')
    pixels = img.load()
    width, height = img.size

    for y in xrange(height):
        for x in xrange(width):
            if pixels[x, y] == (255, 255, 255, 255):
                pixels[x, y] = (255, 255, 255, 0)

    img.save(new_name, 'PNG')

It's pretty easy to modify to do what you need.
Although it's still possible there's a better solution.
Friendship is magic!

R.I.P. Tracy M. You will be missed.
User avatar
stranac
 
Posts: 1135
Joined: Thu Feb 07, 2013 3:42 pm


Return to General Coding Help

Who is online

Users browsing this forum: No registered users and 6 guests