2011-08-24 49 views
1

讀我有一個NSBitmapImageRep,我創建方式如下:NSBitmapImageRep產生BMP不能在Windows

+ (NSBitmapImageRep *)bitmapRepOfImage:(NSURL *)imageURL { 
    CIImage *anImage = [CIImage imageWithContentsOfURL:imageURL]; 
    CGRect outputExtent = [anImage extent]; 

    NSBitmapImageRep *theBitMapToBeSaved = [[NSBitmapImageRep alloc] 
             initWithBitmapDataPlanes:NULL pixelsWide:outputExtent.size.width 
             pixelsHigh:outputExtent.size.height bitsPerSample:8 samplesPerPixel:4 
             hasAlpha:YES isPlanar:NO colorSpaceName:NSDeviceRGBColorSpace 
             bytesPerRow:0 bitsPerPixel:0]; 

    NSGraphicsContext *nsContext = [NSGraphicsContext graphicsContextWithBitmapImageRep:theBitMapToBeSaved]; 

    [NSGraphicsContext saveGraphicsState]; 
    [NSGraphicsContext setCurrentContext: nsContext]; 
    CGPoint p = CGPointMake(0.0, 0.0); 

    [[nsContext CIContext] drawImage:anImage atPoint:p fromRect:outputExtent]; 

    [NSGraphicsContext restoreGraphicsState]; 

    return [[theBitMapToBeSaved retain] autorelease]; 
} 

而且被保存爲BMP這樣:

NSBitmapImageRep *original = [imageTools bitmapRepOfImage:fileURL]; 
NSData *converted = [original representationUsingType:NSBMPFileType properties:nil]; 
[converted writeToFile:filePath atomically:YES]; 

的東西在這裏是BMP文件可以在Mac OSX下正確讀取和操作,但在Windows下,它只是無法加載,就像在此屏幕截圖中一樣:

screenshot http://dl.dropbox.com/u/1661304/Grab/74a6dadb770654213cdd9290f0131880.png

如果使用MS Paint打開文件(是的,MS Paint可以打開它),然後重新保存,但它將起作用。

希望能在這裏找到一隻手。 :)

在此先感謝。

回答

0

我認爲你的代碼失敗的主要原因是你正在創建你的NSBitmapImageRep每像素0位。這意味着您的圖像代表將具有精確的零信息。你幾乎可以肯定每像素需要32位。

然而,你的代碼是從磁盤上的圖像文件獲得NSBitmapImageRep難以置信令人費解的方式。爲什麼你在使用CIImage?這是設計用於核心圖像過濾器的核心圖像對象,根本沒有意義。您應該使用NSImageCGImageRef

您的方法名稱也很差。它應該改爲像+bitmapRepForImageFileAtURL:這樣的名稱,以更好地表明它在做什麼。

而且,這個代碼是沒有意義的:

[[theBitMapToBeSaved retain] autorelease] 

調用retain然後autorelease什麼都不做,因爲所有它的增量保持數,然後立即再次遞減它。

您有責任釋放theBitMapToBeSaved,因爲您是使用alloc創建的。由於它正在返回,您應該打電話給autorelease。您額外撥打retain只是導致無緣無故的泄漏。

試試這個:

+ (NSBitmapImageRep*)bitmapRepForImageFileAtURL:(NSURL*)imageURL 
{ 
    NSImage* image = [[[NSImage alloc] initWithContentsOfURL:imageURL] autorelease]; 
    return [NSBitmapImageRep imageRepWithData:[image TIFFRepresentation]]; 
} 

+ (NSData*)BMPDataForImageFileAtURL:(NSURL*)imageURL 
{ 
    NSBitmapImageRep* bitmap = [self bitmapRepForImageFileAtURL:imageURL]; 
    return [bitmap representationUsingType:NSBMPFileType properties:nil]; 
} 

你真的需要檢討Cocoa Drawing GuideMemory Management Guidelines,因爲它看來,您有一些基本概念的麻煩。

+0

您好,首先感謝您的幫助。你是對的,保留] autorelease]根本沒有意義。你的代碼似乎比我以前的代碼好多了。唯一的問題是,BMP的內置文件查看器仍然無法打開,與上面相同的錯誤。 (你可能還想修復你的第二個方法,以防有人想使用它。你不能調用self,因爲對象沒有被分配,fileURL應該是imageURL)。 – MegaEduX

+0

你*可以*調用self,因爲它是調用另一個類方法的類方法。 –

+0

噢,我想我一直在學習。知道怎麼了BMP問題? – MegaEduX