OS X - 如何在没有alpha通道的情况下将NSImage或NSBitmapImageRep保存到PNG文件?

时间:2014-01-25 07:32:45

标签: objective-c macos cocoa nsimage nsbitmapimagerep

我正在构建一个需要将文件保存到磁盘的OS X应用程序。

我目前正在使用NSBitmapImageRep代表我的代码中的图片,在使用representationUsingType:properties:方法将图片保存到磁盘时,我想为图片设置hasAlpha频道,但properties词典似乎不支持这一点 所以,我试图创建一个 no-alpha 位图表示,但根据许多SO问题,不支持3通道/ 24位组合。那么,我该怎么做呢?

非常感谢!

2 个答案:

答案 0 :(得分:1)

首先,我会尝试确保使用

创建NSBitmapImageRep
-initWithBitmapDataPlanes:... hasAlpha:NO ...

并写出来,看看结果是否没有alpha-one会有所希望。

如果您正在尝试写出具有alpha但未写入alpha的图像,请先将其复制到非alpha图像中,然后将其写出来。

答案 1 :(得分:0)

`

    NSURL *url = [NSURL fileURLWithPath:name];
    CGImageSourceRef source;
    NSImage *srcImage =[[NSImage alloc] initWithContentsOfURL:url];;
    NSLog(@"URL: %@",url);
    source = CGImageSourceCreateWithData((__bridge CFDataRef)[srcImage TIFFRepresentation], NULL);
    CGImageRef imageRef =  CGImageSourceCreateImageAtIndex(source, 0, NULL);
    CGRect rect = CGRectMake(0.f, 0.f, CGImageGetWidth(imageRef), CGImageGetHeight(imageRef));
    CGContextRef bitmapContext = CGBitmapContextCreate(NULL,
                                                       rect.size.width,
                                                       rect.size.height,
                                                       CGImageGetBitsPerComponent(imageRef),
                                                       CGImageGetBytesPerRow(imageRef),
                                                       CGImageGetColorSpace(imageRef),
                                                       kCGImageAlphaNoneSkipLast | kCGBitmapByteOrder32Little
                                                       );

    CGContextDrawImage(bitmapContext, rect, imageRef);

    CGImageRef decompressedImageRef = CGBitmapContextCreateImage(bitmapContext);

    NSImage *finalImage = [[NSImage alloc] initWithCGImage:decompressedImageRef size:NSZeroSize];
    NSData *imageData = [finalImage  TIFFRepresentation];
    NSBitmapImageRep *imageRep = [NSBitmapImageRep imageRepWithData:imageData];
    NSDictionary *imageProps = [NSDictionary dictionaryWithObject:[NSNumber numberWithFloat:0.9] forKey:NSImageCompressionFactor];
    imageData = [imageRep representationUsingType:NSPNGFileType properties:imageProps];
    [imageData writeToFile:name atomically:NO];



    CGImageRelease(decompressedImageRef);
    CGContextRelease(bitmapContext);

`

REF: https://github.com/bpolat/Alpha-Channel-Remover

相关问题