Last active
August 29, 2015 14:05
-
-
Save revolunet/cb7706f92b28e78023d9 to your computer and use it in GitHub Desktop.
Use Python+PIL to add multiple shapes transparency to a given PNG with antialiasing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- encoding: UTF-8 -*- | |
import os | |
import math | |
from PIL import Image, ImageDraw | |
def crop(source, out, top_angle, bottom_angle, crop_height=None): | |
im = Image.open(source) | |
im = im.convert("RGBA") | |
width, height = im.size | |
if crop_height and crop_height < height: | |
offset = (height - crop_height) / 2 | |
im = im.crop((0, offset, width, height-offset)) | |
width, height = im.size | |
def get_y_from_angle(angle): | |
''' return y position from give angle ''' | |
y = width / math.tan((90-angle)*math.pi/180) | |
return y | |
def get_positions_from_angle(angle, position): | |
''' compute shape coordinates based on angle+vertical position ''' | |
y = get_y_from_angle(angle) | |
if position == 'top': | |
y_left = y if y>0 else 0 | |
y_right = abs(y) if y<0 else 0 | |
positions = [ | |
(0, 0), | |
(width, 0), | |
(width, y_right), | |
(0, y_left), | |
] | |
else: | |
y_left = height - (abs(y) if y<0 else 0) | |
y_right = height - (y if y>0 else 0) | |
positions = [ | |
(width, height), | |
(0, height), | |
(0, y_left), | |
(width, y_right), | |
] | |
return positions | |
def removeShapes(image, shapes): | |
''' remove a list of shapes from the image and give them transparency ''' | |
alpha_mask = Image.new('L', (width*2, height*2), 255) | |
alpha_mask_draw = ImageDraw.Draw(alpha_mask) | |
for shape in shapes: | |
shape = [(x*2, y*2) for x, y in shape] | |
alpha_mask_draw.polygon(shape, fill=0, outline=0) | |
alpha_mask = alpha_mask.resize(image.size, Image.ANTIALIAS) | |
image.putalpha(alpha_mask) | |
return image | |
output = removeShapes(im, shapes= [ | |
get_positions_from_angle(top_angle, 'top'), | |
get_positions_from_angle(bottom_angle, 'bottom') | |
]) | |
output.save(out, 'png') | |
print '[+] created {0}'.format(out) | |
if __name__=='__main__': | |
ROOT_PATH = os.path.abspath(os.path.dirname(__file__)) | |
source = os.path.join(ROOT_PATH, 'PAGE-JEU.png') | |
out = os.path.join(ROOT_PATH, 'out.png') | |
crop(source, out, 2, -2, crop_height=1000) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment