为什么一定要"步幅"在System.Drawing.Bitmap构造是4的倍数? [英] Why must "stride" in the System.Drawing.Bitmap constructor be a multiple of 4?

查看:246
本文介绍了为什么一定要"步幅"在System.Drawing.Bitmap构造是4的倍数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写信,要求我带一个专用的位图格式(一种MVTec公司哈尔康画佳)并将其转换成一个System.Drawing.Bitmap在C#中的应用程序。

I am writing an application that requires me to take a proprietary bitmap format (an MVTec Halcon HImage) and convert it into a System.Drawing.Bitmap in C#.

给我的唯一的专有功能,帮助我做这件事牵扯了我写入文件,除了使用get指针的功能。

The only proprietary functions given to me to help me do this involve me writing to file, except for the use of a "get pointer" function.

此功能是很大的,它给我一个指针的像素数据,宽度,高度,和图象的类型。

This function is great, it gives me a pointer to the pixel data, the width, the height, and the type of the image.

我的问题是,当我使用构造函数创建我System.Drawing.Bitmap:

My issue is that when I create my System.Drawing.Bitmap using the constructor:

new System.Drawing.Bitmap(width, height, stride, format, scan)

我需要指定一个步幅,也就是4的倍数。
因为我不能确定什么尺寸的位图我的功能将受到打击,这可能是一个问题。
假如我结束了一个位图,它是111x111像素,我也没办法跑不是增加一个假的列到我的图像或减去3列等这个功能。

I need to specify a "stride" that is a multiple of 4. This may be a problem as I am unsure what size bitmap my function will be hit with. Supposing I end up with a bitmap that is 111x111 pixels, I have no way to run this function other than adding a bogus column to my image or subtracting 3 columns.

有没有一种方法,我可以解决这一限制潜行?

Is there a way I can sneak around this limitation?

推荐答案

这可以追溯到早期的CPU设计。通过位图的比特紧缩的最快方式是通过阅读他们的32位的时间,开始扫描线的开始。当扫描线的第一个字节的32位的地址边界上对齐的效果最好。换言之,这是4的倍数。在早期的CPU,其具有第一字节不对齐会花费额外的CPU周期以从RAM读取两个32位字和随机创建的32位值中的字节的地址。确保每个扫描线在一个对齐的地址(自动如果步幅是4的倍数)开始避免了

This goes back to early CPU designs. The fastest way to crunch through the bits of the bitmap is by reading them 32-bits at a time, starting at the start of a scan line. That works best when the first byte of the scan line is aligned on a 32-bit address boundary. In other words, an address that's a multiple of 4. On early CPUs, having that first byte mis-aligned would cost extra CPU cycles to read two 32-bit words from RAM and shuffle the bytes to create the 32-bit value. Ensuring each scan line starts at an aligned address (automatic if the stride is a multiple of 4) avoids that.

这是不是一个真正的关注了现代的CPU,现在调整为高速缓存行边界更重要。然而,对步幅4要求多停留周围应用程序兼容性的原因。

This isn't a real concern anymore on modern CPUs, now alignment to the cache line boundary is much more important. Nevertheless, the multiple of 4 requirement for stride stuck around for appcompat reasons.

顺便说一句,你可以很容易地从格式和宽度与此计算步幅:

Btw, you can easily calculate the stride from the format and width with this:

        int bitsPerPixel = ((int)format & 0xff00) >> 8;
        int bytesPerPixel = (bitsPerPixel + 7) / 8;
        int stride = 4 * ((width * bytesPerPixel + 3) / 4);

这篇关于为什么一定要"步幅"在System.Drawing.Bitmap构造是4的倍数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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