Skip to content

Instantly share code, notes, and snippets.

@wangtai
Created January 11, 2015 15:58
Show Gist options
  • Save wangtai/73e13df330e0f9c2ad20 to your computer and use it in GitHub Desktop.
Save wangtai/73e13df330e0f9c2ad20 to your computer and use it in GitHub Desktop.
def resize(file_path):
# import pdb; pdb.set_trace()
save_path = os.getcwd() + "/tmp/xxx.gif"
im = Image.open(file_path)
if im.format == 'GIF':
# rename file
new_file_path = file_path.split('.')[0] + '.gif'
os.rename(file_path, new_file_path)
return new_file_path.split('\\')[-1], new_file_path
if 'transparency' in im.info:
transparency = im.info['transparency']
im.save(save_path, transparency=transparency)
else:
# Get the alpha band
alpha = im.split()[3]
# Convert the image into P mode but only use 255 colors in the palette out of 256
im = im.convert('RGB').convert('P', palette=Image.ADAPTIVE, colors=255)
# Set all pixel values below 128 to 255,
# and the rest to 0
mask = Image.eval(alpha, lambda a: 255 if a <=128 else 0)
# Paste the color of index 255 and use alpha as a mask
im.paste(255, mask)
# The transparency index is 255
im.save(save_path, transparency=255)
fp = open(save_path, 'r')
file_name = md5_file_name(fp, 'gif')
fp.close()
return file_name, save_path
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment