def generateGif(sourcePaths, destPath, delays):
    gifsiclePath = getExternalToolPath(os.path.dirname(__file__), "gifsicle")
    assert gifsiclePath is not None
    cmds = [
        # gifsicle path
        gifsiclePath,
        # optimize level
        # "-O3",
        # ignore warnings
        "-w",
        # force to 256 colors
        "--colors",
        "256",
        # make it loop
        "--loop",
    ]
    # add source paths with delay for each frame
    for i, inputPath in enumerate(sourcePaths):
        cmds += [
            # add the frame duration
            "--delay",
            "%i" % delays[i],
            # add the input gif for each frame
            inputPath
        ]

    cmds += [
        # output path
        "--output",
        destPath
    ]
    executeExternalProcess(cmds)
    # remove the temp input gifs
    for inputPath in sourcePaths:
        os.remove(inputPath)
def generateGif(sourcePaths, destPath, delays):
    gifsiclePath = getExternalToolPath(os.path.dirname(__file__), "gifsicle")
    assert gifsiclePath is not None
    cmds = [
        # gifsicle path
        gifsiclePath,
        # optimize level
        # "-O3",
        # ignore warnings
        "-w",
        # force to 256 colors
        "--colors", "256",
        # make it loop
        "--loop",
    ]
    # add source paths with delay for each frame
    for i, inputPath in enumerate(sourcePaths):
        cmds += [
                # add the frame duration
                "--delay", "%i" % delays[i],
                # add the input gif for each frame
                inputPath
            ]

    cmds += [
        # output path
        "--output",
        destPath
    ]
    executeExternalProcess(cmds)
    # remove the temp input gifs
    for inputPath in sourcePaths:
        os.remove(inputPath)
def TraceImage(path, outPen, threshold=.2, blur=None, invert=False, turd=2, tolerance=0.2, offset=None):
    potrace = getExternalToolPath(os.path.dirname(__file__), "potrace")
    mkbitmap = getExternalToolPath(os.path.dirname(__file__), "mkbitmap")

    if isinstance(path, ImageObject):
        image = path
    else:
        image = ImageObject(path)

    x, y = image.offset()
    w, h = image.size()

    imagePath = tempfile.mktemp(".bmp")
    bitmapPath = tempfile.mktemp(".pgm")
    svgPath = tempfile.mktemp(".svg")

    saveImageAsBitmap(image, imagePath)

    assert mkbitmap is not None
    cmds = [mkbitmap, "-x", "-t", str(threshold)]
    if blur:
        cmds.extend(["-b", str(blur)])
    if invert:
        cmds.extend(["-i"])
    cmds.extend([
        # "-g",
        # "-1",
        "-o",
        bitmapPath,
        imagePath
    ])
    log = executeExternalProcess(cmds)
    if log != ('', ''):
        print(log)

    assert potrace is not None
    cmds = [potrace, "-s"]
    cmds.extend(["-t", str(turd)])
    cmds.extend(["-O", str(tolerance)])
    cmds.extend(["-o", svgPath, bitmapPath])

    log = executeExternalProcess(cmds)
    if log != ('', ''):
        print(log)

    importSVGWithPen(svgPath, outPen, (x, y, w, h), offset)

    os.remove(imagePath)
    os.remove(svgPath)
    os.remove(bitmapPath)
def TraceImage(path, outPen, threshold=.2, blur=None, invert=False, turd=2, tolerance=0.2, offset=None):
    potrace = getExternalToolPath(os.path.dirname(__file__), "potrace")
    mkbitmap = getExternalToolPath(os.path.dirname(__file__), "mkbitmap")

    if isinstance(path, ImageObject):
        image = path
    else:
        image = ImageObject(path)

    x, y = image.offset()
    w, h = image.size()

    imagePath = tempfile.mktemp(".bmp")
    bitmapPath = tempfile.mktemp(".pgm")
    svgPath = tempfile.mktemp(".svg")

    saveImageAsBitmap(image, imagePath)

    assert mkbitmap is not None
    cmds = [mkbitmap, "-x", "-t", str(threshold)]
    if blur:
        cmds.extend(["-b", str(blur)])
    if invert:
        cmds.extend(["-i"])
    cmds.extend([
        # "-g",
        # "-1",
        "-o",
        bitmapPath,
        imagePath
    ])
    log = executeExternalProcess(cmds)
    if log != ('', ''):
        print(log)

    assert potrace is not None
    cmds = [potrace, "-s"]
    cmds.extend(["-t", str(turd)])
    cmds.extend(["-O", str(tolerance)])
    cmds.extend(["-o", svgPath, bitmapPath])

    log = executeExternalProcess(cmds)
    if log != ('', ''):
        print(log)

    importSVGWithPen(svgPath, outPen, (x, y, w, h), offset)

    os.remove(imagePath)
    os.remove(svgPath)
    os.remove(bitmapPath)
def generateMP4(imageTemplate, mp4path, frameRate, codec="libx264"):
    ffmpegPath = getExternalToolPath(os.path.dirname(__file__), "ffmpeg")
    assert ffmpegPath is not None
    cmds = [
        # ffmpeg path
        ffmpegPath,
        "-y",                   # overwrite existing files
        "-loglevel", "16",      # 'error, 16' Show all errors, including ones which can be recovered from.
        "-r", str(frameRate),   # frame rate
        "-i", imageTemplate,    # input sequence
        "-c:v", codec,          # codec
        "-crf", "20",           # Constant Rate Factor
        "-pix_fmt", "yuv420p",  # pixel format
        mp4path,                # output path
    ]
    executeExternalProcess(cmds)
def _explodeGif(path):
    gifsiclePath = getExternalToolPath(os.path.dirname(__file__), "gifsicle")
    if isinstance(path, AppKit.NSURL):
        path = path.path()
    destRoot = tempfile.mkdtemp()
    cmds = [
        gifsiclePath,
        # explode
        "--explode",
        # source path
        path
    ]
    executeExternalProcess(cmds, cwd=destRoot)
    files = os.listdir(destRoot)
    _explodedGifCache[path] = dict(
        source=destRoot,
        fileNames=files,
    )
def _explodeGif(path):
    gifsiclePath = getExternalToolPath(os.path.dirname(__file__), "gifsicle")
    if isinstance(path, AppKit.NSURL):
        path = path.path()
    destRoot = tempfile.mkdtemp()
    cmds = [
        gifsiclePath,
        # explode
        "--explode",
        # source path
        path
    ]
    executeExternalProcess(cmds, cwd=destRoot)
    files = os.listdir(destRoot)
    _explodedGifCache[path] = dict(
        source=destRoot,
        fileNames=files,
    )
示例#8
0
 def _writeDataToFile(self, data, path, options):
     # create a iconset folder
     iconsetPath = tempfile.mkdtemp(suffix=".iconset")
     try:
         # get the complete pdf
         pdfDocument = Quartz.PDFDocument.alloc().initWithData_(data)
         pageCount = pdfDocument.pageCount()
         # set the image resolution
         options["imageResolution"] = 72
         # make a copy and alter the resolution
         options_2x = dict(options)
         options_2x["imageResolution"] = 144
         # start loop over all pages
         for index in range(pageCount):
             # get the pdf page
             page = pdfDocument.pageAtIndex_(index)
             # get the pdf page, this acts also as pdf document...
             pageData = page.dataRepresentation()
             # extract the size of the page
             _, (w, h) = page.boundsForBox_(Quartz.kPDFDisplayBoxArtBox)
             w = int(round(w))
             h = int(round(h))
             # dont allow any other size, the command iconutil will not work otherwise
             if w not in self.allowedPageSizes or w != h:
                 raise DrawBotError(
                     "The .icns can not be build with the size '%sx%s'. Must be either: %s"
                     % (w, h, ", ".join(
                         ["%sx%s" % (i, i)
                          for i in self.allowedPageSizes])))
             # generate a 72 dpi png in the iconset path
             pngPath = os.path.join(iconsetPath, "icon_%sx%s.png" % (w, h))
             super(ICNSContext,
                   self)._writeDataToFile(pageData, pngPath, options)
             # generate a 144 dpi png in the iconset path
             pngPath_2x = os.path.join(iconsetPath,
                                       "*****@*****.**" % (w, h))
             super(ICNSContext,
                   self)._writeDataToFile(pageData, pngPath_2x, options_2x)
         # collect all iconutil commands
         cmds = [
             "iconutil",
             "--convert",
             "icns",
             "--output",
             path,
             iconsetPath,
         ]
         # execute the commands
         stdout, stderr = executeExternalProcess(cmds)
     finally:
         # always remove the iconset
         shutil.rmtree(iconsetPath)
示例#9
0
def generateMP4(imageTemplate, mp4path, frameRate):
    ffmpegPath = getExternalToolPath(os.path.dirname(__file__), "ffmpeg")
    assert ffmpegPath is not None
    cmds = [
        # ffmpeg path
        ffmpegPath,
        "-y",  # overwrite existing files
        "-loglevel",
        "16",  # 'error, 16' Show all errors, including ones which can be recovered from.
        "-r",
        str(frameRate),  # frame rate
        "-i",
        imageTemplate,  # input sequence
        "-c:v",
        "libx264",  # codec
        "-crf",
        "20",  # Constant Rate Factor
        "-pix_fmt",
        "yuv420p",  # pixel format
        mp4path,  # output path
    ]
    executeExternalProcess(cmds)
 def _writeDataToFile(self, data, path, options):
     # create a iconset folder
     iconsetPath = tempfile.mkdtemp(suffix=".iconset")
     try:
         # get the complete pdf
         pdfDocument = Quartz.PDFDocument.alloc().initWithData_(data)
         pageCount = pdfDocument.pageCount()
         # set the image resolution
         options["imageResolution"] = 72
         # make a copy and alter the resolution
         options_2x = dict(options)
         options_2x["imageResolution"] = 144
         # start loop over all pages
         for index in range(pageCount):
             # get the pdf page
             page = pdfDocument.pageAtIndex_(index)
             # get the pdf page, this acts also as pdf document...
             pageData = page.dataRepresentation()
             # extract the size of the page
             _, (w, h) = page.boundsForBox_(Quartz.kPDFDisplayBoxArtBox)
             w = int(round(w))
             h = int(round(h))
             # dont allow any other size, the command iconutil will not work otherwise
             if w not in self.allowedPageSizes or w != h:
                 raise DrawBotError("The .icns can not be build with the size '%sx%s'. Must be either: %s" % (w, h, ", ".join(["%sx%s" % (i, i) for i in self.allowedPageSizes])))
             # generate a 72 dpi png in the iconset path
             pngPath = os.path.join(iconsetPath, "icon_%sx%s.png" % (w, h))
             super(ICNSContext, self)._writeDataToFile(pageData, pngPath, options)
             # generate a 144 dpi png in the iconset path
             pngPath_2x = os.path.join(iconsetPath, "*****@*****.**" % (w, h))
             super(ICNSContext, self)._writeDataToFile(pageData, pngPath_2x, options_2x)
         # collect all iconutil commands
         cmds = [
             "iconutil",
             "--convert",
             "icns",
             "--output",
             path,
             iconsetPath,
         ]
         # execute the commands
         stdout, stderr = executeExternalProcess(cmds)
     finally:
         # always remove the iconset
         shutil.rmtree(iconsetPath)