iphone - 从 UIImageView 获取像素数据——适用于模拟器,不适用于设备

标签 iphone uiimageview pixel

基于 a previous question 的回复,我在 UIImageView 上创建了一个类别用于提取像素数据。这在模拟器中工作正常,但在部署到设备时则不然。我应该说不是总是——奇怪的是,如果 point.x == point.y,它确实会获取正确的像素颜色;否则,它会为我提供该线另一侧像素的像素数据,就像镜像一样。 (因此,点击图像右下角的像素即可获得左上角相应像素的像素数据,但点击左下角的像素将返回正确的像素颜色)。触摸坐标(CGPoint)正确。

我做错了什么?

这是我的代码:

@interface UIImageView (PixelColor)
- (UIColor*)getRGBPixelColorAtPoint:(CGPoint)point;
@end

@implementation UIImageView (PixelColor)

- (UIColor*)getRGBPixelColorAtPoint:(CGPoint)point
{
    UIColor* color = nil;

    CGImageRef cgImage = [self.image CGImage];
    size_t width = CGImageGetWidth(cgImage);
    size_t height = CGImageGetHeight(cgImage);
    NSUInteger x = (NSUInteger)floor(point.x);
    NSUInteger y = height - (NSUInteger)floor(point.y);

    if ((x < width) && (y < height))
    {
        CGDataProviderRef provider = CGImageGetDataProvider(cgImage);
        CFDataRef bitmapData = CGDataProviderCopyData(provider);
        const UInt8* data = CFDataGetBytePtr(bitmapData);
        size_t offset = ((width * y) + x) * 4;
        UInt8 red = data[offset];
        UInt8 blue = data[offset+1];
        UInt8 green = data[offset+2];
        UInt8 alpha = data[offset+3];
        CFRelease(bitmapData);
        color = [UIColor colorWithRed:red/255.0f green:green/255.0f blue:blue/255.0f alpha:alpha/255.0f];
    }

    return color;
}

最佳答案

我认为 R B G 是错误的。你有:

UInt8 red =   data[offset];     
UInt8 blue =  data[offset+1];
UInt8 green = data[offset+2];

但是你真的不是指R G B吗? :

UInt8 red =   data[offset];     
UInt8 green = data[offset+1];
UInt8 blue =  data[offset+2];

但即使修复了这个问题,Apple byte swaps 仍然存在问题。 (很棒的文章)在设备上时的 R 和 B 值,但在模拟器上时不是

对于 CFDataGetBytePtr 返回的 PNG 像素缓冲区,我遇到了类似的模拟器/设备问题。

这解决了我的问题:

#if TARGET_IPHONE_SIMULATOR
        UInt8 red =   data[offset];
        UInt8 green = data[offset + 1];
        UInt8 blue =  data[offset + 2];
#else
        //on device
        UInt8 blue =  data[offset];       //notice red and blue are swapped
        UInt8 green = data[offset + 1];
        UInt8 red =   data[offset + 2];
#endif

不确定这是否能解决您的问题,但您的行为不当的代码看起来与我修复它之前的情况很接近。

最后一件事:我相信即使在调用 CFRelease(bitmapData) 之后,模拟器也会让您访问像素缓冲区 data[]。根据我的经验,在设备上,情况并非如此。您的代码不应该受到影响,但如果这对其他人有帮助,我想我会提到它。

关于iphone - 从 UIImageView 获取像素数据——适用于模拟器,不适用于设备,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1911360/

相关文章:

iphone - 如何更改 Controller 中按钮的图像与另一个按钮的图像?

iphone - NSMutabledata byteswithnocopy 的问题

iphone - 内部 iPhone 企业应用程序分发的替代解决方案

iphone - 创建点击叠加说明 View

ios - 多选 TableView - 当部分展开/折叠时在自定义标题中旋转图像

iphone - iOS OpenGL ES 逻辑缓冲区加载

iphone - xibs 问题 : should I use @2x 中的 UIImage 名称

javascript - 远处变换元素的宽度/高度(以像素为单位)

android - OpenCV转换每个像素的颜色

c - X11: 将像素值转换为 RGB