Browse Source

Added code to optimize PNG images file size (indexed colors with all-or-nothing alpha)

master
Youen 2 years ago
parent
commit
ff8b904dc4
  1. 1
      .gitignore
  2. 16
      ahb_raster_view.py

1
.gitignore vendored

@ -3,3 +3,4 @@
__pycache__/ __pycache__/
*.py[cod] *.py[cod]
*$py.class *$py.class
/pydev/

16
ahb_raster_view.py

@ -252,6 +252,20 @@ class RasterView:
composite_img = prev_parts_img.copy() composite_img = prev_parts_img.copy()
composite_img.paste(new_parts_img, None, new_parts_img) composite_img.paste(new_parts_img, None, new_parts_img)
# Optimize the image to reduce storage size
if not fast_render:
num_colors = 32
# All-or-nothing alpha: we use a white background and only make pixels fully transparent where alpha is zero, to not loose antialiasing
bg_img = Image.new(composite_img.mode, composite_img.size, color = '#ffffff')
bg_img.paste(composite_img.convert('RGB'), composite_img)
final_alpha = composite_img.split()[3].point(lambda p: 0 if p <= int(255/num_colors+0.5) else 255)
composite_img = bg_img
composite_img.putalpha(final_alpha)
# Convert to indexed colors
composite_img = composite_img.quantize(colors=num_colors, dither=Image.Dither.NONE)
finally: finally:
# restore properties on objects we have modified # restore properties on objects we have modified
for obj, props in objects_to_reset.items(): for obj, props in objects_to_reset.items():
@ -271,7 +285,7 @@ class RasterView:
# Crop the image, which is also used to deduce the center of the source view # Crop the image, which is also used to deduce the center of the source view
original_size = composite_img.size original_size = composite_img.size
diff_source_img = composite_img.split()[3] diff_source_img = composite_img.split()[-1]
bg = Image.new(diff_source_img.mode, diff_source_img.size, '#000000') # fills an image with the background color bg = Image.new(diff_source_img.mode, diff_source_img.size, '#000000') # fills an image with the background color
diff = ImageChops.difference(diff_source_img, bg) # diff between the actual image and the background color diff = ImageChops.difference(diff_source_img, bg) # diff between the actual image and the background color
bbox = diff.getbbox() # finds border size (non-black portion of the image) bbox = diff.getbbox() # finds border size (non-black portion of the image)

Loading…
Cancel
Save