Skip to content

Instantly share code, notes, and snippets.

@prabhatsdp
Created February 6, 2024 14:37
Show Gist options
  • Save prabhatsdp/620f79a7173aab9ed3cc62af80ead0b0 to your computer and use it in GitHub Desktop.
Save prabhatsdp/620f79a7173aab9ed3cc62af80ead0b0 to your computer and use it in GitHub Desktop.
Python script to resize 4x PNG image to multi density for Android.
import argparse
from PIL import Image
import os
# Create a dictionary to store the multipliers for density suffixes
density_multipliers = {
'-ldpi': 0.75,
'-mdpi': 1.0,
'-hdpi': 1.5,
'-xhdpi': 2.0,
'-xxhdpi': 3.0,
'-xxxhdpi': 4.0
}
# Create an ArgumentParser
parser = argparse.ArgumentParser(description='Resize and rename an image based on scaling factor')
# Add an argument for the image file name
parser.add_argument('image_file', help='Input image file name')
# Parse the command-line arguments
args = parser.parse_args()
# Open the image file
image = Image.open(args.image_file)
# Define the density suffixes
suffixes = list(density_multipliers.keys())
# Create resized images for each density suffix
for suffix in suffixes:
width, height = image.size
w = (width / 4) * density_multipliers[suffix]
h = (height / 4) * density_multipliers[suffix]
resized_image = image.resize((int(w), int(h)), Image.ANTIALIAS)
# Construct the new filename with the density suffix
base_filename, file_extension = os.path.splitext(args.image_file)
filename_splitted = base_filename.split("/")
new_name = filename_splitted[-1]
output_dir_suffix = f'drawable{suffix}'
output_dir_full = os.path.join(new_name, output_dir_suffix)
if not os.path.exists(output_dir_full):
os.makedirs(output_dir_full)
output_path = os.path.join(output_dir_full, f'{new_name}{file_extension}')
# Save the resized image with the new filename
resized_image.save(output_path)
# Close the original image
image.close()
print('Image generated successfully')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment