sheyinhai 2023-07-24 13:19 采纳率: 0%
浏览 117
已结题

C#byte数组转化成Bitmap图像 像素错位

问题:c# 中 由于项目需要,图像保存在byte数组中,图像格式为8bit灰度图像,原图如下所示:

img

然后对图像进行缩放,缩放的代码为:

public static byte[] ResizeNearestNeighbor(byte[] srcByte, Size srcSize, Size dstSize)
{
    int bytesPerPixel = 1;
    byte[] dstDataBuffer = new byte[dstSize.Width * dstSize.Height];
    int dstDataLen = dstSize.Width * dstSize.Height * bytesPerPixel;
    if (dstDataBuffer.Length < dstDataLen)
    {
        Array.Resize(ref dstDataBuffer, dstDataLen);
    }
    float scale_x = (float)srcSize.Width / dstSize.Width;
    float scale_y = (float)srcSize.Height / dstSize.Height;
    int dstStep = dstSize.Width * bytesPerPixel;
    int srcStep = srcSize.Width * bytesPerPixel;
    int ny, nx, nc;
    int sy, sx;
    for (ny = 0; ny < dstSize.Height; ++ny)
    {
        sy = Convert.ToInt32(Math.Floor(ny * scale_y));
        sy = Math.Min(sy, srcSize.Height - 1);
        for (nx = 0; nx < dstSize.Width; ++nx)
        {
            sx = Convert.ToInt32(Math.Floor(nx * scale_x));
            sx = Math.Min(sx, srcSize.Width - 1);
            for (nc = 0; nc < bytesPerPixel; nc++)
            {
                dstDataBuffer[ny * dstStep + nx * bytesPerPixel + nc] =
                    srcByte[sy * srcStep + sx * bytesPerPixel + nc];
            }
        }
    }
    return dstDataBuffer;
}

最后需要将缩放完的图像再转为bitmap去保存,保存的图像出现像素错位现象,byte转bitmap代码如下:

public static Bitmap ByteArrayToBitmap(byte[] byteArray, Size size)
{
    Bitmap bmp = new Bitmap(size.Width, size.Height, PixelFormat.Format8bppIndexed);
    BitmapData bmpData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height),ImageLockMode.WriteOnly, bmp.PixelFormat);
    //用Marshal的Copy方法,将刚才得到的内存字节数组复制到BitmapData中
    Marshal.Copy(byteArray, 0, bmpData.Scan0, size.Width * size.Height);
    //解锁内存区域  
    bmp.UnlockBits(bmpData);

    //使PixelFormat.Format8bppIndexed(八位颜色索引)生效,在调色板中设置每个索引到具体的颜色映射
    ColorPalette palette = bmp.Palette;
    for (int i = 0; i < 256; i++)
    {
        palette.Entries[i] = Color.FromArgb(i, i, i);
    }
    bmp.Palette = palette;

    return bmp;
}

错位图像如下所示,哪位能够帮忙解惑一下

img

  • 写回答

6条回答 默认 最新

报告相同问题?

问题事件

  • 已结题 (查看结题原因) 7月25日
  • 创建了问题 7月24日