typemytype / drawbot

http://www.drawbot.com
Other
408 stars 63 forks source link

support for antiAliasing while saveImage #375

Closed typemytype closed 4 years ago

typemytype commented 4 years ago

a proposal

saveImage(path, antiAliasing=False)

discussion started on forum: https://forum.drawbot.com/topic/251/turn-off-antialiasing/3

Screen Shot 2020-04-17 at 15 40 02

size(100, 100)
#fill(1)
#rect(0, 0, 100, 100)
fill(0)
oval(10, 10, 40, 80)
stroke(0)
line((-0.5, -0.5), (100.5, 100.5))
line((0, 20.5), (100, 20.5))

fontSize(10)
text("a", (62, 30))

saveImage('testAliasingNormal.png')

pdf = pdfImage()
page = pdf.pageAtIndex_(0)

import AppKit, Quartz

def _makeBitmapImageRep(image, page=None, imageResolution=72.0, colorSpaceName=AppKit.NSCalibratedRGBColorSpace, antiAliasing=True):
    """Construct a bitmap image representation at a given resolution."""
    scaleFactor = max(1.0, imageResolution) / 72.0
    rep = AppKit.NSBitmapImageRep.alloc().initWithBitmapDataPlanes_pixelsWide_pixelsHigh_bitsPerSample_samplesPerPixel_hasAlpha_isPlanar_colorSpaceName_bytesPerRow_bitsPerPixel_(
        None,                                    # planes
        int(image.size().width * scaleFactor),   # pixelsWide
        int(image.size().height * scaleFactor),  # pixelsHigh
        8,                                       # bitsPerSample
        4,                                       # samplesPerPixel
        True,                                    # hasAlpha
        False,                                   # isPlanar
        colorSpaceName,                          # colorSpaceName
        0,                                       # bytesPerRow
        0                                        # bitsPerPixel
    )
    rep.setSize_(image.size())

    AppKit.NSGraphicsContext.saveGraphicsState()
    try:
        AppKit.NSGraphicsContext.setCurrentContext_(
            AppKit.NSGraphicsContext.graphicsContextWithBitmapImageRep_(rep))
        context = AppKit.NSGraphicsContext.currentContext().CGContext()
        if not antiAliasing:
            Quartz.CGContextSetInterpolationQuality(context, Quartz.kCGInterpolationNone)
            Quartz.CGContextSetAllowsAntialiasing(context, False)
        if page is not None:
            Quartz.CGContextDrawPDFPage(context, page.pageRef())
        else:
            image.drawAtPoint_fromRect_operation_fraction_((0, 0), AppKit.NSZeroRect, AppKit.NSCompositeSourceOver, 1.0)

    finally:
        AppKit.NSGraphicsContext.restoreGraphicsState()
    return rep

pdfIm = AppKit.NSImage.alloc().initWithData_(page.dataRepresentation())

imageRep = _makeBitmapImageRep(pdfIm, page, antiAliasing=False)

imageData = imageRep.representationUsingType_properties_(AppKit.NSPNGFileType, {})
imagePath = 'testAliasingDisabled.png'
imageData.writeToFile_atomically_(imagePath, True)