CGImageRef宽度与每行字节数不一致 [英] CGImageRef width doesn't agree with bytes-per-row

查看:354
本文介绍了CGImageRef宽度与每行字节数不一致的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从屏幕缓冲区中读取像素,我正在使用CGDisplayCreateImage创建一个CGImageRef,但是CGImageGetWidthCGImageGetBytesPerRow的值没有意义,将字节分开每行乘以每个像素的字节数可以得到1376个像素,但是图像的宽度为1366.

I'm trying to read pixels out of the screen buffer, I'm creating a CGImageRef with CGDisplayCreateImage, but the values for CGImageGetWidth and CGImageGetBytesPerRow Don't make sense together, dividing the bytes per row by the bytes per pixel gives me 1376 pixels per row, but the width of the image is 1366.

这是怎么回事?图像中是否存在某种填充?如何安全地从中读取数据并获得正确的结果?

What's going on here? Is there some kind of padding in the image? How do I read from the data I'm getting out of it safely, and with the correct results?

重现此内容所需的最少代码如下:

The minimal code needed to reproduce this is the following:

#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 * bpr + x * bpp(其中bpr是每行字节,bpp是每像素字节)

The bytes per row (also called the "stride") can be larger than the width of the image. The extra bytes at the end of each row are simply ignored. The bytes for the pixel at (x, y) start at offset y * bpr + x * bpp (where bpr is bytes-per-row and bpp is bytes-per-pixel).

请注意,1376可以被32(以及所有2的较小次幂)完全整除,而1366却不能.现代Mac中的CPU具有一次可在16或32或64字节上运行的指令,因此,如果图像的跨度是16或32或64的倍数,则CGImage算法会更高效.知道这一点的人.

Notice that 1376 is exactly divisible by 32 (and all smaller powers of 2), while 1366 is not. The CPUs in modern Macs have instructions that operate on 16 or 32 or 64 bytes at a time, so the CGImage algorithms can be more efficient if the image's stride is a multiple of 16 or 32 or 64. CGDisplayCreateImage was written by someone who knows this.

这篇关于CGImageRef宽度与每行字节数不一致的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