C#메모리 이미지 스트림을 가져오는 방법
2480 단어 C#
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 형식으로 서열화하고 반서열화하여 데이터량이 크게 낮아지고 눈대중효율도 전편보다 조금 좋으며 코드는 더욱 간단하고 읽기 쉽다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
WebView2를 Visual Studio 2017 Express에서 사용할 수 있을 때까지Evergreen .Net Framework SDK 4.8 VisualStudio2017에서 NuGet을 사용하기 때문에 패키지 관리 방법을 packages.config 대신 PackageReference를 사용해야...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.