ProgramingTip

바이트 배열에서 비트 맵을 만드는 방법은 무엇입니까?

bestdevel 2021. 1. 5. 21:16
반응형

바이트 배열에서 비트 맵을 만드는 방법은 무엇입니까?


바이트 배열에 대한 모든 질문을 검색했지만 항상 실패했습니다. 나는 C #을 코딩 한 적이 없습니다. 바이트 배열에서 이미지 파일을 만드는 방법을 도와 주시겠습니까?

다음은 배열에 바이트를 저장하는 함수입니다. imageData

public void imageReady( byte[] imageData, int fWidth, int fHeight))

그 취득은 당신해야 우리합니다 bytes로를 MemoryStream:

Bitmap bmp;
using (var ms = new MemoryStream(imageData))
{
    bmp = new Bitmap(ms);
}

Bitmap(Stream stream)생성자 오버로드를 사용합니다 .

업데이트 : 문서와 내가 읽은 소스 코드 ArgumentException에 따르면 다음 조건에서는 던질 것입니다.

stream does not contain image data or is null.
-or-
stream contains a PNG image file with a single dimension greater than 65,535 pixels.

여러분의 도움에 감사드립니다. 이 모든 답변이 작동 생각합니다. 그러나 내 바이트 배열에 원시 바이트가 포함되어 있다고 생각합니다. 그래서 모든 솔루션이 내 코드에서 작동하지 않습니다.

그러나 나는 해결책을 찾았습니다. 이 솔루션은 저와 같은 문제가있는 다른 코더에게 도움이 될 수 있습니다.

static byte[] PadLines(byte[] bytes, int rows, int columns) {
   int currentStride = columns; // 3
   int newStride = columns;  // 4
   byte[] newBytes = new byte[newStride * rows];
   for (int i = 0; i < rows; i++)
       Buffer.BlockCopy(bytes, currentStride * i, newBytes, newStride * i, currentStride);
   return newBytes;
 }

 int columns = imageWidth;
 int rows = imageHeight;
 int stride = columns;
 byte[] newbytes = PadLines(imageData, rows, columns);

 Bitmap im = new Bitmap(columns, rows, stride, 
          PixelFormat.Format8bppIndexed, 
          Marshal.UnsafeAddrOfPinnedArrayElement(newbytes, 0));

 im.Save("C:\\Users\\musa\\Documents\\Hobby\\image21.bmp");

이 솔루션은 8 비트 256bpp (Format8bppIndexed)에서 작동합니다. 이미지에 다른 형식이있는 경우 변경해야합니다 PixelFormat.

그리고 지금 색상에 문제가 있습니다. 이 문제를 해결하자마자 다른 사용자를 위해 내 대답을 편집합니다.

* PS = stride 값에 대해 잘 모르겠지만 8 비트의 경우 열과 고려합니다.

8 비트 그레이드 이미지를 32 비트 레이아웃으로 복사합니다.

public void SaveBitmap(string fileName, int width, int height, byte[] imageData)
        {

            byte[] data = new byte[width * height * 4];

            int o = 0;

            for (int i = 0; i < width * height; i++)
            {
                byte value = imageData[i];


                data[o++] = value;
                data[o++] = value;
                data[o++] = value;
                data[o++] = 0; 
            }

            unsafe
            {
                fixed (byte* ptr = data)
                {

                    using (Bitmap image = new Bitmap(width, height, width * 4,
                                PixelFormat.Format32bppRgb, new IntPtr(ptr)))
                    {

                        image.Save(Path.ChangeExtension(fileName, ".jpg"));
                    }
                }
            }
        }

다음과 같이 쉽게 할 수 있습니다.

var ms = new MemoryStream(imageData);
System.Drawing.Image image = Image.FromStream(ms);

image.Save("c:\\image.jpg");

테스트 :

byte[] imageData;

// Create the byte array.
var originalImage = Image.FromFile(@"C:\original.jpg");
using (var ms = new MemoryStream())
{
    originalImage.Save(ms, ImageFormat.Jpeg);
    imageData = ms.ToArray();
}

// Convert back to image.
using (var ms = new MemoryStream(imageData))
{
    Image image = Image.FromStream(ms);
    image.Save(@"C:\newImage.jpg");
}

참조 URL : https://stackoverflow.com/questions/21555394/how-to-create-bitmap-from-byte-array

반응형