1

我正在尝试访问图像的原始像素,但我一直遇到一个让我真正陷入困境的问题。我对 iPhone 编程很陌生,所以它可能非常简单......

这是我的课程,它使用CGImageRef来自图像的图像并查看各个像素。这是我的代码

头文件:

#import <QuartzCore/QuartzCore.h>
#import <QuartzCore/QuartzCore.h>
#import <CoreImage/CoreImage.h>


@interface GraphingView : UIControl 
{
@private
    CAShapeLayer *shapeLayer;    
    CGImageRef pixelData;
}

@property(assign) CGImageRef pixelData;
@end

还有我的实现文件:

#import "GraphingView.h"
#import "iSpectrumViewController.h"

@implementation GraphingView

@synthesize pixelData;
- (void)awakeFromNib
{
    // set up a rounded border
    CALayer *layer = [self layer];

    // clear the view's background color so that our background
    // fits within the rounded border
    CGColorRef backgroundColor = [self.backgroundColor CGColor];
    self.backgroundColor = [UIColor clearColor];
    layer.backgroundColor = backgroundColor;


    shapeLayer = [CAShapeLayer layer];      

    [self setNeedsDisplay];
}

- (void)drawRect:(CGRect)rect
{

}

- (void)updateGraph
{
    // This is where my problem is:
     // Whenever the next line is executed the application stops working. It works fine in the setPixelData
     // down below.
    CFDataRef pixelRef = CGDataProviderCopyData(CGImageGetDataProvider(pixelData));
    CFIndex byteSize = CFDataGetLength(pixelRef);
    int intByteSize = (int) byteSize;
    NSLog(@"Number of Bytes contained %i",intByteSize);

     //Then get a pointer to the data so the information can be accessed
    const UInt8 *pixelPtr = CFDataGetBytePtr(pixelRef);


    // Do some drawing here using the data obtained from the image...

    [shapeLayer setPath:path];
    [shapeLayer setNeedsDisplay];
    CFRelease(path);    
}

-(void)setPixelData:(CGImageRef)pixelImage
{
     //This code takes the CGImage from my image and copies it to the pixelData CGImageRef defined in the header file


    //This gets the CFDataRef from the CGImage so the pixel information is available
    CFDataRef PixelCopy = CGDataProviderCopyData(CGImageGetDataProvider(pixelImage));
    CFIndex byteSize = CFDataGetLength(PixelCopy);
    int intByteSize = (int) byteSize;
    NSLog(@"Number of Bytes contained %i",intByteSize);

    pixelData = CGImageCreateCopy(pixelImage);
    [self updateGraph];

}
@end

我遇到的问题是:

该函数setPixelData获取CGImageRef图像并将其复制到pixelData. 然后,在(void) updateGraph方法中,我使用CGImageRef pixelDataand create aCFDataRef来获取原始像素数据。但是,有些不对劲。因为当我使用作为输入的CFDataGetLength方法时,我在程序运行时得到错误。让我感到困惑的是,当我在函数中放入相同的两行代码(如上面的代码所示)并注释掉其中的代码时,程序运行得非常好。CFDataRef pixelRefEXC_BAD_ACCESS(void) setPixelDataupdateGraph

关于可能导致此错误的原因以及如何消除它的任何想法?

谢谢,

山姆

4

1 回答 1

1

啊……我找到了,

它不起作用的原因是因为我有两个 setter 方法(其中一个没有在代码中显示)。那个总是在函数之前setPixelData运行,所以PixelData CGImageRef从来没有设置,因此,CFDataRef不存在,给出内存错误。

于 2012-02-12T02:21:20.440 回答