1

やあみんな!ここでの最初の投稿です。

私はobjective-cにまったく慣れていないので、私の質問はそれほど難しくないかもしれませんが、それは私にとって問題です。Webを検索しましたが、役立つヒントは見つかりませんでした...XcodeのObjective-cでプログラムを作成しています。pgmファイル(ピクセルあたり2バイトのP5)を読み取って表示する必要があります。それを行うために私はサブクラス化しようとしてNSImageRepいますが、このファイルに適切なビットマップを作成する方法とそれを描画する方法がわかりません。以下はこれまでの私のコードです:

ヘッダ:

@interface CTPWTPGMImageRep : NSImageRep

@property (readonly)NSInteger width;
@property (readonly)NSInteger height;
@property (readonly)NSInteger maxValue;

+ (void)load;
+ (NSArray *)imageUnfilteredTypes;
+ (NSArray *)imageUnfilteredFileTypes;
+ (BOOL)canInitWithData:(NSData *)data;
+ (id)imageRepWithContentsOfFile:(NSString*)file;
+ (id)imageRepWithData:(NSData*)pgmData;

- (id)initWithData:(NSData *)data;
- (BOOL)draw;

@end

および実装:

#import "CTPWTPGMImageRep.h"

@implementation CTPWTPGMImageRep

@synthesize width;
@synthesize height;
@synthesize maxValue;

#pragma mark - class methods
+(void) load
{
    NSLog(@"Called 'load' method for CTPWTPGMImageRep");
    [NSImageRep registerImageRepClass:[CTPWTPGMImageRep class]];
}

+ (NSArray *)imageUnfilteredTypes
{    
    // This is a UTI
    NSLog(@"imageUnfilteredTypes called");
    static NSArray *types = nil;
    if (!types) {
        types = [[NSArray alloc] initWithObjects:@"public.unix-executable", @"public.data", @"public.item", @"public.executable", nil];
    }

    return types;
}

+ (NSArray *)imageUnfilteredFileTypes
{
    // This is a filename suffix
    NSLog(@"imageUnfilteredFileTypes called");

    static NSArray *types = nil;
    if (!types)
        types = [[NSArray alloc] initWithObjects:@"pgm", @"PGM", nil];
    return types;
}

+ (BOOL)canInitWithData:(NSData *)data;
{
    // FIX IT
    NSLog(@"canInitWithData called");
    if ([data length] >= 2) // First two bytes for magic number magic number
    {
        NSString *magicNumber = @"P5";
        const unsigned char *mNum = (const unsigned char *)[magicNumber UTF8String];
        unsigned char aBuffer[2];
        [data getBytes:aBuffer length:2];
        if(memcmp(mNum, aBuffer, 2) == 0)
        {
            NSLog(@"canInitWithData: YES");
            return YES;
        }
    }
    NSLog(@"canInitWithData: NO");

    // end
    return NO;
}

+ (id)imageRepWithContentsOfFile:(NSString*)file {
    NSLog(@"imageRepWithContentsOfFile called");
    NSData* data = [NSData dataWithContentsOfFile:file];
    if (data)
        return [CTPWTPGMImageRep imageRepWithData:data];
    return nil;
 }

+ (id)imageRepWithData:(NSData*)pgmData {
    NSLog(@"imageRepWithData called");
    return [[self alloc] initWithData:pgmData];
}


#pragma mark - instance methods

- (id)initWithData:(NSData *)data;
{
    NSLog(@"initWithData called");
    self = [super init];

    if (!self)
    {
        return nil;
    }

    if ([data length] >= 2) {
        NSString *magicNumberP5 = @"P5";
        const unsigned char *mnP5 = (const unsigned char *)[magicNumberP5 UTF8String];
        unsigned char headerBuffer[20];
        [data getBytes:headerBuffer length:2];

        if(memcmp(mnP5, headerBuffer, 2) == 0)
        {
            NSArray *pgmParameters = [self calculatePgmParameters:data beginingByte:3];
            width = [[pgmParameters objectAtIndex:0] integerValue];
            height = [[pgmParameters objectAtIndex:1] integerValue];
            maxValue = [[pgmParameters objectAtIndex:2] integerValue];

            if (width <= 0 || height <= 0)
            {
                NSLog(@"Invalid image size: Both width and height must be > 0");
                return nil;
            }

            [self setPixelsWide:width];
            [self setPixelsHigh:height];
            [self setSize:NSMakeSize(width, height)];
            [self setColorSpaceName:NSDeviceWhiteColorSpace];
            [self setBitsPerSample:16];
            [self setAlpha:NO];
            [self setOpaque:NO];

            //What to do here?
            //CTPWTPGMImageRep *imageRep = 
              [NSBitmapImageRep alloc] initWithBitmapDataPlanes:];

            //if (imageRep) {
            /* code to populate the pixel map */
            //}
        }
        else
        {
            NSLog(@"It is not supported pgm file format.");
        }
    }
    return self;
  //return imageRep;
}

