我正在尝试从屏幕缓冲区中读取像素,我正在创建一个CGImageRef
with CGDisplayCreateImage
,但值CGImageGetWidth
and CGImageGetBytesPerRow
在一起没有意义,将每行字节数除以每像素字节数得到每行 1376 个像素,但图像的宽度是 1366。
这里发生了什么?图像中是否有某种填充?如何安全地读取我从中获取的数据并获得正确的结果?
编辑:重现此问题所需的最少代码如下:
#import <Foundation/Foundation.h>
#import <ApplicationServices/ApplicationServices.h>
int main(int argc, const char * argv[])
{
@autoreleasepool {
CGImageRef image = CGDisplayCreateImage(CGMainDisplayID());
size_t width = CGImageGetWidth(image);
size_t bpr = CGImageGetBytesPerRow(image);
size_t bpp = CGImageGetBitsPerPixel(image);
size_t bpc = CGImageGetBitsPerComponent(image);
size_t bytes_per_pixel = bpp / bpc;
NSLog(@"%li %li", bpr/bytes_per_pixel, width);
CGImageRelease(image);
}
return 0;
}
每行的字节数(也称为“步幅”)可以大于图像的宽度。每行末尾的额外字节将被简单地忽略。像素的字节数(x, y)
从偏移量开始y * bytesPerRow + x * bytesPerPixel
.
请注意,1376 可以被 32(以及所有较小的 2 的幂)整除,而 1366 则不能。现代 Mac 中的 CPU 具有一次运行 16 或 32 或 64 字节的指令,因此CGImage
如果图像的步长是 16、32 或 64 的倍数,算法会更有效。CGDisplayCreateImage
是由了解这一点的人写的。 (同样适用于CGBitmapContextCreate
/ CGContext.init
如果你传递 0bytesPerRow
.)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)