def __init__(self, width, height): GPixmap.__init__(self) # ns_size = NSSize(width, height) # ns_image = NSImage.alloc().initWithSize_(ns_size) ns_image = NSImage.alloc().init() ns_image.setCacheMode_(NSImageCacheNever) row_bytes = 4 * width ns_bitmap = NSBitmapImageRep.alloc().initWithBitmapDataPlanes_pixelsWide_pixelsHigh_bitsPerSample_samplesPerPixel_hasAlpha_isPlanar_colorSpaceName_bytesPerRow_bitsPerPixel_( None, width, height, 8, 4, True, False, NSCalibratedRGBColorSpace, row_bytes, 32 ) ns_image.addRepresentation_(ns_bitmap) ns_bitmap_context = NSGraphicsContext.graphicsContextWithBitmapImageRep_(ns_bitmap) ns_graphics_context = FlippedNSGraphicsContext.alloc().initWithBase_(ns_bitmap_context) ns_tr = NSAffineTransform.transform() ns_tr.translateXBy_yBy_(0.0, height) ns_tr.scaleXBy_yBy_(1.0, -1.0) # Using __class__ to get +saveGraphicsState instead of -saveGraphicsState NSGraphicsContext.__class__.saveGraphicsState() try: NSGraphicsContext.setCurrentContext_(ns_graphics_context) ns_tr.concat() finally: NSGraphicsContext.__class__.restoreGraphicsState() self._init_with_ns_image(ns_image, flipped=True) # False) self._ns_bitmap_image_rep = ns_bitmap self._ns_graphics_context = ns_graphics_context
def generateThumbnail(self): if not self._thumbnail: if usePyObjC: from AppKit import NSBitmapImageRep, NSCalibratedRGBColorSpace, NSGraphicsContext, NSCompositeCopy, NSImage from Foundation import NSRect image = self.image rep = NSBitmapImageRep.alloc().initWithBitmapDataPlanes_pixelsWide_pixelsHigh_bitsPerSample_samplesPerPixel_hasAlpha_isPlanar_colorSpaceName_bytesPerRow_bitsPerPixel_( None, int(self.thumbnailSize), int(self.thumbnailSize), 8, 4, True, False, NSCalibratedRGBColorSpace, 0, 32, ) context = NSGraphicsContext.graphicsContextWithBitmapImageRep_(rep) oldContext = NSGraphicsContext.currentContext() NSGraphicsContext.setCurrentContext_(context) image.drawInRect_fromRect_operation_fraction_( NSRect((0, 0), (self.thumbnailSize, self.thumbnailSize)), NSRect((0, 0), image.size()), NSCompositeCopy, 1.0, ) NSGraphicsContext.setCurrentContext_(oldContext) self._thumbnail = NSImage.alloc().initWithSize_((self.thumbnailSize, self.thumbnailSize)) self._thumbnail.addRepresentation_(rep) else: import wx try: image = self.image.Scale(self.thumbnailSize, self.thumbnailSize, wx.IMAGE_QUALITY_HIGH) except AttributeError: # wx 2.6 can't do IMAGE_QUALITY_HIGH image = self.image.Scale(self.thumbnailSize, self.thumbnailSize) self._thumbnail = wx.BitmapFromImage(image) return self._thumbnail
def __init__(self, width, height): GPixmap.__init__(self) #ns_size = NSSize(width, height) #ns_image = NSImage.alloc().initWithSize_(ns_size) ns_image = NSImage.alloc().init() ns_image.setCacheMode_(NSImageCacheNever) row_bytes = 4 * width ns_bitmap = NSBitmapImageRep.alloc().\ initWithBitmapDataPlanes_pixelsWide_pixelsHigh_bitsPerSample_samplesPerPixel_hasAlpha_isPlanar_colorSpaceName_bytesPerRow_bitsPerPixel_( None, width, height, 8, 4, True, False, NSCalibratedRGBColorSpace, row_bytes, 32) ns_image.addRepresentation_(ns_bitmap) ns_bitmap_context = NSGraphicsContext.graphicsContextWithBitmapImageRep_(ns_bitmap) ns_graphics_context = FlippedNSGraphicsContext.alloc().initWithBase_(ns_bitmap_context) ns_tr = NSAffineTransform.transform() ns_tr.translateXBy_yBy_(0.0, height) ns_tr.scaleXBy_yBy_(1.0, -1.0) # Using __class__ to get +saveGraphicsState instead of -saveGraphicsState NSGraphicsContext.__class__.saveGraphicsState() try: NSGraphicsContext.setCurrentContext_(ns_graphics_context) ns_tr.concat() finally: NSGraphicsContext.__class__.restoreGraphicsState() self._init_with_ns_image(ns_image, flipped = True) #False) self._ns_bitmap_image_rep = ns_bitmap self._ns_graphics_context = ns_graphics_context
def setPixel(self, event, dragging=False): if self.data is None: return False try: editView = self.editViewController().graphicView() except: return False layer = editView.activeLayer() try: master = layer.parent.parent.masters[layer.layerId] except KeyError: return False if master is None: return False # Get location of click in font coordinates Loc = editView.getActiveLocation_(event) loc_pixel = ((Loc.x - self.rect.origin.x) / self.pixel_size, (Loc.y - self.rect.origin.y) / self.pixel_size / self.pixel_ratio) if self.prev_location != loc_pixel: x, y = loc_pixel current = NSGraphicsContext.currentContext() context = NSGraphicsContext.graphicsContextWithBitmapImageRep_( self.data) if context is None: self.prev_location = loc_pixel print("Could not get context in setPixel") return False NSGraphicsContext.saveGraphicsState() NSGraphicsContext.setCurrentContext_(context) if self.erase: NSColor.whiteColor().set() else: NSColor.blackColor().set() effective_size = self.pen_size / self.pixel_size if dragging and self.prev_location is not None: px, py = self.prev_location path = NSBezierPath.alloc().init() path.setLineCapStyle_(NSRoundLineCapStyle) path.setLineWidth_(effective_size) # path.strokeLineFromPoint_toPoint_(x, y, x + self.pen_size, y + self.pen_size) path.moveToPoint_((px, py)) path.lineToPoint_((x, y)) path.stroke() self.needs_save = True else: half = effective_size / 2 rect = NSMakeRect(x - half, y - half, effective_size, effective_size) path = NSBezierPath.bezierPathWithOvalInRect_(rect) path.fill() self.needs_save = True # For rectangular pens: # NSBezierPath.fillRect_(rect) NSGraphicsContext.setCurrentContext_(current) NSGraphicsContext.restoreGraphicsState() self.prev_location = loc_pixel return True
def toRGBA(self): if usePyObjC: from AppKit import NSBitmapImageRep, NSDeviceRGBColorSpace, NSGraphicsContext, NSCompositeCopy from Foundation import NSRect image = self.image size = image.size() rep = NSBitmapImageRep.alloc().initWithBitmapDataPlanes_pixelsWide_pixelsHigh_bitsPerSample_samplesPerPixel_hasAlpha_isPlanar_colorSpaceName_bytesPerRow_bitsPerPixel_( None, int(size.width), int(size.height), 8, 4, True, False, NSDeviceRGBColorSpace, 0, 32, ) context = NSGraphicsContext.graphicsContextWithBitmapImageRep_(rep) oldContext = NSGraphicsContext.currentContext() NSGraphicsContext.setCurrentContext_(context) oldFlipped = image.isFlipped() image.setFlipped_(True) image.drawInRect_fromRect_operation_fraction_( NSRect((0, 0), size), NSRect((0, 0), size), NSCompositeCopy, 1.0, ) image.setFlipped_(oldFlipped) NSGraphicsContext.setCurrentContext_(oldContext) # FIXME: take bytesPerRow into account data = str(rep.bitmapData()) else: image = self.image.Mirror(horizontally = False) # wxImage coordinates are flipped vertically data = list(image.GetData()) rdata = data[0::3] gdata = data[1::3] bdata = data[2::3] if image.HasAlpha(): adata = image.GetAlpha() else: adata = '\xFF' * len(rdata) data = ''.join([r + g + b + a for r, g, b, a in zip(rdata, gdata, bdata, adata)]) return data
def render(self, filename): ''' Renders the given build's build preview to an image with the given filename. ''' # Sets up a blank bitmap canvas for drawing to. Such an ugly method # call. Any easier way to do this in Obj-C? init = NSBitmapImageRep.alloc().initWithBitmapDataPlanes_pixelsWide_pixelsHigh_bitsPerSample_samplesPerPixel_hasAlpha_isPlanar_colorSpaceName_bytesPerRow_bitsPerPixel_ im = init(None, self.kpf.width, self.kpf.height, 8, 4, True, False, NSDeviceRGBColorSpace, 0, 0) # Set up the Objective-C graphics context based on the bitmap canvas # we just created context = NSGraphicsContext.graphicsContextWithBitmapImageRep_(im) context.setCompositingOperation_(NSCompositeSourceOver) NSGraphicsContext.setCurrentContext_(context) # Ask the implementation to render itself self.__render__() # Output the file imjpeg = im.representationUsingType_properties_(NSJPEGFileType, None) imjpeg.writeToFile_atomically_(filename, False)
def render(self, filename): ''' Renders the given build's build preview to an image with the given filename. ''' # Sets up a blank bitmap canvas for drawing to. Such an ugly method # call. Any easier way to do this in Obj-C? init = NSBitmapImageRep.alloc().initWithBitmapDataPlanes_pixelsWide_pixelsHigh_bitsPerSample_samplesPerPixel_hasAlpha_isPlanar_colorSpaceName_bytesPerRow_bitsPerPixel_ im = init(None, self.kpf.width, self.kpf.height, 8, 4, True, False, NSDeviceRGBColorSpace, 0, 0) # Set up the Objective-C graphics context based on the bitmap canvas # we just created context = NSGraphicsContext.graphicsContextWithBitmapImageRep_(im) context.setCompositingOperation_(NSCompositeSourceOver) NSGraphicsContext.setCurrentContext_(context) # Ask the implementation to render itself self.__render__() # Output the file imjpeg = im.representationUsingType_properties_(NSJPEGFileType, None) imjpeg.writeToFile_atomically_(filename, False)
def dt_bitmap2d_from_ci_image(ci_image, width, height, grid): """ :param ci_image: a :class:`Quartz.CIImage` instance from PyObjC :param width: desired width in pixels :param height: desired height in pixels :param grid: a four-tuple (x0, y0, dx, dy) spatial grid :returns: a :class:`datatank_py.DTBitmap2D.DTBitmap2D` instance **Requires Mac OS X and PyObjC** This function allows you to turn a :class:`Quartz.CIImage` into an object that DataTank can use. Only 8-bit RGB images are supported at this time. """ from datatank_py.DTBitmap2D import DTBitmap2D from Quartz import CGRectMake, CGPointZero from AppKit import NSBitmapImageRep, NSCalibratedRGBColorSpace, NSGraphicsContext # No matter what, I can't get NSBitmapImageRep to create a rep from planar data or # a passed-in buffer, so I have to let it manage the buffer. Constraining row bytes # seems to work properly, so at least I don't have to deal with that. I really think # PyObjC is buggy here as well. image_rep = NSBitmapImageRep.alloc().initWithBitmapDataPlanes_pixelsWide_pixelsHigh_bitsPerSample_samplesPerPixel_hasAlpha_isPlanar_colorSpaceName_bitmapFormat_bytesPerRow_bitsPerPixel_(None, width, height, 8, 4, True, False, NSCalibratedRGBColorSpace, 0, 4 * width, 32) ns_context = NSGraphicsContext.graphicsContextWithBitmapImageRep_(image_rep) ns_context.CIContext().drawImage_atPoint_fromRect_(ci_image, CGPointZero, CGRectMake(0, 0, width, height)) ns_context.flushGraphics() (red, green, blue, alpha) = __bitmap_planes_from_imagerep(image_rep) dt_bitmap = DTBitmap2D() dt_bitmap.red = red dt_bitmap.green = green dt_bitmap.blue = blue dt_bitmap.grid = grid return dt_bitmap
def initImage(layer, width, height, pixel_size=default_pixel_size, ratio=1): # See https://developer.apple.com/documentation/appkit/nsbitmapimagerep/1395538-init img = NSBitmapImageRep.alloc( ).initWithBitmapDataPlanes_pixelsWide_pixelsHigh_bitsPerSample_samplesPerPixel_hasAlpha_isPlanar_colorSpaceName_bitmapFormat_bytesPerRow_bitsPerPixel_( None, # BitmapDataPlanes int(round(width / pixel_size)), # pixelsWide int(round(height / pixel_size / ratio)), # pixelsHigh 8, # bitsPerSample: 1, 2, 4, 8, 12, or 16 1, # samplesPerPixel: 1 - 5 False, # hasAlpha False, # isPlanar NSDeviceWhiteColorSpace, # colorSpaceName # NSDeviceRGBColorSpace, 0, # bitmapFormat 0, # bytesPerRow 0, # bitsPerPixel ) """ NSCalibratedWhiteColorSpace NSCalibratedBlackColorSpace NSCalibratedRGBColorSpace NSDeviceWhiteColorSpace NSDeviceBlackColorSpace NSDeviceRGBColorSpace NSDeviceCMYKColorSpace NSNamedColorSpace NSCustomColorSpace """ # The image is filled black for some reason, make it white current = NSGraphicsContext.currentContext() context = NSGraphicsContext.graphicsContextWithBitmapImageRep_(img) NSGraphicsContext.setCurrentContext_(context) NSColor.whiteColor().set() # NSBezierPath.setLineWidth_(1) NSBezierPath.fillRect_(NSMakeRect(0, 0, width, int(round(height / ratio)))) NSGraphicsContext.setCurrentContext_(current) return img
def as_matrix(self, normalize=False, binarize=False): """Renders the glyph as a matrix. By default, the matrix values are integer pixel greyscale values in the range 0 to 255, but they can be normalized or turned into binary values with the appropriate keyword arguments. The matrix is returned as a `GlyphRendering` object which can be further manipulated.""" box_height = int(self.font.full_height_px) box_width = int(self.ink_width) b = NSBitmapImageRep.alloc( ).initWithBitmapDataPlanes_pixelsWide_pixelsHigh_bitsPerSample_samplesPerPixel_hasAlpha_isPlanar_colorSpaceName_bytesPerRow_bitsPerPixel_( None, box_width, box_height, 8, 1, False, False, NSCalibratedWhiteColorSpace, 0, 0) ctx = NSGraphicsContext.graphicsContextWithBitmapImageRep_(b) assert (ctx) NSGraphicsContext.setCurrentContext_(ctx) NSColor.whiteColor().setFill() p2 = NSBezierPath.bezierPath() p2.appendBezierPath_(self.layer.completeBezierPath) t = NSAffineTransform.transform() t.translateXBy_yBy_(-self.lsb, -self.font.descender * self.font.scale_factor) t.scaleBy_(self.font.scale_factor) p2.transformUsingAffineTransform_(t) p2.fill() png = b.representationUsingType_properties_(NSPNGFileType, None) png.writeToFile_atomically_("/tmp/foo.png", False) Z = np.array(b.bitmapData()) box_width_up = Z.shape[0] / box_height Z = Z.reshape((box_height, box_width_up))[0:box_height, 0:box_width] if normalize or binarize: Z = Z / 255.0 if binarize: Z = Z.astype(int) return GlyphRendering.init_from_numpy(self, Z)
def generateImage(self): size = self.imageSize dx, dy = self.dx, self.dy image = self.texture.image if usePyObjC: from AppKit import NSBitmapImageRep, NSCalibratedRGBColorSpace, NSGraphicsContext, NSCompositeCopy, NSImage from Foundation import NSRect rep = NSBitmapImageRep.alloc().initWithBitmapDataPlanes_pixelsWide_pixelsHigh_bitsPerSample_samplesPerPixel_hasAlpha_isPlanar_colorSpaceName_bytesPerRow_bitsPerPixel_( None, int(size), int(size), 8, 4, True, False, NSCalibratedRGBColorSpace, 0, 32, ) context = NSGraphicsContext.graphicsContextWithBitmapImageRep_(rep) oldContext = NSGraphicsContext.currentContext() NSGraphicsContext.setCurrentContext_(context) image.drawInRect_fromRect_operation_fraction_( NSRect((0, 0), (size, size)), NSRect((0, 0), image.size()), NSCompositeCopy, 1.0, ) NSGraphicsContext.setCurrentContext_(oldContext) image = NSImage.alloc().initWithSize_((size, size)) image.addRepresentation_(rep) rep = NSBitmapImageRep.alloc().initWithBitmapDataPlanes_pixelsWide_pixelsHigh_bitsPerSample_samplesPerPixel_hasAlpha_isPlanar_colorSpaceName_bytesPerRow_bitsPerPixel_( None, int(size), int(size), 8, 4, True, False, NSCalibratedRGBColorSpace, 0, 32, ) context = NSGraphicsContext.graphicsContextWithBitmapImageRep_(rep) oldContext = NSGraphicsContext.currentContext() NSGraphicsContext.setCurrentContext_(context) srcPoints = ( (0, 0), (size - dx, 0), (0, size - dy), (size - dx, size - dy), ) dstPoints = ( (dx, dy), (0, dy), (dx, 0), (0, 0), ) sizes = ( (size - dx, size - dy), (dx, size - dy), (size - dx, dy), (dx, dy), ) for src, dst, siz in zip(srcPoints, dstPoints, sizes): if siz[0] > 0 and siz[1] > 0: # not sure if Cocoa appreciates trying to draw an image with invalid bounds image.drawInRect_fromRect_operation_fraction_( NSRect(dst, siz), NSRect(src, siz), NSCompositeCopy, 1.0, ) NSGraphicsContext.setCurrentContext_(oldContext) result = NSImage.alloc().initWithSize_((size, size)) result.addRepresentation_(rep) else: import wx try: image = image.Scale(size, size, wx.IMAGE_QUALITY_HIGH) except AttributeError: # wx 2.6 can't do IMAGE_QUALITY_HIGH image = image.Scale(size, size) result = wx.BitmapFromImage(image) return result