0

我正在使用UIImagePickerController类。我有一个按钮,当我单击该按钮时,我希望图像变亮。我在网上搜索过,但我在搜索时找到的代码不起作用。

这是我找到并使用的代码:

- (UIImage *) brightness:(UIImage *)image
{


int level= 200;//put here an int value that go from -255 to 255;



CGImageRef inImage = image.CGImage;   //Input image cgi

CGContextRef ctx;


CFDataRef m_DataRef;
m_DataRef = CGDataProviderCopyData(CGImageGetDataProvider(inImage));
UInt8 * m_PixelBuf = (UInt8 *) CFDataGetBytePtr(m_DataRef);

int length = CFDataGetLength(m_DataRef);
CGImageGetBitsPerComponent(inImage), CGImageGetBitsPerPixel(inImage),CGImageGetBytesPerRow(inImage);


for (int index = 0; index < length; index += 4)
{
    Byte tempR = m_PixelBuf[index + 1];
    Byte tempG = m_PixelBuf[index + 2];
    Byte tempB = m_PixelBuf[index + 3];

    int outputRed = level + tempR;
    int outputGreen = level + tempG;
    int outputBlue = level + tempB;

    if (outputRed>255) outputRed=255;
    if (outputGreen>255) outputGreen=255;
    if (outputBlue>255) outputBlue=255;

    if (outputRed<0) outputRed=0;
    if (outputGreen<0) outputGreen=0;
    if (outputBlue<0) outputBlue=0;


    m_PixelBuf[index + 1] = outputRed; 
    m_PixelBuf[index + 2] = outputGreen; 
    m_PixelBuf[index + 3] = outputBlue;

}



ctx = CGBitmapContextCreate(m_PixelBuf,
                            CGImageGetWidth( inImage ),
                            CGImageGetHeight( inImage ),
                            8,
                            CGImageGetBytesPerRow( inImage ),
                            CGImageGetColorSpace( inImage ),
                            kCGImageAlphaPremultipliedFirst );


CGImageRef imageRef = CGBitmapContextCreateImage (ctx);
UIImage* rawImage = [UIImage imageWithCGImage:imageRef];

CGContextRelease(ctx);


CGImageRelease(imageRef); 

CFRelease(m_DataRef);



return rawImage; 

}

图像仍然是原始图像的亮度,没有变化。

4

1 回答 1

2

总的来说,这个想法看起来不错,可能是更新像素数据时出错了。但要改变亮度,我建议使用 CoreGraphics 而不是软处理:

CGFloat brightness = 0.5;

UIGraphicsBeginImageContext(image.size);
CGRect imageRect = CGRectMake(0, 0, image.size.width, image.size.height);
CGContextRef context = UIGraphicsGetCurrentContext();

// Original image
[image drawInRect:imageRect]; 

// Brightness overlay
CGContextSetFillColorWithColor(context, [UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:brightness].CGColor);
CGContextAddRect(context, imageRect);
CGContextFillPath(context);

UIImage* resultImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

您可以更改亮度叠加颜色以获得正确的结果。

于 2012-06-26T13:50:32.183 回答