- (BOOL)draw
{
    NSLog(@"draw method1 called");
    return NO;
}

私のcanInitWithData:メソッドが呼び出されないのは興味深いことです。ビットマップを賢く読む方法のヒントを教えてください。使う必要があると思いますが、使い方initWithBitmapDataPlanes:pixelsWide:pixelsHigh:bitsPerSample:samplesPerPixel:hasAlpha:isPlanar:colorSpaceName:bytesPerRow:bitsPerPixel:がわかりません。NSDataオブジェクトからスマート作成(unsigned char **)平面を作成するにはどうすればよいですか?必要ですか?

白とアルファの成分を持っているものを使用NSDeviceWhiteColorSpaceしてもいいですか(アルファは必要ありません)

[self setColorSpaceName:NSDeviceWhiteColorSpace];

そして最も難しい部分-描画メソッドを実装する方法がまったくわかりません。何か推測やヒントはありますか?

よろしくお願いします。

編集:

Ok。これで、NSGodの指示に従って実装できました。

@implementation CTPWTPGMImageRep

//@synthesize width;
//@synthesize height;

#pragma mark - class methods

+(void) load
{
    NSLog(@"Called 'load' method for CTPWTPGMImageRep");
    [NSBitmapImageRep registerImageRepClass:[CTPWTPGMImageRep class]];
}

+ (NSArray *)imageUnfilteredTypes
{
    // This is a UTI
    NSLog(@"imageUnfilteredTypes called");
    static NSArray *types = nil;
    if (!types) {
        types = [[NSArray alloc] initWithObjects:@"public.unix-executable", @"public.data", @"public.item", @"public.executable", nil];
    }

    return types;
}

+ (NSArray *)imageUnfilteredFileTypes
{
    // This is a filename suffix
    NSLog(@"imageUnfilteredFileTypes called");

    static NSArray *types = nil;
    if (!types)
        types = [[NSArray alloc] initWithObjects:@"pgm", nil];
    return types;
}

+ (NSArray *)imageRepsWithData:(NSData *)data {
    NSLog(@"imageRepsWithData called");
    id imageRep = [[self class] imageRepWithData:data];
    return [NSArray arrayWithObject:imageRep];
}

- (id)initWithData:(NSData *)data {
    NSLog(@"initWithData called");
    CTPWTPGMImageRep *imageRep = [[self class] imageRepWithData:data];

    if (imageRep == nil) {
        return nil;
    }
    return self;
}

#pragma mark - instance methods

+ (id)imageRepWithData:(NSData *)data {
    NSLog(@"imageRepWithData called");
    if (data.length < 2) return nil;
    NSString *magicNumberP5 = @"P5";
    const unsigned char *mnP5 = (const unsigned char *)[magicNumberP5 UTF8String];
    unsigned char headerBuffer[2];
    [data getBytes:headerBuffer length:2];

    if (memcmp(mnP5, headerBuffer, 2) != 0) {
        NSLog(@"It is not supported pgm file format.");
        return nil;
    }
    NSArray *pgmParameters = [self calculatePgmParameters:data beginingByte:3];

    NSInteger width = [[pgmParameters objectAtIndex:0] integerValue];     // width in pixels
    NSInteger height = [[pgmParameters objectAtIndex:1] integerValue];    // height in pixels

    NSUInteger imageLength = width * height * 2;                          // two bytes per pixel

    // imageData contains bytes of Bitmap only. Without header

    NSData *imageData = [data subdataWithRange:
                         NSMakeRange(data.length - imageLength, imageLength)];

    CGDataProviderRef provider = CGDataProviderCreateWithCFData((CFDataRef)CFBridgingRetain(imageData));
    CGColorSpaceRef colorSpace = CGColorSpaceCreateWithName(kCGColorSpaceGenericGray); // kCGColorSpaceGenericGrayGamma2_2
    CGImageRef imageRef = CGImageCreate(width,
                                        height,
                                        16,
                                        16,
                                        width * 2,
                                        colorSpace,
                                        kCGImageAlphaNone,
                                        provider,
                                        NULL,
                                        false,
                                        kCGRenderingIntentDefault);
    CGColorSpaceRelease(colorSpace);
    CGDataProviderRelease(provider);

    if (imageRef == NULL) {
        NSLog(@"CGImageCreate() failed!");
    }
    CTPWTPGMImageRep *imageRep = [[CTPWTPGMImageRep alloc] initWithCGImage:imageRef];
    return imageRep;
}

