예제 #1
0
def make_icons(c):
    """Rescale images and embed them in a python module."""
    from PIL import Image
    from PIL import ImageOps
    from wx.tools.img2py import img2py

    TARGET_SIZE = (24, 24)
    IMAGE_SOURCE_FOLDER = PROJECT_ROOT / "fullsize_images"
    PY_MODULE = PACKAGE_FOLDER / "resources" / "image_data.py"
    print(f"Rescaling images and embedding them in {PY_MODULE}")
    if PY_MODULE.exists():
        PY_MODULE.unlink()
    with TemporaryDirectory() as temp:
        for index, imgfile in enumerate(Path(IMAGE_SOURCE_FOLDER).iterdir()):
            filename, ext = os.path.splitext(imgfile.name)
            if imgfile.is_dir() or ext != ".png":
                continue
            save_target = Path(temp) / imgfile.name
            save_target_hc = Path(temp) / f"{filename}.hg{ext}"
            Image.open(imgfile).resize(TARGET_SIZE).save(save_target)
            # Create an inverted version for high contrast
            invert_image(str(imgfile)).resize(TARGET_SIZE).save(save_target_hc)
            append = bool(index)
            with redirect_stdout(StringIO()):
                img2py(
                    python_file=str(PY_MODULE),
                    image_file=str(save_target),
                    imgName=f"_{filename}",
                    append=append,
                    compressed=True,
                )
                img2py(
                    python_file=str(PY_MODULE),
                    image_file=str(save_target_hc),
                    imgName=f"_{filename}_hc",
                    append=True,
                    compressed=True,
                )
        print("*" * 10 + " Done Embedding Images" + "*" * 10)
    print("Creating installer images...")
    inst_dst = PROJECT_ROOT / "scripts" / "builder" / "assets"
    inst_imgs = {
        "bookworm.ico": ICON_SIZE,
        "bookworm.bmp": (48, 48),
        "bookworm-logo.bmp": (164, 164),
    }
    for fname, imgsize in inst_imgs.items():
        imgfile = inst_dst.joinpath(fname)
        if not imgfile.exists():
            print(f"Creating image {fname}.")
            Image.open(IMAGE_SOURCE_FOLDER / "logo" / "bookworm.png")\
            .resize(imgsize)\
            .save(imgfile)
            print(f"Copied image {fname} to the assets folder.")
    website_header = PROJECT_ROOT / "docs" / "img" / "bookworm.png"
    if not website_header.exists():
        print("Website header logo is not there, creating it.")
        Image.open(IMAGE_SOURCE_FOLDER / "logo" / "bookworm.png").resize(
            (256, 256)).save(website_header)
        print("Copied website header image  to the docs folder.")
예제 #2
0
def ConvertIcons():
	path = '.\\ico\\'
	allFiles = ListDirFiles(path)
	pyFile = os.path.join(path,'..\\FCRes.py')
	append = False
	for f in allFiles:
		fn = os.path.join(path,f)
		img2py.img2py(fn,pyFile,append=True,catalog=True,icon=True)
예제 #3
0
def convertImagesToPy(list, target):
    """
    Prend une liste de chemins d'acces a des images prealablement creee avec listImgFiles() et
    en deuxieme parametre le nom du fichier cible avec l'endroit ou il doit etre depose.
    """
    for i in range(len(list)):
        img2py.img2py(list[i], target, True)
    print "\n#############################################################"
    print "# Done converting %d files to %s." % (len(list), target)
    print "#############################################################\n"
예제 #4
0
def generateIconModule(sourcePath, outModule):
    search = os.path.join(sourcePath, "*.png")
    lst = glob.glob(search)
    splitext = os.path.splitext
    basename = os.path.basename
    i = 0
    for i, png in enumerate(lst):
        name = splitext(basename(png))[0]
        name = name.replace('-', ' ').title()
        name = name.replace(' ', '')
        img2py.img2py(png, outModule, i > 0, imgName=name)
    return i
예제 #5
0
def ConvertCardImages():
	path = '.\\res1\\'
	allFiles = ListDirFiles(path)
	pyFile = os.path.join(path,'..\\FCRes.py')
	append = False
	for f in allFiles:
		i = GetIByName(f)
		fn = os.path.join(path,f)
		if i<0:
			imagName = ''
		else:
			imagName = '%02d'%i
		img2py.img2py(fn,pyFile,append=append,catalog=True,imgName=imagName)
		append = True
