如何正确设置图像的步幅?

时间:2017-04-08 06:40:13

标签: image-processing bitmap bitmapdata

double[,]转换为Bitmap时,

Bitmap image = ImageDataConverter.ToBitmap(new double[,]  
                                    {   
                                    { .11, .11, .11, }, 
                                    { .11, .11, .11, }, 
                                    { .11, .11, .11, }, 
                                    });

例程给出

data.Stride == 4

这个值来自哪里?

由于double[,]3x3,因此步幅应为5。正确?

我怎样才能解决这个问题,不仅适用于任何维度?

相关源代码

public class ImageDataConverter
{
    public static Bitmap ToBitmap(double[,] input)
    {
        int width = input.GetLength(0);
        int height = input.GetLength(1);

        Bitmap output = Grayscale.CreateGrayscaleImage(width, height);

        BitmapData data = output.LockBits(new Rectangle(0, 0, width, height),
                                            ImageLockMode.WriteOnly,
                                            output.PixelFormat);            

        int pixelSize = System.Drawing.Image.GetPixelFormatSize(output.PixelFormat) / 8;

        int offset = data.Stride - width * pixelSize;

        double Min = 0.0;
        double Max = 255.0;

        unsafe
        {
            byte* address = (byte*)data.Scan0.ToPointer();

            for (int y = 0; y < height; y++)
            {
                for (int x = 0; x < width; x++)
                {
                    double v = 255 * (input[x, y] - Min) / (Max - Min);

                    byte value = unchecked((byte)v);

                    for (int c = 0; c < pixelSize; c++, address++)
                    {
                        *address = value;
                    }
                }

                address += offset;
            }
        }

        output.UnlockBits(data);

        return output;
    }
}

1 个答案:

答案 0 :(得分:0)

不知道你是怎么到达5的。

  

步幅是单行像素(扫描线)的宽度,四舍五入到四字节边界。

Link

由于它是3x3,3向上舍入到四字节边界是4。