ご覧のとおり、ピクセルの値が0〜65535であるため、0〜255の範囲の値を拡張してパーツを残しました。

しかし、それは機能しません。パネルからpgmファイルを選択しても、何も起こりません。以下は私のopenPanelコードです:

- (IBAction)showOpenPanel:(id)sender
{
    NSLog(@"showPanel method called");

    __block NSOpenPanel *panel = [NSOpenPanel openPanel];
    [panel setAllowedFileTypes:[NSImage imageFileTypes]];
    [panel beginSheetModalForWindow:[pgmImageView window] completionHandler:^ (NSInteger result) {
        if (result == NSOKButton) {
            CTPWTPGMImageRep *pgmImage = [[CTPWTPGMImageRep alloc] initWithData:[NSData dataWithContentsOfURL:[panel URL]]];

            // NSLog(@"Bits per pixel: %ld",[pgmImage bitsPerPixel]); // BUG HERE!

            NSImage *image = [[NSImage alloc] init];
            [image addRepresentation:pgmImage];
            [pgmImageView setImage:image];
        }
        panel = nil; // prevent strong ref cycle
    }];
}

さらに、チェックのためだけにコードのコメント// NSLog(@"Bits per pixel: %ld",[pgmImage bitsPerPixel]); // BUG HERE!を外すと、Xcodeが一時的にフリーズし、次の場所でEXC_BAD_ACCESSが取得されます。