예제 #6
0
def makeimage(path, write=False):
    path = os.path.abspath(path)
    im = Image.open(path)
    if 'icc_profile' in im.info:
        im.info.pop('icc_profile')
    im.save(path, 'PNG')
    image_file = path
    python_file = '.'.join((os.path.splitext(path)[0], 'py'))
    imgName = os.path.splitext(os.path.split(path)[-1])[0]
    # compatible = img2py.DEFAULT_COMPATIBLE
    img2py.img2py(image_file, python_file, append=False, imgName=imgName)
    f = open(python_file, 'rb')
    print(f.read())
    f.close()
    if write is False:
        os.remove(python_file)
예제 #7
0
def forderprocess():
    listext = ('.png', '.ico', '.icon', '.gif')
    apppath, appfilename = os.path.split(os.path.abspath(sys.argv[0]))
    pyfile = apppath + '\img.py'

    if os.path.isdir(apppath):

        for name in os.listdir(apppath):
            (x, ext) = os.path.splitext(name)

            if ext in listext:
                img = os.path.join(apppath, name)
                if os.path.isfile(pyfile):
                    ret = img2py(img, pyfile, append=True)
                else:
                    ret = img2py(img, pyfile, append=True)
예제 #8
0
파일: setup.py 프로젝트: PhotoFilmStrip/PFS
    def _make_resources(self):
        try:
            from wx.tools.img2py import img2py
        except ImportError:
            log.warn("Cannot update image resources! Using images.py from source")
            return 
        
        if sys.platform.startswith("linux") and os.getenv("DISPLAY") is None:
            log.warn("Cannot update image resources! img2py needs X")
            return 
        
        imgDir = os.path.abspath(os.path.join("res", "icons"))
        if not os.path.exists(imgDir):
            return

        target = os.path.join("photofilmstrip", "res", "images.py")
        target_mtime = os.path.getmtime(target)
        
        imgResources = (
#                        ("ALIGN_BOTTOM", "align_bottom.png"),
#                        ("ALIGN_MIDDLE", "align_middle.png"),
#                        ("ALIGN_TOP", "align_top.png"),
#                        ("ALIGN_LEFT", "align_left.png"),
#                        ("ALIGN_CENTER", "align_center.png"),
#                        ("ALIGN_RIGHT", "align_right.png"),
                        ("PLAY_PAUSE", "play_pause_16.png"),
                        ("MOTION_RIGHT", "motion_right_24.png"),
                        ("MOTION_LEFT", "motion_left_24.png"),
                        ("MOTION_SWAP", "motion_swap_24.png"),
                        ("MOTION_INPUT", "motion_input_24.png"),
                        ("MOTION_RANDOM", "motion_random_24.png"),
                        ("LOCK", "lock_24.png"),
                        ("UNLOCK", "unlock_24.png"),
                        ("ICON_32", "photofilmstrip_32.png"),
                        ("ICON_48", "photofilmstrip_48.png")
                       )
        
        for idx, (imgName, imgFile) in enumerate(imgResources):
            img2py(os.path.join(imgDir, imgFile), 
                   target, append=idx>0, 
                   imgName=imgName, 
                   icon=True, 
                   compressed=True, 
                   catalog=True)
예제 #9
0
 def start(self):
     imgFolderPath = os.path.join(
         os.path.dirname(os.path.abspath(os.path.dirname(__file__))), 'img')
     fileLists = os.listdir(imgFolderPath)
     for file in fileLists:
         fileName = os.path.splitext(file)[0]
         fileFormat = os.path.splitext(file)[1]
         imgFilePath = os.path.abspath(os.path.join(imgFolderPath, file))
         if (fileFormat == '.png') or (fileFormat == '.jpg') or (
                 fileFormat == '.ico') or (fileFormat
                                           == '.bmp') or (fileFormat
                                                          == '.gif'):
             # Don't convert image file named tinypycom.png
             if (file != 'tinypycom.png'):
                 pyFilePath = os.path.abspath(
                     os.path.join(imgFolderPath, fileName + '.py'))
                 img2py(imgFilePath, pyFilePath)
         else:
             print("Unrecognized file: %s\n" % (imgFilePath))
예제 #10
0
def convert(outputfile, dir='', imagefiles=[]):
    files = []
    files.extend(imagefiles)
    if dir:
        f = [os.path.join(dir, x) for x in os.listdir(dir) if os.path.isfile(os.path.join(dir, x))]
        files.extend(f)
    files = list(set([x for x in files if isImageFile(x)]))
    for i, x in enumerate(files):
        name = os.path.splitext(os.path.basename(x))[0].lower()
        cmd =[]
        if i != 0:
            cmd.append('-a')
        cmd.append('-n')
        cmd.append(name.capitalize())
        cmd.append(x)
        cmd.append(outputfile)
        os.system("python e:\\devtools\img2py.py %s" % " ".join(cmd)) 
        print name.capitalize(), outputfile
        img2py.img2py(x, outputfile)
예제 #11
0
#!/usr/bin/env python

import os
from wx.tools.img2py import img2py

outputFile = "./ChessImages.py"
try:
    os.remove(outputFile)
except:
    pass

for (thisDir, ignored, names) in os.walk("."):
    for x in names:
        (fileName, ext) = os.path.splitext(x)
        if ext in (".png", ".bmp"):
            img2py(x, outputFile, append=os.path.exists(outputFile), imgName=fileName.capitalize())
예제 #12
0
파일: make_images.py 프로젝트: jorgb/airs
# Copyright:   (c) Jorgen Bodde
# License:     GPLv2 (see LICENSE.txt)
#==============================================================================

import os, os.path
import wxversion
wxversion.select('2.8')
import wx

import os.path, glob
import wx.tools.img2py as i2p

image_exts = ['*.png', '*.gif', '*.bmp']
images = []
for ext in image_exts:
    images.extend(glob.glob(ext))

for name in images:
    root, ext = os.path.splitext(name)
    
    src_f = os.stat(name).st_mtime
    make_dst = True
    dst_name = root + '.py'
    if os.path.isfile(dst_name):
        dst_f = os.stat(dst_name).st_mtime
        make_dst = src_f > dst_f       # make when image is newer then python file
            
    if make_dst:
        print 'Converting', name, ' to ', root + '.py'
        i2p.img2py(name, root + '.py')
예제 #13
0
파일: images.py 프로젝트: tazjel/rad2py
if __name__=='__main__':
    import sys
    from wx.tools import img2py
    image_file = sys.argv[1]
    python_file = __file__
    img2py.img2py(image_file, python_file, append=True, compressed=True, maskClr=None,
        imgName='', icon=False, catalog=False, functionCompatible=False, functionCompatibile=0)

#----------------------------------------------------------------------
# This file was generated by encode_bitmaps.py
#
from wx import ImageFromStream, BitmapFromImage
from wx.lib.embeddedimage import PyEmbeddedImage
import wx
import cStringIO

def merge_bitmaps(image1, image2):
    #prepare blank bitmap
    bmp = wx.EmptyBitmap(16, 16)
    mem_dc = wx.MemoryDC()
    mem_dc.SelectObject(bmp)
    brush = wx.Brush('white', wx.SOLID)
    mem_dc.SetBackground(brush)
    mem_dc.Clear()
    
    mask = wx.Mask(image2, wx.WHITE)
    image2.SetMask(mask)
    
    mem_dc.DrawBitmap(image1, 0, 0, True)
    mem_dc.DrawBitmap(image2, 0, 0, True)
    
예제 #14
0
filename = 'icons.py'

import glob
from wx.tools import img2py

files = glob.glob('*.png')

open(filename, 'w').close()

for i, file in enumerate( files ) :
    append = i > 0
    img2py.img2py( file, filename, append = append, catalog = True )
