Getting pixel data from UIImageView — works on simulator, not device

谁都会走 提交于 2019-11-29 07:46:59

I think R B G is wrong. You have:

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

But don't you really mean R G B? :

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

But even with that fixed there's still a problem as it turns out Apple byte swaps (great article) the R and B values when on the device, but not when on the simulator.

I had a similar simulator/device issue with a PNG's pixel buffer returned by CFDataGetBytePtr.

This resolved the issue for me:

#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

Not sure if this will fix your issue, but your misbehaving code looks close to what mine looked like before I fixed it.

One last thing: I believe the simulator will let you access your pixel buffer data[] even after CFRelease(bitmapData) is called. On the device this is not the case in my experience. Your code shouldn't be affected, but in case this helps someone else I thought I'd mention it.

You could try the following alternative approach:

  • create a CGBitmapContext
  • draw the image into the context
  • call CGBitmapContextGetData on the context to get the underlying data
  • work out your offset into the raw data (based on how you created the bitmap context)
  • extract the value

This approach works for me on the simulator and device.

It looks like that in the code posted in the original questions instead of:

NSUInteger x = (NSUInteger)floor(point.x);
NSUInteger y = height - (NSUInteger)floor(point.y);

It should be:

NSUInteger x = (NSUInteger)floor(point.x);
NSUInteger y = (NSUInteger)floor(point.y);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!