AppKit`__75-[NSBitmapImageRep _withoutChangingBackingPerformBlockUsingBackingCGImage:]_block_invoke_0:
0x7fff8b4823e8:  pushq  %rbp
0x7fff8b4823e9:  movq   %rsp, %rbp
0x7fff8b4823ec:  pushq  %r15
0x7fff8b4823ee:  pushq  %r14
0x7fff8b4823f0:  pushq  %r13
0x7fff8b4823f2:  pushq  %r12
0x7fff8b4823f4:  pushq  %rbx
0x7fff8b4823f5:  subq   $312, %rsp
0x7fff8b4823fc:  movq   %rsi, %rbx
0x7fff8b4823ff:  movq   %rdi, %r15
0x7fff8b482402:  movq   10625679(%rip), %rax
0x7fff8b482409:  movq   (%rax), %rax
0x7fff8b48240c:  movq   %rax, -48(%rbp)
0x7fff8b482410:  movq   %rbx, %rdi
0x7fff8b482413:  callq  0x7fff8b383148            ; BIRBackingType  //EXC_BAD_ACCESS (code=2, adress=...)

助けは?何が悪いのかわかりません...

4

2 に答える 2

2

実際には、思っているよりもはるかに簡単です。

まず、ではなくCTPWTPGMImageRepのサブクラスを作成することをお勧めします。すでに自分自身を描画する方法を知っているので、カスタムメソッドを実装する必要がないため、これで「最も難しい」問題が解決されます。(OS X 10.5以降では、基本的にCoreGraphicsの直接ラッパーです)。NSBitmapImageRepNSImageRepdrawNSBitmapImageRepNSBitmapImageRepCGImageRef

私はPGM形式にあまり詳しくありませんが、基本的に行うことは、ソース形式に一致する最も近い宛先形式で画像の表現を作成することです。特定の例を使用するために、ウィキペディアからPGMの例のFEEP画像を取り上げます。

P2
# Shows the word "FEEP" (example from Netpbm main page on PGM)
24 7
15
0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0
0  3  3  3  3  0  0  7  7  7  7  0  0 11 11 11 11  0  0 15 15 15 15  0
0  3  0  0  0  0  0  7  0  0  0  0  0 11  0  0  0  0  0 15  0  0 15  0
0  3  3  3  0  0  0  7  7  7  0  0  0 11 11 11  0  0  0 15 15 15 15  0
0  3  0  0  0  0  0  7  0  0  0  0  0 11  0  0  0  0  0 15  0  0  0  0
0  3  0  0  0  0  0  7  7  7  7  0  0 11 11 11 11  0  0 15  0  0  0  0
0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0

ここに画像の説明を入力してください

サンプル画像の値を表現できる最も近いネイティブ画像は、単一チャネルのグレースケール画像で、ピクセルあたり8ビット、アルファなしです。CGImageRef次に、指定した設定でを作成し、NSBitmapImageRepinitWithCGImage:メソッドを使用してカスタムサブクラスを初期化する計画です。

最初に、次の2つのメソッドをオーバーライドして、両方とも単数に依存します+imageRepWithData:

+ (NSArray *)imageRepsWithData:(NSData *)data {
    id imageRep = [[self class] imageRepWithData:data];
    return [NSArray arrayWithObject:imageRep];
}

- (id)initWithData:(NSData *)data {
    CTPWTPGMImageRep *imageRep = [[self class] imageRepWithData:data];
    if (imageRep == nil) {
        [self release];
        return nil;
    }
    self = [imageRep retain];
    return self;
}

私にとっては+imageRepsWithData:、画像を正しく読み込む前に、特異なメソッドを呼び出すメソッドを実装する必要がありました。

次に、単数+imageRepWithData:法を次のように変更します。

+ (id)imageRepWithData:(NSData *)data {
    if (data.length < 2) return nil;
    NSString *magicNumberP5 = @"P5";
    const unsigned char *mnP5 = (const unsigned char *)[magicNumberP5 UTF8String];
    unsigned char headerBuffer[20];
    [data getBytes:headerBuffer length:2];

    if (memcmp(mnP5, headerBuffer, 2) != 0) {
        NSLog(@"It is not supported pgm file format.");
        return nil;
    }
    NSArray *pgmParameters = [self calculatePgmParameters:data beginingByte:3];

    NSUInteger width = [[pgmParameters objectAtIndex:0] integerValue];
    NSUInteger height = [[pgmParameters objectAtIndex:1] integerValue];
    NSUInteger maxValue = [[pgmParameters objectAtIndex:2] integerValue];

    NSUInteger imageLength = width * height * 1;

    NSData *imageData = [data subdataWithRange:
                        NSMakeRange(data.length - imageLength, imageLength)];
    const UInt8 *imageDataBytes = [imageData bytes];
    UInt8 *expandedImageDataBytes = malloc(imageLength);

    for (NSUInteger i = 0; i < imageLength; i++) {
        expandedImageDataBytes[i] = 255 * (imageDataBytes[i] / (CGFloat)maxValue);
    }

    NSData *expandedImageData = [NSData dataWithBytes:expandedImageDataBytes
                                               length:imageLength];
    free(expandedImageDataBytes);
    CGDataProviderRef provider = CGDataProviderCreateWithCFData(
                                          (CFDataRef)expandedImageData);
    CGColorSpaceRef colorSpace =
             CGColorSpaceCreateWithName(kCGColorSpaceGenericGrayGamma2_2);
    CGImageRef imageRef = CGImageCreate(width,
                                        height,
                                        8,
                                        8,
                                        width * 1,
                                        colorSpace,
                                        kCGImageAlphaNone,
                                        provider,
                                        NULL,
                                        false,
                                        kCGRenderingIntentDefault);
    CGColorSpaceRelease(colorSpace);
    CGDataProviderRelease(provider);
    if (imageRef == NULL) {
        NSLog(@"CGImageCreate() failed!");
    }
    CTPWTPGMImageRep *imageRep = [[[CTPWTPGMImageRep alloc]
                                initWithCGImage:imageRef] autorelease];
    CGImageRelease(imageRef);
    return imageRep;
}

ご覧のとおり、元の画像のバイトをループして、0〜255の範囲で完全に拡張されたこれらのバイトの2番目のコピーを作成する必要があります。

この画像の担当者を利用するには、次のように呼び出すことができます(必ずNSImageinitWithData:メソッドを使用してください)。

// if it hasn't been done already:
[NSImageRep registerImageRepClass:[CTPWTPGMImageRep class]];

NSString *path = [[NSBundle mainBundle] pathForResource:@"feep" ofType:@"pgm"];
NSData *data = [NSData dataWithContentsOfFile:path];
NSImage *image = [[[NSImage alloc] initWithData:data] autorelease];
[self.imageView setImage:image];

メソッドに関するもう1つの注意+imageUnfilteredFileTypes:ファイル名拡張子は大文字と小文字を区別しないため、小文字と大文字@"PGM"の両方を指定する必要はありません。小文字で指定できます。

+ (NSArray *)imageUnfilteredFileTypes {
    static NSArray *types = nil;
    if (!types) types = [[NSArray alloc] initWithObjects:@"pgm", nil];
    return types;
}
于 2013-01-11T08:25:46.183 に答える
1

NSBitmapImageRep.pgmファイル専用の画像担当者を作成するよりも、ピクセルデータをメモリに読み込んで、ピクセルデータからを作成する方が簡単な場合があります。

于 2013-01-11T05:00:33.677 に答える