예제 #15
0
파일: setup.py 프로젝트: LambdaDriver/PFS
    def _make_resources(self):
        try:
            from wx.tools.img2py import img2py
        except ImportError:
            log.warn(
                "Cannot update image resources! Using images.py from source")
            return

        if sys.platform.startswith("linux") and os.getenv("DISPLAY") is None:
            log.warn("Cannot update image resources! img2py needs X")
            return

        imgDir = os.path.abspath(os.path.join("res", "icons"))
        if not os.path.exists(imgDir):
            return

        target = os.path.join("photofilmstrip", "res", "images.py")
        target_mtime = os.path.getmtime(target)

        imgResources = (
            ("ICON_16", "photofilmstrip_16.png"),
            ("ICON_24", "photofilmstrip_24.png"),
            ("ICON_32", "photofilmstrip_32.png"),
            ("ICON_48", "photofilmstrip_48.png"),
            ("ICON_64", "photofilmstrip_64.png"),
            ("ICON_128", "photofilmstrip_128.png"),
            ("PROJECT_NEW_16", "project_new_16.png"),
            ("PROJECT_NEW_24", "project_new_24.png"),
            ("PROJECT_NEW_64", "project_new_64.png"),
            ("PROJECT_OPEN_16", "project_open_16.png"),
            ("PROJECT_OPEN_24", "project_open_24.png"),
            ("PROJECT_OPEN_64", "project_open_64.png"),
            ("PROJECT_SAVE_16", "project_save_16.png"),
            ("PROJECT_SAVE_D_16", "project_save_d_16.png"),
            ("PROJECT_SAVE_24", "project_save_24.png"),
            ("PROJECT_SAVE_D_24", "project_save_d_24.png"),
            ("PROJECT_CLOSE_16", "project_close_16.png"),
            ("PROJECT_CLOSE_D_16", "project_close_d_16.png"),
            ("FOLDER_OPEN_16", "folder_open_16.png"),
            ("FOLDER_OPEN_24", "folder_open_24.png"),
            ("MOTION_START_TO_END_24", "motion_start_to_end_24.png"),
            ("MOTION_END_TO_START_24", "motion_end_to_start_24.png"),
            ("MOTION_SWAP_24", "motion_swap_24.png"),
            ("MOTION_MANUAL_24", "motion_manual_24.png"),
            ("MOTION_MANUAL_32", "motion_manual_32.png"),
            ("MOTION_RANDOM_16", "motion_random_16.png"),
            ("MOTION_RANDOM_D_16", "motion_random_d_16.png"),
            ("MOTION_RANDOM_24", "motion_random_24.png"),
            ("MOTION_CENTER_16", "motion_center_16.png"),
            ("MOTION_CENTER_D_16", "motion_center_d_16.png"),
            ("LOCK_24", "lock_24.png"),
            ("UNLOCK_24", "unlock_24.png"),
            ("MENU_24", "menu_24.png"),
            ("ABORT_16", "abort_16.png"),
            ("ABORT_24", "abort_24.png"),
            ("LIST_REMOVE_16", "list_remove_16.png"),
            ("LIST_REMOVE_24", "list_remove_24.png"),
            ("RENDER_16", "render_16.png"),
            ("RENDER_D_16", "render_d_16.png"),
            ("RENDER_24", "render_24.png"),
            ("RENDER_D_24", "render_d_24.png"),
            ("RENDER_32", "render_32.png"),
            ("IMPORT_PICTURES_16", "import_pictures_16.png"),
            ("IMPORT_PICTURES_D_16", "import_pictures_d_16.png"),
            ("IMPORT_PICTURES_24", "import_pictures_24.png"),
            ("IMPORT_PICTURES_D_24", "import_pictures_d_24.png"),
            ("IMPORT_PICTURES_32", "import_pictures_32.png"),
            ("JOB_QUEUE_16", "job_queue_16.png"),
            ("JOB_QUEUE_D_16", "job_queue_d_16.png"),
            ("JOB_QUEUE_24", "job_queue_24.png"),
            ("JOB_QUEUE_D_24", "job_queue_d_24.png"),
            ("IMAGE_ROTATION_LEFT_16", "image_rotation_left_16.png"),
            ("IMAGE_ROTATION_LEFT_D_16", "image_rotation_left_d_16.png"),
            ("IMAGE_ROTATION_RIGHT_16", "image_rotation_right_16.png"),
            ("IMAGE_ROTATION_RIGHT_D_16", "image_rotation_right_d_16.png"),
            ("IMAGE_MOVING_LEFT_16", "image_moving_left_16.png"),
            ("IMAGE_MOVING_LEFT_D_16", "image_moving_left_d_16.png"),
            ("IMAGE_MOVING_LEFT_32", "image_moving_left_32.png"),
            ("IMAGE_MOVING_LEFT_D_32", "image_moving_left_d_32.png"),
            ("IMAGE_MOVING_RIGHT_16", "image_moving_right_16.png"),
            ("IMAGE_MOVING_RIGHT_D_16", "image_moving_right_d_16.png"),
            ("IMAGE_MOVING_RIGHT_32", "image_moving_right_32.png"),
            ("IMAGE_MOVING_RIGHT_D_32", "image_moving_right_d_32.png"),
            ("IMAGE_REMOVE_16", "image_remove_16.png"),
            ("IMAGE_REMOVE_D_16", "image_remove_d_16.png"),
            ("IMAGE_REMOVE_32", "image_remove_32.png"),
            ("IMAGE_REMOVE_D_32", "image_remove_d_32.png"),
            ("MUSIC_16", "music_16.png"),
            ("PLAY_16", "play_16.png"),
            ("PLAY_24", "play_24.png"),
            ("PLAY_PAUSE_16", "play_pause_16.png"),
            ("PLAY_PAUSE_d_16", "play_pause_d_16.png"),
            ("ARROW_UP_16", "arrow_up_16.png"),
            ("ARROW_UP_D_16", "arrow_up_d_16.png"),
            ("ARROW_DOWN_16", "arrow_down_16.png"),
            ("ARROW_DOWN_D_16", "arrow_down_d_16.png"),
            ("REMOVE_16", "remove_16.png"),
            ("REMOVE_D_16", "remove_d_16.png"),
            ("VIDEO_FORMAT_16", "video_format_16.png"),
            ("VIDEO_FORMAT_32", "video_format_32.png"),
            ("ALERT_16", "alert_16.png"),
            ("PROPERTIES_16", "properties_16.png"),
            ("EXIT_16", "exit_16.png"),
            ("HELP_16", "help_16.png"),
            ("ABOUT_16", "about_16.png"),
            ("FILMSTRIP", "filmstrip.png"),
            ("DIA", "dia.png"),
            ("DIA_S", "dia_s.png"),
        )

        for idx, (imgName, imgFile) in enumerate(imgResources):
            img2py(os.path.join(imgDir, imgFile),
                   target,
                   append=idx > 0,
                   imgName=imgName,
                   icon=True,
                   compressed=True,
                   catalog=True)
예제 #16
0
from wx.tools.img2py import img2py
import os
try:
  os.remove("evemetrics/icons.py")
except:
  pass
  
img2py('icons/ok.png', 'evemetrics/icons.py', append=True)#,compressed=True, maskClr=None, imgName='ok', icon=False, catalog=True)
img2py('icons/warning.png', 'evemetrics/icons.py', append=True)#,compressed=True, maskClr=None, imgName='warning', icon=False, catalog=True)
img2py('icons/error.png', 'evemetrics/icons.py', append=True)#,compressed=True, maskClr=None, imgName='error', icon=False, catalog=True)
img2py('icons/icon.png', 'evemetrics/icons.py', append=True)#,compressed=True, maskClr=None, imgName='error', icon=False, catalog=True)
img2py('icons/icon_ico.ico', 'evemetrics/icons.py', append=True)#,compressed=True, maskClr=None, imgName='error', icon=False, catalog=True)
def convertImagesToPy(list, target):
    for i in range(len(list)):
        img2py.img2py(list[i], target, True)
    print "\n#############################################################"
    print "Done converting %d files to %s." % (len(list), target)
    print "#############################################################\n"
예제 #18
0
#!/usr/bin/env python

import os
from wx.tools.img2py import img2py

outputFile = "./ExampleImages.py"
try:
    os.remove(outputFile)
except:
    pass

for (thisDir, ignored, names) in os.walk("."):
    for x in names:
        (fileName, ext) = os.path.splitext(x)
        if ext in (".png", ".bmp"):
            img2py(x,
                   outputFile,
                   append=os.path.exists(outputFile),
                   imgName=fileName.capitalize())
예제 #19
0
import glob
import os
from wx.tools import img2py

_imgExtensions = [
    "*.ico", "*.jpeg", "*.jpg", "*.gif", "*.xpm", "*.bmp", "*.png"
]

files = []
for imgType in _imgExtensions:
    files += glob.glob(imgType)

