Skip to content

Instantly share code, notes, and snippets.

@crash-horror
Last active May 22, 2018 09:16
Show Gist options
  • Save crash-horror/002c80e384972de9fd7c1ac86b22ddd4 to your computer and use it in GitHub Desktop.
Save crash-horror/002c80e384972de9fd7c1ac86b22ddd4 to your computer and use it in GitHub Desktop.
A simple script to mass (or not so mass) convert PNG to ICO files.
#!/usr/bin/env python3
# png2ico.py
# github.com/crash-horror
"""
A simple script to mass convert PNG to ICO files.
It is not a command line script, it will open simple
UI dialogs using tkinter. It will ask for multiple input files,
if you select at least one, it will ask you for a
destination folder to save the target ICO files.
If you select one the process will begin and the files
will be created. Nothing happens to the source PNGs.
This script will not delete anything.
You will need:
* pillow
* tqdm
external python modules.
"""
import os
import sys
from tkinter import Tk
from tkinter.filedialog import askopenfilenames, askdirectory
from multiprocessing.dummy import Pool as ThreadPool
from tqdm import tqdm
from PIL import Image
# get user's home folder
HOMEDIR = os.path.expanduser("~")
# hide main tkinter window
root = Tk()
root.withdraw()
# ask source png files
print('Hello: Select PNG files. ')
pngfiletuple = askopenfilenames(title="Select Multiple PNG files",
initialdir=HOMEDIR, filetypes=(
("PNG files", "*.png"), ("All the other boring files", "*.*")))
# quit if cancel pressed
if not pngfiletuple:
print('Exiting: No files present.')
sys.exit()
# spit out list of selected file paths
for i in tqdm(pngfiletuple):
tqdm.write(i)
# ask destination directory
savedirectory = askdirectory(title="Select folder to save ICO files")
# quit if cancel pressed
if not savedirectory:
print('Exiting: No output folder selected.')
sys.exit()
# run through the files, use tqdm to print a progress bar
# single thread for small number of files (<100)
def run_single_thread():
for png in tqdm(pngfiletuple):
img = Image.open(png)
outpath = os.path.join(savedirectory, os.path.basename(png)) + '.ico'
tqdm.write(outpath)
img.save(outpath)
# run through the files, use tqdm to print a progress bar
# 16 threads for large number of files (>100)
def run_multiple_threads():
def a_thread(png):
img = Image.open(png)
outpath = os.path.join(savedirectory, os.path.basename(png)) + '.ico'
tqdm.write(outpath)
img.save(outpath)
pool = ThreadPool(16)
pool.map(a_thread, tqdm(pngfiletuple))
pool.close()
pool.join()
# if more than 100 files to process, use multiple threads
if len(pngfiletuple) > 100:
run_multiple_threads()
else:
run_single_thread()
# success
print('Exiting: Process complete.')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment