Skip to content

Instantly share code, notes, and snippets.

@LettError
Created November 23, 2021 21:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LettError/36665439ba4e24b45560c21026718ffb to your computer and use it in GitHub Desktop.
Save LettError/36665439ba4e24b45560c21026718ffb to your computer and use it in GitHub Desktop.
Script for Robofont - copy unreferenced images from the ufo to a new folder, then delete them from the ufo.
import os
import io
from fontParts.fontshell import RGlyph as partsGlyph
from shutil import copyfile
"""
This will cross reference the image files in <ufoname>/images
with the actual files referenced in the .glif.
Images that are not used will be copied to a new folder <ufoname>_rescued_images
and then deleted from <ufoname>/images
To prevent triggering external changes to the ufo when RF is open,
the ufo will close when deleting.
20211123
erik@letterror.com
"""
def getGlifPath(glyph):
# get glyphset for currrent layer
glyphSet = glyph.naked().layer._glyphSet
layerName = glyph.naked().layer.name
# get filename for glyph name
glifName = glyphSet.glyphNameToFileName(glyph.name, None)
# glif path = ufo path + layer folder + glif file
glifPath = os.path.join(glyph.font.path, glyphSet.dirName, glifName)
return glifPath
f = CurrentFont()
fontPath = f.path
imagesPath = os.path.join(fontPath, "images")
checked = {}
images = {}
old = []
if os.path.exists(imagesPath):
for name in os.listdir(imagesPath):
imgPath = os.path.join(imagesPath, name)
images[name] = imgPath
#print('images', images)
ts = "<image fileName=\""
for g in f:
for l in g.layers:
glifPath = getGlifPath(l)
obj = io.open(glifPath, mode="r", encoding="utf-8")
#obj = open(glifPath, 'r')
xml = obj.read()
obj.close()
start = xml.find(ts)
if start!=-1:
end = xml.find(".png\"", start)
imageFileName = xml[start+len(ts):end+4]
if imageFileName in images:
checked[imageFileName] = images[imageFileName]
for name, path in images.items():
if name not in checked:
old.append(path)
#
rescueFolder = f.path.replace(".ufo", "_rescued_images")
ext = ".png"
if not os.path.exists(rescueFolder):
os.makedirs(rescueFolder)
for imagePath in old:
imageBaseName = os.path.basename(imagePath)
dstPath = os.path.join(rescueFolder, imageBaseName)
if dstPath[-len(ext):] != ext:
dstPath += ext
copyfile(imagePath, dstPath)
# we have some images that are no longer used
# give them a new home, and delete them from the ufo
if old:
f.save()
f.close()
for imagePath in old:
os.remove(imagePath)
print(f'Rescued {len(old)} unused images from {fontPath}')
OpenFont(fontPath)
else:
print(f"Nothing to rescue from {fontPath}")
print('done')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment