using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.Runtime.InteropServices; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TUCamera { /// /// Bitmap转化 /// public static class Tools { public static Bitmap ToBitmap(this byte[] rawValues, int width, int height, PixelFormat pixelFormat) { //// 申请目标位图的变量,并将其内存区域锁定 try { var currBitmap = new Bitmap(width, height, pixelFormat); var rect = new Rectangle(0, 0, width, height); var bitmapData = currBitmap.LockBits(rect, ImageLockMode.WriteOnly, pixelFormat); IntPtr iptr = bitmapData.Scan0; // 获取bmpData的内存起始位置 int size = width * height; if (pixelFormat == PixelFormat.Format24bppRgb) size *= 3; Marshal.Copy(rawValues, 0, iptr, size); currBitmap.UnlockBits(bitmapData); return currBitmap; } catch { return null; } } public static byte[] ToByteArray(this Bitmap bitmap) { BitmapData bmpdata = null; try { bmpdata = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly, bitmap.PixelFormat); int numbytes = bmpdata.Stride * bitmap.Height; byte[] bytedata = new byte[numbytes]; IntPtr ptr = bmpdata.Scan0; Marshal.Copy(ptr, bytedata, 0, numbytes); return bytedata; } finally { if (bmpdata != null) bitmap.UnlockBits(bmpdata); } } public static Bitmap ToBitmap(this TUCAMAPI.TUCAM_FRAME frame) { var width = (int)(frame.usWidth); var height = (int)(frame.usHeight); int nSize = (int)(frame.uiImgSize + frame.usHeader); var buff = new byte[nSize]; Marshal.Copy(frame.pBuffer, buff, 0, nSize); Buffer.BlockCopy(buff, (int)(frame.usHeader), buff, 0, (int)(frame.uiImgSize)); Bitmap bitmap; if (frame.ucChannels == 1) { bitmap = buff.ToBitmap(width, height, PixelFormat.Format8bppIndexed); ; } else { bitmap = buff.ToBitmap(width, height, PixelFormat.Format24bppRgb); ; } return bitmap; } } }