for python_file in ["../AllIcons.py", "../AllIcons.pyo", "../AllIcons.pyc"]:
    if os.path.isfile(python_file):
        os.remove(python_file)

python_file = "../AllIcons.py"

for fileName in files:
    append = True
    if not os.path.isfile(python_file):
        append = False

    img2py.img2py(fileName,
                  python_file,
                  append=append,
                  compressed=False,
                  catalog=True)
예제 #20
0
#! /usr/bin/env python
# -*- coding: utf-8 -*-

import base64
import os

from wx.tools.img2py import img2py

if __name__ == '__main__':
    _basePath = os.path.abspath(os.path.join(__file__, '../images'))

    # img2py(os.path.abspath(os.path.join(
    #     _basePath, 'robot-nothing.png')), os.path.abspath(os.path.join(_basePath, 'imageRobotNothing.py')))

    # img2py(os.path.abspath(os.path.join(
    #     _basePath, 'robot-text.png')), os.path.abspath(os.path.join(_basePath, 'imageRobotText.py')))

    img2py(os.path.abspath(os.path.join(_basePath, 'logo.png')),
           os.path.abspath(os.path.join(_basePath, 'logo.py')))
예제 #21
0
# License:     GPLv2 (see LICENSE.txt)
#==============================================================================

import os, os.path
import wxversion

wxversion.select('2.8')
import wx

import os.path, glob
import wx.tools.img2py as i2p

image_exts = ['*.png', '*.gif', '*.bmp']
images = []
for ext in image_exts:
    images.extend(glob.glob(ext))

for name in images:
    root, ext = os.path.splitext(name)

    src_f = os.stat(name).st_mtime
    make_dst = True
    dst_name = root + '.py'
    if os.path.isfile(dst_name):
        dst_f = os.stat(dst_name).st_mtime
        make_dst = src_f > dst_f  # make when image is newer then python file

    if make_dst:
        print 'Converting', name, ' to ', root + '.py'
        i2p.img2py(name, root + '.py')
예제 #22
0
# -*- coding:utf-8 -*-
import glob
from wx.tools.img2py import img2py


if __name__=='__main__':
    #~ img2py("img/icono.png","icono.py")
    for img in glob.glob("img/*.png"):
        img2py(img,"iconos.py", append=True)
예제 #23
0
from wx.tools.img2py import img2py

if __name__ == '__main__':
    img2py('xiaofu.ico', 'hyhr_img.py', append=True)
예제 #24
0
import os
import sys
from wx.tools.img2py import img2py as img2py

try:
    dirName = os.path.dirname(os.path.abspath(__file__))
except:
    dirName = os.path.dirname(os.path.abspath(sys.argv[0]))
    
ouputFile = os.path.join(dirName, "images.py")
    
entries = os.listdir(dirName)
imgFileExts = ["png", "gif", "jpg", "bmp"]
i = 0
for entry in entries:
    if os.path.exists(entry) and os.path.isfile(entry):
        split_name = os.path.basename(entry).split(".")
        img_name = "".join(split_name[0:-1])
        if split_name[-1] in imgFileExts:
            if i > 0:
                img2py(entry, ouputFile, True, True, None, img_name, True, True)
            else:
                img2py(entry, ouputFile, False, True, None, img_name, True, True)
            i += 1
예제 #25
0
filename = 'icons.py'

import glob
from wx.tools import img2py

files = glob.glob('*.png')

open(filename, 'w').close()

for i, file in enumerate(files):
    append = i > 0
    img2py.img2py(file, filename, append=append, catalog=True)
예제 #26
0
import glob
import os
from wx.tools import img2py

_imgExtensions = ["*.ico", "*.jpeg", "*.jpg", "*.gif", "*.xpm", "*.bmp", "*.png"]

files = []
for imgType in _imgExtensions:
    files += glob.glob(imgType)

for python_file in ["../AllIcons.py", "../AllIcons.pyo", "../AllIcons.pyc"]:
    if os.path.isfile(python_file):
        os.remove(python_file)

python_file = "../AllIcons.py"

for fileName in files:
    append = True
    if not os.path.isfile(python_file):
        append = False

    img2py.img2py(fileName, python_file, append=append, compressed=False, catalog=True)
예제 #27
0
#!/usr/bin/env python
import wx.tools.img2py as i2p
import glob
import string

resource_file = "NewResourcesToAdd.py"
print "-"*78
print "Looking for BMP and PNG files in this directory and one level down. Then converting them into a Python resource file called",resource_file,"in the current working directory."
print "."*78
extensions = ['bmp','gif'] # png files can't be loaded, but img2img.convert may be ablet to deal with them. img2png can certainly save them
directories = ['./','./*/']
files=[]
for e in extensions:
  for d in directories:
    files.extend(glob.glob(d+"*."+e)) # .extend is the same as old_list[len(old_list):]=added_list, actHL: find uses for extend() in Mesh where np.concatenate and np.append are used inneficiently
for k,f in enumerate(files):
  n = string.rfind(f, '.') # no need to check for success since *dot pattern used to create list of filenames so they will all contain at least one dot
  i2p.img2py(f, resource_file, append=bool(k), compressed=True, maskClr=None, imgName=f[0:n])#, icon=False, catalog=False, functionCompatible=True, functionCompatibile=-1)
  
예제 #28
0
def make_icons(c):
    """Rescale images and embed them in a python module."""
    from PIL import Image
    from PIL import ImageOps
    from wx.tools.img2py import img2py

    TARGET_SIZE = (24, 24)
    IMAGE_SOURCE_FOLDER = PROJECT_ROOT / "fullsize_images"
    APP_ICONS_FOLDER = IMAGE_SOURCE_FOLDER / "app_icons"
    PY_MODULE = PACKAGE_FOLDER / "resources" / "app_icons_data.py"
    print(f"Rescaling images and embedding them in {PY_MODULE}")
    if PY_MODULE.exists():
        PY_MODULE.unlink()
    with TemporaryDirectory() as temp:
        for index, imgfile in enumerate(Path(APP_ICONS_FOLDER).iterdir()):
            filename, ext = os.path.splitext(imgfile.name)
            if imgfile.is_dir() or ext != ".png":
                continue
            save_target = Path(temp) / imgfile.name
            save_target_hc = Path(temp) / f"{filename}.hg{ext}"
            Image.open(imgfile).resize(TARGET_SIZE).save(save_target)
            # Create an inverted version for high contrast
            invert_image(str(imgfile)).resize(TARGET_SIZE).save(save_target_hc)
            append = bool(index)
            with redirect_stdout(StringIO()):
                img2py(
                    python_file=str(PY_MODULE),
                    image_file=str(save_target),
                    imgName=f"_{filename}",
                    append=append,
                    compressed=True,
                )
                img2py(
                    python_file=str(PY_MODULE),
                    image_file=str(save_target_hc),
                    imgName=f"_{filename}_hc",
                    append=True,
                    compressed=True,
                )
        # Fix for some import issues with Img2Py
        imgdata_py = PY_MODULE.read_text()
        imp_statement = "from wx.lib.embeddedimage import PyEmbeddedImage"
        if imp_statement not in imgdata_py:
            PY_MODULE.write_text(f"{imp_statement}\n{imgdata_py}")
        print("*" * 10 + " Done Embedding Images" + "*" * 10)
    print("Creating installer images...")
    inst_dst = PROJECT_ROOT / "scripts" / "builder" / "assets"
    inst_imgs = {
        "bookworm.ico": ICON_SIZE,
        "bookworm.bmp": (48, 48),
    }
    if not inst_dst.exists():
        inst_dst.mkdir(parents=True, exist_ok=True)
    make_installer_image(IMAGE_SOURCE_FOLDER / "bookworm.png").save(
        inst_dst / "bookworm-logo.bmp")
    for fname, imgsize in inst_imgs.items():
        imgfile = inst_dst.joinpath(fname)
        if not imgfile.exists():
            print(f"Creating image {fname}.")
            Image.open(IMAGE_SOURCE_FOLDER /
                       "bookworm.png").resize(imgsize).save(imgfile)
            print(f"Copied image {fname} to the assets folder.")
예제 #29
0

if __name__ == "__main__":
    main()

"""

# Append should initially be False, so the file is overwritten
# and the necessary imports/declarations are made.
append = False
for file in os.listdir(base):
    name, ext = [s.lower() for s in file.split('.')]
    if ext in validExts:
        #print 'img2pying %s' % file
        try:
            img2py.img2py(os.path.join(base, file), '%s.py'%base, append=append, imgName=name, catalog=True, functionCompatible=False)
        except TypeError:
            # Try with the typo that existed in wxPython 2.8.8.0 but fixed since 2.8.8.1.
            img2py.img2py(os.path.join(base, file), '%s.py'%base, append=append, imgName=name, catalog=True, functionCompatibile=False)
        # From now on, we want to append to the original file, not overwrite.
        append = True
    else:
        print 'Ignoring %s' % file

# Fix < 2.8 compatibility by shipping embeddedimage.py.
print "Fixing compatibility with wxPython < 2.8...",
lines = open('%s.py'%base).readlines()
assert lines[3] == "from wx.lib.embeddedimage import PyEmbeddedImage\n", lines[3]
lines[3] = "from wxbanker.art.embeddedimage import PyEmbeddedImage\n"
print "fixed!"
예제 #30
0
from wx.tools import img2py
import sys
import os

library='../pydatview/icons.py'

for i,arg in enumerate(sys.argv[1:]):
    png  = arg
    name = os.path.splitext(os.path.basename(png))[0]

    img2py.img2py(image_file=png, python_file=library, imgName=name, icon=True, append=i>0)
예제 #31
0
    for name in os.listdir(folder):
        if name.endswith('.png'):
            path = os.path.join(folder, name)
            iconname = '/'.join((folder, name[:-4]))
            files[iconname] = path

for basename, names in tango.iteritems():
    for name in names:
        path = os.path.join('tango', basename, name + '.png')
        iconname = '/'.join(('tango', basename, name))
        files[iconname] = path


kwargs = dict(compressed=True,
              catalog=True,
              functionCompatible=False,
              functionCompatibile=-1)


img2py('system-icons/eelbrain/eelbrain256.png', python_file, append=False,
       imgName='eelbrain256', icon=False, **kwargs)

img2py('system-icons/eelbrain/eelbrain32.png', python_file, append=True,
       imgName='eelbrain', icon=True, **kwargs)

for name, image_file in files.iteritems():
    img2py(image_file, python_file, append=True,
           imgName=name, icon=False, **kwargs)

print("Done")
예제 #32
0
파일: icons.py 프로젝트: paulkokos/wxtruss
# -*- coding: utf-8 -*-
#
# wxtruss 0.1.1
# License: MIT License
# Author: Pedro Jorge De Los Santos
# E-mail: [email protected]

import glob
from wx.tools.img2py import img2py

if __name__ == '__main__':
    for img in glob.glob("/img/*.png"):
        img2py(img, "iconos.py", append=True)
예제 #33
0
파일: exportimages.py 프로젝트: klauer/genx
'''
A utillity that exports all png files in the scripts directory
to a python file using img2py
'''

import wx.tools.img2py as impy
import os

files = [file for file in os.listdir('.') if file[-4:] == '.png']

appending = False

for file in files:
    impy.img2py(file,
                'images.py',
                append=appending,
                imgName=file[:-4],
                functionCompatibile=True,
                functionCompatible=True)
    appending = True
예제 #34
0
types = ['*.png', '*.bmp']

pics = []
for files in types:
    # files_grabbed.extend(glob.glob(files))
    pics.extend(glob.glob(os.path.join(im_path, files)))

scr_path = os.path.join(os.getcwd(), 'images.py')
try:
    os.remove(scr_path)
    print('Deleting and recreating"', scr_path, ' "')
except:
    print('Script "', os.path.split(scr_path)[-1], '" will be created')

# Main bit: dumping image data...
for pic in pics:
    # Get filename only from full path
    _name = os.path.split(pic)[-1]
    img2py(pic, scr_path, append=True, imgName=_name, icon=True)

# ...then reload and prepend header, as wasn't working properly otherwise
_time = strftime("%d-%m-%Y %H:%M:%S", localtime())
header_text = '# HR ' + _time + '\n' \
    + '# Created with "embed_images.py"\n\n' \
    + 'from wx.lib.embeddedimage import PyEmbeddedImage\n' \
    + '\n###############################################################################\n\n'
with open(scr_path, 'r') as original:
    data = original.read()
with open(scr_path, 'w') as modified:
    modified.write(header_text + data)