Skip to content

Instantly share code, notes, and snippets.

@pudquick
Created January 10, 2018 17:58
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save pudquick/1edd0d5e6c1ca5a1486bf727d071664e to your computer and use it in GitHub Desktop.
Save pudquick/1edd0d5e6c1ca5a1486bf727d071664e to your computer and use it in GitHub Desktop.
A variation on https://scriptingosx.com/2018/01/get-an-icon-for-your-mac/ that doesn't attempt to contact WindowServer / trigger errors
#!/usr/bin/python
from Foundation import NSZeroRect, NSMakeRect, NSMakeSize
from AppKit import NSPNGFileType, NSCompositeCopy, NSGraphicsContext, NSCalibratedRGBColorSpace, NSBitmapImageRep, NSImage, NSImageNameComputer
dimension = 512
size = NSMakeSize(dimension, dimension)
rect = NSMakeRect(0, 0, dimension, dimension)
image = NSImage.imageNamed_(NSImageNameComputer)
image.setSize_(size)
rep = NSBitmapImageRep.alloc()
rep.initWithBitmapDataPlanes_pixelsWide_pixelsHigh_bitsPerSample_samplesPerPixel_hasAlpha_isPlanar_colorSpaceName_bytesPerRow_bitsPerPixel_(None, dimension, dimension, 8, 4, True, False, NSCalibratedRGBColorSpace, 0, 0)
rep.setSize_(size)
NSGraphicsContext.saveGraphicsState()
NSGraphicsContext.setCurrentContext_(NSGraphicsContext.graphicsContextWithBitmapImageRep_(rep))
image.drawInRect_fromRect_operation_fraction_(rect, NSZeroRect, NSCompositeCopy, 1.0)
NSGraphicsContext.restoreGraphicsState()
pngData = rep.representationUsingType_properties_(NSPNGFileType, None)
pngData.writeToFile_atomically_("computer.png", True)
@pudquick
Copy link
Author

Another variation, but due to still using CGImageRef, causes some pointer warnings (though doesn't contact the WindowServer)

#!/usr/bin/python

from Foundation import NSZeroRect, NSMakeRect, NSMakeSize
from AppKit import NSPNGFileType, NSCompositeCopy, NSGraphicsContext, NSCalibratedRGBColorSpace, NSBitmapImageRep, NSImage, NSImageNameComputer
from objc import NULL

dimension = 512
size = NSMakeSize(dimension, dimension)
             
image = NSImage.imageNamed_(NSImageNameComputer)
image.setSize_(size)

rep = NSBitmapImageRep.alloc()
rep.initWithBitmapDataPlanes_pixelsWide_pixelsHigh_bitsPerSample_samplesPerPixel_hasAlpha_isPlanar_colorSpaceName_bytesPerRow_bitsPerPixel_(None, dimension, dimension, 8, 4, True, False, NSCalibratedRGBColorSpace, 0, 0)
rep.setSize_(size)

cgRef, rect = image.CGImageForProposedRect_context_hints_(NULL, NSGraphicsContext.graphicsContextWithBitmapImageRep_(rep), None)
imageRep = NSBitmapImageRep.alloc().initWithCGImage_(cgRef)
imageRep.setSize_(image.size())
pngData = imageRep.representationUsingType_properties_(NSPNGFileType, None)

pngData.writeToFile_atomically_("computer.png", True)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment