NSImage to NSBitmapImageRep

后端 未结 3 1843
暗喜
暗喜 2021-02-04 06:00

How to convert NSImage to NSBitmapImageRep? I have code:

- (NSBitmapImageRep *)bitmapImageRepresentation
{
    NSBitmapImageRep *ret = (NSBitmapImageRep *)[self          


        
3条回答
  •  你的背包
    2021-02-04 06:50

    You could try this method adapted from Mike Ash's "Obtaining and Interpreting Image Data" blog post:

    - (NSBitmapImageRep *)bitmapImageRepresentation {
      int width = [self size].width;
      int height = [self size].height;
    
      if(width < 1 || height < 1)
          return nil;
    
      NSBitmapImageRep *rep = [[NSBitmapImageRep alloc]
                               initWithBitmapDataPlanes: NULL
                               pixelsWide: width
                               pixelsHigh: height
                               bitsPerSample: 8
                               samplesPerPixel: 4
                               hasAlpha: YES
                               isPlanar: NO
                               colorSpaceName: NSDeviceRGBColorSpace
                               bytesPerRow: width * 4
                               bitsPerPixel: 32];
    
      NSGraphicsContext *ctx = [NSGraphicsContext graphicsContextWithBitmapImageRep: rep];
      [NSGraphicsContext saveGraphicsState];
      [NSGraphicsContext setCurrentContext: ctx];  
      [self drawAtPoint: NSZeroPoint fromRect: NSZeroRect operation: NSCompositeCopy fraction: 1.0];
      [ctx flushGraphics];
      [NSGraphicsContext restoreGraphicsState];
    
      return [rep autorelease];
    }
    

提交回复
热议问题