【问题标题】:Saving NSImage as PNG with no alpha and 5 bit colour将 NSImage 保存为没有 alpha 和 5 位颜色的 PNG
【发布时间】:2014-02-20 08:46:47
【问题描述】:

我有一个我想保存为 PNG 的 NSImage,但删除了 alpha 通道并使用 5 位颜色。我目前正在这样做以创建我的 PNG:

NSData *imageData = [image TIFFRepresentation];
NSBitmapImageRep *imageRep = [NSBitmapImageRep imageRepWithData:imageData];

NSDictionary *imageProps = nil;
imageData = [imageRep representationUsingType:NSPNGFileType properties:imageProps];

[imageData writeToFile:fileNameWithExtension atomically:YES];

我已经阅读了很多关于 SO 的类似问题,但对最佳/正确的使用方法感到困惑。我是否创建一个新的 CGGraphics 上下文并绘制到其中?我可以直接使用这些参数创建一个新的 imageRep 吗?任何帮助,代码 sn-p 将不胜感激。

干杯

戴夫

【问题讨论】:

    标签: png quartz-graphics nsimage nsimagerep


    【解决方案1】:

    我最终做到了。对我来说看起来很丑而且闻起来很臭。任何更好的建议都非常感谢。

    // Create a graphics context (5 bits per colour, no-alpha) to render the tile
    static int const kNumberOfBitsPerColour = 5;
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef tileGraphicsContext = CGBitmapContextCreate (NULL, rect.size.width, rect.size.height, kNumberOfBitsPerColour, 2 * rect.size.width, colorSpace, kCGBitmapByteOrder16Little | kCGImageAlphaNoneSkipFirst);
    
    // Draw the clipped part of the image into the tile graphics context
    NSData *imageData = [clippedNSImage TIFFRepresentation];
    CGImageRef imageRef = [[NSBitmapImageRep imageRepWithData:imageData] CGImage];
    CGContextDrawImage(tileGraphicsContext, rect, imageRef);
    
    // Create an NSImage from the tile graphics context
    CGImageRef newImage = CGBitmapContextCreateImage(tileGraphicsContext);
    NSImage *newNSImage = [[NSImage alloc] initWithCGImage:newImage size:rect.size];
    
    // Clean up
    CGImageRelease(newImage);
    CGContextRelease(tileGraphicsContext);
    CGColorSpaceRelease(colorSpace);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-29
      • 2011-06-30
      • 1970-01-01
      • 2020-01-05
      • 1970-01-01
      • 2019-08-11
      • 2011-11-27
      • 1970-01-01
      相关资源
      最近更新 更多