重写值时for循环中的错误

时间:2013-06-17 10:30:12

标签: ios objective-c image-processing

我使用以下方法将输入图像转换为灰度和阈值:

UIImage *image = self.imageView.image;

    // Create image rectangle with current image width/height

    CGRect imageRect = CGRectMake(0, 0, image.size.width, image.size.height);
    NSLog(@"width %f, height %f", image.size.width, image.size.height  );

    // Grayscale color space
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray();

    // Create bitmap content with current image size and grayscale colorspace
    CGContextRef context = CGBitmapContextCreate(nil, image.size.width, image.size.height, 8, 0, colorSpace, kCGImageAlphaNone);

    // Draw image into current context, with specified rectangle
    // using previously defined context (with grayscale colorspace)
    CGContextDrawImage(context, imageRect, [image CGImage]);

    // Create bitmap image info from pixel data in current context
    CGImageRef imageRef = CGBitmapContextCreateImage(context);

    // Create a new UIImage object
    UIImage *newImage = [UIImage imageWithCGImage:imageRef];

    // Release colorspace, context and bitmap information
    CGColorSpaceRelease(colorSpace);
    CGContextRelease(context);
    CFRelease(imageRef);

    // Return the new grayscale image
    self.imageView.image= newImage;




    //Thresholds the grayscale image



    CGImageRef sourceImage = newImage.CGImage ; //creates a CGImage reference for it

    //
    CFDataRef theData; //creates a variable of CFDataRef to store data of the image.
    //
    //
    //
    theData = CGDataProviderCopyData(CGImageGetDataProvider(sourceImage)); //assigns theData variable to the actual image
    //
    //
    //
    //
    //
    //
    //
    //
    UInt8 *pixelData = (UInt8 *) CFDataGetBytePtr(theData);
    //

    int dataLength = CFDataGetLength(theData);
    int counter=0;


    for (int index = 0; index < dataLength; index += 4)
    {

        if (pixelData[index]  < 180)
        {
               NSLog(@"The intensity is %u", pixelData[index]);
            pixelData[index] = 0;
            //pixelData[index+1] = 0;
            //pixelData[index+2] = 0;
            //pixelData[index+3] = 0;

        }

        else
        {
            NSLog(@"The intensity is %u", pixelData[index]);
            pixelData[index] = 255;
           // pixelData[index+1] = 255;
           // pixelData[index+2] = 0;
            //pixelData[index+3] = 0;
        }





    }

当for循环试图重写强度时,应用程序崩溃:

pixelData[index] = 0;

请有人帮帮我吗?

谢谢!

1 个答案:

答案 0 :(得分:1)

CFDataGetBytePtr返回只读指针,如Apple docs所述。 提出了一种解决方案here