Làm thế nào để chuyển đổi NSImage sang NSBitmapImageRep? Tôi có mã:NSImage to NSBitmapImageRep
- (NSBitmapImageRep *)bitmapImageRepresentation
{
NSBitmapImageRep *ret = (NSBitmapImageRep *)[self representations];
if(![ret isKindOfClass:[NSBitmapImageRep class]])
{
ret = nil;
for(NSBitmapImageRep *rep in [self representations])
if([rep isKindOfClass:[NSBitmapImageRep class]])
{
ret = rep;
break;
}
}
if(ret == nil)
{
NSSize size = [self size];
size_t width = size.width;
size_t height = size.height;
size_t bitsPerComp = 32;
size_t bytesPerPixel = (bitsPerComp/CHAR_BIT) * 4;
size_t bytesPerRow = bytesPerPixel * width;
size_t totalBytes = height * bytesPerRow;
NSMutableData *data = [NSMutableData dataWithBytesNoCopy:calloc(totalBytes, 1) length:totalBytes freeWhenDone:YES];
CGColorSpaceRef space = CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB);
CGContextRef ctx = CGBitmapContextCreate([data mutableBytes], width, height, bitsPerComp, bytesPerRow, CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB), kCGBitmapFloatComponents | kCGImageAlphaPremultipliedLast);
if(ctx != NULL)
{
[NSGraphicsContext saveGraphicsState];
[NSGraphicsContext setCurrentContext:[NSGraphicsContext graphicsContextWithGraphicsPort:ctx flipped:[self isFlipped]]];
[self drawAtPoint:NSZeroPoint fromRect:NSZeroRect operation:NSCompositeCopy fraction:1.0];
[NSGraphicsContext restoreGraphicsState];
CGImageRef img = CGBitmapContextCreateImage(ctx);
ret = [[NSBitmapImageRep alloc] initWithCGImage:img];
[self addRepresentation:ret];
CFRelease(img);
CFRelease(space);
CGContextRelease(ctx);
}
}
return ret;
}
Nó hoạt động nhưng gây rò rỉ bộ nhớ. Ít nhất là khi tôi đang sử dụng nó với ARC. Sử dụng initWithData:[nsimagename TIFFRepresentation]
nó không hoạt động chính xác. Một số đại diện của hình ảnh không tốt. Tôi nghĩ rằng nó phụ thuộc vào định dạng và không gian màu của hình ảnh. Có cách nào khác để đạt được điều đó không?
quả với mrwalker giải pháp đề nghị:
hình ảnh gốc:
Chuyển Đổi Sang bitmapimagerep và trở lại hình ảnh 1 thời gian:
Chuyển Đổi Sang bitm apimagerep và trở lại hình ảnh 3 lần:
Như bạn thấy hình ảnh bị tối hơn mỗi lần sau khi chuyển đổi để NSBitmapImageRep
Hockeyman, bạn vẫn có giải pháp đầy đủ cho câu hỏi của bạn? Tôi đang tìm kiếm một cách để xác định màu sắc pixel mà không có quá nhiều quá trình. Có lẽ NSBitmapImageRep có thể giúp tôi bằng cách nào đó. Cảm ơn. – RickON