Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python
- from PIL import Image as PilImage
- import sys, os.path, ConfigParser
- from Tkinter import *
- import ttk
- import tkFileDialog, tkMessageBox
- import codecs
- # Fix for Unicode Filenames ( http://habrahabr.ru/post/119405/ )
- class UnicodeConfigParser(ConfigParser.RawConfigParser):
- def __init__(self, *args, **kwargs):
- ConfigParser.RawConfigParser.__init__(self, *args, **kwargs)
- def write(self, fp):
- """Fixed for Unicode output"""
- if self._defaults:
- fp.write("[%s]\n" % DEFAULTSECT)
- for (key, value) in self._defaults.items():
- fp.write("%s = %s\n" % (key, unicode(value).replace('\n', '\n\t')))
- fp.write("\n")
- for section in self._sections:
- fp.write("[%s]\n" % section)
- for (key, value) in self._sections[section].items():
- if key != "__name__":
- fp.write("%s = %s\n" %
- (key, unicode(value).replace('\n','\n\t')))
- fp.write("\n")
- # This function is needed to override default lower-case conversion
- # of the parameter's names. They will be saved 'as is'.
- def optionxform(self, strOut):
- return strOut
- resolutions = [("", 1.0), ("@2x", 2.0), ("@3x", 3.0)]
- configFile = "config.txt"
- configSection = "configuration"
- configLastDir = "LastDir"
- imagePath = ""
- imageDir = ""
- imageName = ""
- image = None
- defWidth = defHeight = 1
- root = Tk()
- root.title("IOS ImageAsset Downsampler")
- root.resizable(0, 0)
- pyfilepath = ""
- if hasattr(sys, 'frozen'):
- pyfilepath = sys.executable
- else:
- pyfilepath = os.path.realpath(__file__)
- pyfilepath = os.path.dirname(pyfilepath)
- # iconpath = pyfilepath + "/iasdownsampler.ico"
- # if os.path.exists(iconpath):
- # root.iconbitmap(iconpath)
- widthVar = StringVar()
- heightVar = StringVar()
- suffix = StringVar()
- labelFileName = convertButton = buttonCalculateSizes = None
- configdir = os.path.expanduser("~") + "/.downsampler/"
- if not os.path.exists(configdir):
- os.makedirs(configdir)
- configpath = configdir + configFile
- def loadParameter(param, defval):
- if os.path.exists(configpath):
- parser = ConfigParser.ConfigParser()
- parser.optionxform = unicode
- parser.readfp(codecs.open(configpath, "rb", "utf8"))
- items = parser.items(configSection)
- itemsDict = dict(items)
- return itemsDict[param]
- else:
- return defval
- def storeParameter(param, value):
- parser = UnicodeConfigParser()
- if os.path.exists(configpath):
- parser.read(configpath)
- else:
- parser.add_section(configSection)
- parser.set(configSection, param, value)
- with codecs.open(configpath, "wb", "utf8") as cfile:
- parser.write(cfile)
- def onSelectFile():
- global imagePath, imageDir, imageName, image, defHeight, defWidth
- options = dict()
- options['initialdir'] = loadParameter(configLastDir, pyfilepath)
- options['title'] = 'Select original large image'
- options['filetypes'] = [('PNG files', '.png')]
- imagePath = tkFileDialog.askopenfilename(**options)
- if len(imagePath) == 0:
- return
- imageDir = os.path.dirname(imagePath)
- storeParameter(configLastDir, imageDir)
- imageName = os.path.basename(imagePath)
- image = PilImage.open(imagePath)
- defWidth, defHeight = image.size
- labelFileName["text"] = imageName + " (%dx%d)" % (defWidth, defHeight)
- convertButton["state"] = "enabled"
- buttonCalculateSizes["state"] = "enabled"
- def calculateSizes():
- if len(widthVar.get()) == 0 and len(heightVar.get()) > 0:
- height = int(heightVar.get())
- width = int(1.0 * defWidth / defHeight * height)
- widthVar.set(str(width))
- if len(widthVar.get()) > 0 and len(heightVar.get()) == 0:
- width = int(widthVar.get())
- height = int(1.0 * defHeight / defWidth * width)
- heightVar.set(str(height))
- def convert():
- if len(widthVar.get()) == 0 or len(heightVar.get()) == 0:
- tkMessageBox.showinfo("Error", "Please, specify width and height for @1x resolution")
- return
- convertButton["state"] = "disabled"
- width = int(widthVar.get())
- height = int(heightVar.get())
- sizes = {resolution[0]: (int(width * resolution[1]), int(height * resolution[1])) for resolution in resolutions}
- (imageRootName, imageExt) = os.path.splitext(imageName)
- for category, (width, height) in sizes.iteritems():
- finaldir = imageDir + "/result-images"
- if not os.path.exists(finaldir):
- os.makedirs(finaldir)
- print("Resizing for %s to %dx%d" % (category, width, height))
- imageResized = image.resize((width, height), PilImage.ANTIALIAS)
- imageResized.save(finaldir + "/" + imageRootName + category + suffix.get() + imageExt)
- convertButton["state"] = "enabled"
- labelFileName = ttk.Label(root, text = "Please, select original image")
- labelFileName.grid(row = 0, column = 0, columnspan = 2)
- buttonSelectFile = ttk.Button(root, text="Choose file...", width = 40, command = onSelectFile)
- buttonSelectFile.grid(row = 1, column = 0, columnspan = 2)
- ttk.Label(root, text = "@1x Width").grid(row = 2, column = 0)
- ttk.Label(root, text = "@1x Height").grid(row = 2, column = 1)
- textWidth = ttk.Entry(root, width = 30, textvariable = widthVar, justify = "center")
- textWidth.grid(row = 3, column = 0)
- textHeight = ttk.Entry(root, width = 30, textvariable = heightVar, justify = "center")
- textHeight.grid(row = 3, column = 1)
- buttonCalculateSizes = ttk.Button(root, text = "Width <==> Height", width = 40, command = calculateSizes)
- buttonCalculateSizes.grid(row = 4, column = 0, columnspan = 2)
- buttonCalculateSizes["state"] = "disabled"
- ttk.Label(root,
- text = "If you left width OR height empty, press button above to maintain aspect ratio").\
- grid(row = 5, column = 0, columnspan = 2)
- ttk.Checkbutton(root, text = "Add ~ipad suffix", variable = suffix,
- onvalue = "~ipad", offvalue = "").grid(row = 6, column = 0, columnspan = 2)
- convertButton = ttk.Button(root, text = "_____ DO IT _____", width = 40, command = convert)
- convertButton.grid(row = 7, column = 0, columnspan = 2)
- convertButton["state"] = "disabled"
- ttk.Label(root,
- text = "Result files will be placed to result-images folder in original image directory").\
- grid(row = 8, column = 0, columnspan = 2)
- ttk.Label(root,
- text = "Version 0.1 by Egor Aristov (ef@efprojects.com). Based on Android Drawable Downsampler").\
- grid(row = 9, column = 0, columnspan = 2)
- root.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement