0

I'm building an OS X app that needs to save the file to disk.

I'm currently using NSBitmapImageRep to represent the image in my code, and while saving the image to disk with representationUsingType:properties: method, I want to set the hasAlpha channel for the image, but the properties dictionary does not seem to support this.
So, I've tried to create a no-alpha bitmap representation, but according to many SO questions, the 3 channel/24 bits combination is not supported. Well, what should I do then?

Big thanks!

Jay
  • 6,572
  • 3
  • 37
  • 65
Void Main
  • 2,241
  • 3
  • 27
  • 36

2 Answers2

1

First off, I would try just making sure you create your NSBitmapImageRep with

-initWithBitmapDataPlanes:... hasAlpha:NO ...

And write it out and see if it the result doesn’t have alpha—one would kind of hope so.

If you’re trying to write out an image that has alpha, but not write the alpha, just copy it into a non-alpha image first, and write that out.

Wil Shipley
  • 9,343
  • 35
  • 59
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

iHTCboy
  • 2,715
  • 21
  • 20