C#메모리 이미지 스트림을 가져오는 방법

2480 단어 C#
배경: 때때로 우리는 이미지의 메모리 대상, 예를 들어 Bitmap 대상을 얻었다. 우리는 이 대상의 데이터 흐름을 얻으려고 한다. 이를 디스크에 서열화할 수도 있고 메모리 대상으로 반서열화할 수도 있다. 이때 제목과 같은 문제가 발생했다. 내가 인터넷을 샅샅이 뒤졌지만 비교적 적합한 방법을 발견하지 못했다. 그래서 나는 머리를 쥐어짜서 다음과 같은 방법을 썼다.
  public byte[] ImgToBytes(Bitmap bmp)

        {

            int width = bmp.Size.Width;

            int height = bmp.Size.Height;

            byte[] bws = BitConverter.GetBytes(width);

            byte[] bhs = BitConverter.GetBytes(height);

          

            BitmapData bd = bmp.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);

            IntPtr ptr = bd.Scan0;

            int bmpLen = bd.Stride * bd.Height;

            byte[] imgbytes = new byte[bmpLen + 8];

            Marshal.Copy(ptr, imgbytes, 0, bmpLen);

            bmp.UnlockBits(bd);

            for (int i = 0; i < 4; i++)

            {

                imgbytes[bmpLen + i] = bws[i];

                imgbytes[bmpLen + i + 4] = bhs[i];

            }



            return imgbytes;

        }



        public Bitmap BytesToImg(byte[] bytes)

        {

           int w =BitConverter.ToInt32(bytes, bytes.Length - 8);

           int h = BitConverter.ToInt32(bytes, bytes.Length - 4);



            Bitmap bmp = new Bitmap(w, h);

            BitmapData bd = bmp.LockBits(new Rectangle(0, 0, w, h), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);

            IntPtr ptr = bd.Scan0;

            int bmpLen = bd.Stride * bd.Height;

            Marshal.Copy(bytes, 0, ptr, bmpLen);

            bmp.UnlockBits(bd);

            return bmp;

        }

이 두 가지 방법은 제목과 같은 기능을 실현하지만 눈대중의 효율은 정말 보장할 수 없다. 게다가 데이터를 Bmp 형식으로 서열화하고 반서열화하기 때문에 데이터의 양이 매우 커지고 디스크의 읽기와 쓰기, 네트워크 전송에 시간이 비교적 소모되기 때문에 이곳은 틀림없이 가장 좋은 방법이 아닐 것이다.하늘이 무너져도 솟아날 구멍이 있다. 나는 또 다음과 같은 방법을 발견했다.
        public byte[] ImgToBytes2(Bitmap bmp)

        {

            MemoryStream sr = new MemoryStream();

            bmp.Save(sr, ImageFormat.Png);

            int len = (int)sr.Position;

            byte[] ret = new byte[sr.Position];

            sr.Seek(0, SeekOrigin.Begin);

            sr.Read(ret, 0, len);

            return ret;

        }



        public Image BytesToImg2(byte[] bytes)

        {

            return Image.FromStream(new MemoryStream(bytes));

        }


이 방법은 메모리 이미지를 Png 형식으로 서열화하고 반서열화하여 데이터량이 크게 낮아지고 눈대중효율도 전편보다 조금 좋으며 코드는 더욱 간단하고 읽기 쉽다.

좋은 웹페이지 즐겨찾기