1.不含图片格式信息的byte和Bitma相互转换
public static byte[] BitmapToByte(Bitmap bitmap)
{
BitmapData bitmapDat = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadWrite, bitmap.PixelFormat);
IntPtr intPtr = bitmapDat.Scan0;
byte[] image = new byte[bitmap.Width * bitmap.Height];
Marshal.Copy(intPtr, image, 0, bitmap.Width * bitmap.Height);
bitmap.UnlockBits(bitmapDat);
return image;
}
public static Bitmap ToGrayBitmap(byte[] rawValues, int width, int height)
{
Bitmap bmp = new Bitmap(width, height, PixelFormat.Format8bppIndexed);
BitmapData bmpData = bmp.LockBits(new Rectangle(0, 0, width, height),
ImageLockMode.WriteOnly, PixelFormat.Format8bppIndexed);
int stride = bmpData.Stride;
int offset = stride - width;
IntPtr iptr = bmpData.Scan0;
int scanBytes = stride * height;
int posScan = 0, posReal = 0;
byte[] pixelValues = new byte[scanBytes];
for (int x = 0; x < height; x++)
{
for (int y = 0; y < width; y++)
{
pixelValues[posScan++] = rawValues[posReal++];
}
posScan += offset;
}
System.Runtime.InteropServices.Marshal.Copy(pixelValues, 0, iptr, scanBytes);
bmp.UnlockBits(bmpData);
ColorPalette tempPalette;
using (Bitmap tempBmp = new Bitmap(1, 1, PixelFormat.Format8bppIndexed))
{
tempPalette = tempBmp.Palette;
}
for (int i = 0; i < 256; i++)
{
tempPalette.Entries[i] = Color.FromArgb(i, i, i);
// tempPalette.Entries = Color.FromArgb(i, i, i);
}
bmp.Palette = tempPalette;
return bmp;
}
2.含有图片格式信息的byte和Bitma相互转换
public static Bitmap ByteToBitmap(byte[] bytes)
{
byte[] bytelist = bytes;
MemoryStream ms1 = new MemoryStream(bytelist);
Bitmap bm = (Bitmap)Image.FromStream(ms1);
ms1.Close();
return bm;
}
private static byte[] BitmapToByte(System.Drawing.Bitmap bitmap)
{
System.IO.MemoryStream ms = new System.IO.MemoryStream();
bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
ms.Seek(0, System.IO.SeekOrigin.Begin);
byte[] bytes = ms.ToArray();
ms.Close();
return bytes;
}