Skip to content

Instantly share code, notes, and snippets.

@aspose-com-gists
Last active July 7, 2023 11:00
Compress Images in Python
from aspose.imaging.fileformats.png import PngColorType
from aspose.imaging.imageoptions import PngOptions
from aspose.imaging import ColorPaletteHelper, Image
import os
if 'TEMPLATE_DIR' in os.environ:
templates_folder = os.environ['TEMPLATE_DIR']
else:
templates_folder = r"C:\Users\USER\Downloads\templates"
delete_output = 'SAVE_OUTPUT' not in os.environ
def compress_png():
# Input and output file paths
input_file = os.path.join(templates_folder, "template.png")
output_file = os.path.join(templates_folder, "compressed_png.png")
# Load image
with Image.load(input_file) as image:
obj_init = PngOptions()
# Set compression level
obj_init.compression_level = 9
obj_init.progressive = True
obj_init.color_type = PngColorType.INDEXED_COLOR
obj_init.palette = ColorPaletteHelper.get_close_image_palette(image, 1 << 5)
# Save compressed image
image.save(output_file, obj_init)
if delete_output:
os.remove(output_file)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment