Mi-mimeType识别-bitmap

本文详细介绍了位图文件的标准格式,包括位图文件头、信息头、颜色表及颜色索引数组等内容。通过实例解析了位图文件的具体结构及其存储方式。

Bitmap Storage

Bitmaps should be saved in a file that uses the established bitmap file format and assigned a name with the three-character .bmp extension. The established bitmap file format consists of a BITMAPFILEHEADER structure followed by a BITMAPINFOHEADERBITMAPV4HEADER, or BITMAPV5HEADER structure. An array of RGBQUAD structures (also called a color table) follows the bitmap information header structure. The color table is followed by a second array of indexes into the color table (the actual bitmap data).

The bitmap file format is shown in the following illustration.

Diagram of the bitmap file format, showing the BITMAPFILEHEADER, BITMAPINFOHEADER, RGBQUAD array, and color-index array

The members of the BITMAPFILEHEADER structure identify the file; specify the size of the file, in bytes; and specify the offset from the first byte in the header to the first byte of bitmap data. The members of the BITMAPINFOHEADERBITMAPV4HEADER, or BITMAPV5HEADER structure specify the width and height of the bitmap, in pixels; the color format (count of color planes and color bits-per-pixel) of the display device on which the bitmap was created; whether the bitmap data was compressed before storage and the type of compression used; the number of bytes of bitmap data; the resolution of the display device on which the bitmap was created; and the number of colors represented in the data. The RGBQUAD structures specify the RGB intensity values for each of the colors in the device's palette.

The color-index array associates a color, in the form of an index to an RGBQUAD structure, with each pixel in a bitmap. Thus, the number of bits in the color-index array equals the number of pixels times the number of bits needed to index the RGBQUAD structures. For example, an 8x8 black-and-white bitmap has a color-index array of 8 * 8 * 1 = 64 bits, because one bit is needed to index two colors. The Redbrick.bmp, mentioned in About Bitmaps, is a 32x32 bitmap with 16 colors; its color-index array is 32 * 32 * 4 = 4096 bits because four bits index 16 colors.

To create a color-index array for a top-down bitmap, start at the top line in the bitmap. The index of the RGBQUAD for the color of the left-most pixel is the first n bits in the color-index array (where n is the number of bits needed to indicate all of the RGBQUAD structures). The color of the next pixel to the right is the next n bits in the array, and so forth. After you reach the right-most pixel in the line, continue with the left-most pixel in the line below. Continue until you finish with the entire bitmap. If it is a bottom-up bitmap, start at the bottom line of the bitmap instead of the top line, still going from left to right, and continue to the top line of the bitmap.

The following hexadecimal output shows the contents of the file Redbrick.bmp.

C++
0000    42 4d 76 02 00 00 00 00  00 00 76 00 00 00 28 00 
0010    00 00 20 00 00 00 20 00  00 00 01 00 04 00 00 00 
0020    00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00 
0030    00 00 00 00 00 00 00 00  00 00 00 00 80 00 00 80 
0040    00 00 00 80 80 00 80 00  00 00 80 00 80 00 80 80 
0050    00 00 80 80 80 00 c0 c0  c0 00 00 00 ff 00 00 ff 
0060    00 00 00 ff ff 00 ff 00  00 00 ff 00 ff 00 ff ff 
0070    00 00 ff ff ff 00 00 00  00 00 00 00 00 00 00 00 
0080    00 00 00 00 00 00 00 00  00 00 00 00 00 00 09 00 
0090    00 00 00 00 00 00 11 11  01 19 11 01 10 10 09 09 
00a0    01 09 11 11 01 90 11 01  19 09 09 91 11 10 09 11 
00b0    09 11 19 10 90 11 19 01  19 19 10 10 11 10 09 01 
00c0    91 10 91 09 10 10 90 99  11 11 11 11 19 00 09 01 
00d0    91 01 01 19 00 99 11 10  11 91 99 11 09 90 09 91 
00e0    01 11 11 11 91 10 09 19  01 00 11 90 91 10 09 01 
00f0    11 99 10 01 11 11 91 11  11 19 10 11 99 10 09 10 
0100    01 11 11 11 19 10 11 09  09 10 19 10 10 10 09 01 
0110    11 19 00 01 10 19 10 11  11 01 99 01 11 90 09 19 
0120    11 91 11 91 01 11 19 10  99 00 01 19 09 10 09 19 
0130    10 91 11 01 11 11 91 01  91 19 11 00 99 90 09 01 
0140    01 99 19 01 91 10 19 91  91 09 11 99 11 10 09 91 
0150    11 10 11 91 99 10 90 11  01 11 11 19 11 90 09 11 
0160    00 19 10 11 01 11 99 99  99 99 99 99 99 99 09 99 
0170    99 99 99 99 99 99 00 00  00 00 00 00 00 00 00 00 
0180    00 00 00 00 00 00 90 00  00 00 00 00 00 00 00 00 
0190    00 00 00 00 00 00 99 11  11 11 19 10 19 19 11 09 
01a0    10 90 91 90 91 00 91 19  19 09 01 10 09 01 11 11 
01b0    91 11 11 11 10 00 91 11  01 19 10 11 10 01 01 11 
01c0    90 11 11 11 91 00 99 09  19 10 11 90 09 90 91 01 
01d0    19 09 91 11 01 00 90 10  19 11 00 11 11 00 10 11 
01e0    01 10 11 19 11 00 90 19  10 91 01 90 19 99 00 11 
01f0    91 01 11 01 91 00 99 09  09 01 10 11 91 01 10 91 
0200    99 11 10 90 91 00 91 11  00 10 11 01 10 19 19 09 
0210    10 00 99 01 01 00 91 01  19 91 19 91 11 09 10 11 
0220    00 91 00 10 90 00 99 01  11 10 09 10 10 19 09 01 
0230    91 90 11 09 11 00 90 99  11 11 11 90 19 01 19 01 
0240    91 01 01 19 09 00 91 10  11 91 99 09 09 90 11 91 
0250    01 19 11 11 91 00 91 19  01 00 11 00 91 10 11 01 
0260    11 11 10 01 11 00 99 99  99 99 99 99 99 99 99 99 
0270    99 99 99 99 99 90 


The following table shows the data bytes associated with the structures in a bitmap file.

Structure Corresponding bytes
BITMAPFILEHEADER 0x00 0x0D
BITMAPINFOHEADER 0x0E 0x35
RGBQUAD array 0x36 0x75
Color-index array 0x76 0x275
using System; using System.Collections.Generic; using System.Text; using System.Windows.Forms; using System.Runtime.InteropServices; using System.Drawing; using System.Collections; using System.IO; using System.Drawing.Imaging; using System.IO.Compression; using System.Diagnostics; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; using Newtonsoft.Json; namespace Util { #region EnumStringAttribute [AttributeUsage(AttributeTargets.Field, AllowMultiple = false, Inherited = false)] public class EnumStringAttribute : System.Attribute { public EnumStringAttribute(string str) { this.enumStr = str; } public string GetEnumString() { return this.enumStr; } private string enumStr; } #endregion public class Util { /// <summary> /// 得到可执行程序所在的目录,最后具有分隔符“\\”。 /// </summary> /// <returns></returns> public static string GetApplicationPath() { return AppDomain.CurrentDomain.BaseDirectory; } /// <summary> /// 填充并显示窗体到Panel中 /// </summary> /// <param name="panel"></param> /// <param name="frm"></param> public static void fillShowFrmToPanel(Panel panel, Form frm) { if (panel.Controls.Contains(frm)) { return; } panel.Controls.Clear(); frm.TopLevel = false; panel.Controls.Add(frm); frm.FormBorderStyle = FormBorderStyle.None; frm.Dock = DockStyle.Fill; frm.Show(); } /// <summary> /// 将文件名中的非法字符替换为'_',得到有效的文件名 /// </summary> /// <param name="filename"></param> /// <returns></returns> public static string GetValidFileName(string filename) { string newname = filename; newname = newname.Replace('/', '_'); newname = newname.Replace('\\', '_'); newname = newname.Replace(':', '_'); newname = newname.Replace('*', '_'); newname = newname.Replace('?', '_'); newname = newname.Replace('"', '_'); newname = newname.Replace('<', '_'); newname = newname.Replace('>', '_'); newname = newname.Replace('|', '_'); newname = newname.Replace((char)0xA, ' '); return newname; } /// <summary> /// 将字符串转化为整数 /// </summary> /// <param name="val"></param> /// <param name="defVal"></param> /// <returns></returns> public static int ToInt(string val, int defVal) { if (string.IsNullOrEmpty(val)) return defVal; try { if (val.StartsWith("0x") || val.StartsWith("0X")) { return int.Parse(val.Substring(2, val.Length - 2), System.Globalization.NumberStyles.HexNumber); } else { return int.Parse(val); } } catch (Exception e) { Console.WriteLine("数据转换格式错误:val: {0} {1}", val, e.Message); return defVal; } } /// <summary> /// 将字符串转换为长整数。 /// </summary> /// <param name="val"></param> /// <param name="defVal"></param> /// <returns></returns> public static long ToLong(string val, long defVal) { if (string.IsNullOrEmpty(val)) return defVal; try { if (val.StartsWith("0x") || val.StartsWith("0X")) { return long.Parse(val.Substring(2, val.Length - 2), System.Globalization.NumberStyles.HexNumber); } else { return long.Parse(val); } } catch (Exception e) { Console.WriteLine("数据转换格式错误:val: {0} {1}", val, e.Message); return defVal; } } /// <summary> /// 将二进制转化为16进制字符串。 /// </summary> /// <param name="buf"></param> /// <returns></returns> public static string BinaryToString(byte[] buf, int maxLen) { if (buf == null) return ""; int count = Math.Min(buf.Length, maxLen); bool bOmit = count < buf.Length; StringBuilder sb = new StringBuilder(count * 2 + 30); for (int i = 0; i < count; ++i) { sb.Append(buf[i].ToString("X2")); } if (bOmit) sb.Append(string.Format(" ... Total {0} Bytes", buf.Length)); return sb.ToString(); } /// <summary> /// 将二进制转化为16进制字符串。 /// </summary> /// <param name="buf"></param> /// <param name="cntPerRow">每行显示几个字节</param> /// <returns></returns> public static string BinaryToStringFormat(byte[] buf, int cntPerRow) { if (buf == null) return ""; StringBuilder sb = new StringBuilder(buf.Length * 2); int cnt = 0; int cntall = 0; foreach (byte b in buf) { cnt++; cntall++; if (cnt == 1) { sb.Append((cntall - 1).ToString("d4")).Append(" : "); } sb.Append(b.ToString("X2")).Append(" "); if (cnt >= cntPerRow) { sb.AppendLine(); cnt = 0; } } return sb.ToString(); } /// <summary> /// 将字符串转化为二进制数据数组 /// </summary> /// <param name="str"></param> /// <returns></returns> public static byte[] BinaryFromString(string str) { if (string.IsNullOrEmpty(str)) return new byte[0]; str = str.Trim(); int len = str.Length / 2; byte[] buf = new byte[len + (str.Length % 2)]; for (int i = 0; i < len; ++i) { buf[i] = byte.Parse(str.Substring(i * 2, 2), System.Globalization.NumberStyles.HexNumber); } if ((str.Length % 2) > 0) { // 最后一个字符 buf[buf.Length - 1] = byte.Parse(str.Substring(str.Length - 1, 1), System.Globalization.NumberStyles.HexNumber); } return buf; } /// <summary> /// byte数组格式化为十六进制的字符串 /// </summary> /// <param name="buffer"></param> /// <param name="len">长度</param> /// <param name="spliter">分割符</param> /// <returns></returns> public static string BufferFormat(byte[] buffer, int len, char spliter) { StringBuilder sb = new StringBuilder(""); if (buffer == null) return sb.ToString(); for (int i = 0; i < len; ++i) { sb.Append(buffer[i].ToString("X2")).Append(spliter); } return sb.ToString(); } public static uint ColorToInt(Color color) { return (uint)(((uint)color.B << 16) | (ushort)(((ushort)color.G << 8) | color.R)); } public static Color IntToColor(int color) { int r = 0xFF & color; int g = 0xFF00 & color; g >>= 8; int b = 0xFF0000 & color; b >>= 16; return Color.FromArgb(r, g, b); } #region DllImport 把窗体导出为图片使用 [DllImport("user32.dll")] public static extern IntPtr GetWindowRect(IntPtr hWnd, ref Rectangle rect); [DllImport("gdi32.dll")] public static extern IntPtr CreateCompatibleDC(IntPtr hdc); [DllImport("gdi32.dll")] public static extern IntPtr CreateCompatibleBitmap(IntPtr hdc, int nWidth, int nHeight); [DllImport("gdi32.dll")] public static extern IntPtr SelectObject(IntPtr hdc, IntPtr hgdiobj); [DllImport("gdi32.dll")] public static extern int DeleteDC(IntPtr hdc); [DllImport("gdi32.dll")] public static extern bool BitBlt( IntPtr hdcDest, // 目的 DC的句柄 int nXDest, int nYDest, int nWidth, int nHeight, IntPtr hdcSrc, // 源DC的句柄 int nXSrc, int nYSrc, System.Int32 dwRop // 光栅的处置数值 ); [DllImport("user32.dll")] public static extern bool PrintWindow(IntPtr hwnd, IntPtr hdcBlt, UInt32 nFlags); [DllImport("user32.dll")] public static extern IntPtr GetWindowDC(IntPtr hwnd); #endregion /// <summary> /// 根据窗口句柄,把窗口显示导出图片(.bmp) /// </summary> /// <param name="hWnd"></param> /// <returns></returns> public static Bitmap GetWindowCapture(IntPtr hWnd) { IntPtr hscrdc = GetWindowDC(hWnd); Rectangle windowRect = new Rectangle(); GetWindowRect(hWnd, ref windowRect); int width = windowRect.Right - windowRect.Left; int height = windowRect.Bottom - windowRect.Top; IntPtr hbitmap = CreateCompatibleBitmap(hscrdc, width, height); IntPtr hmemdc = CreateCompatibleDC(hscrdc); SelectObject(hmemdc, hbitmap); PrintWindow(hWnd, hmemdc, 0); Bitmap bmp = Bitmap.FromHbitmap(hbitmap); DeleteDC(hscrdc);//删除用过的对象 DeleteDC(hmemdc);//删除用过的对象 return bmp; } public static string BufferFormatSimple(byte[] buffer) { return Util.BufferFormat(buffer, buffer.Length, ' '); } static Dictionary<string, List<string>> typeHash = new Dictionary<string, List<string>>(); /// <summary> /// 得到与枚举类型值相关联的字符串 /// </summary> /// <param name="type"></param> /// <returns></returns> public static List<string> GetEnumString(Type type) { if (typeHash.ContainsKey(type.ToString())) { return typeHash[type.ToString()]; } else { List<string> list = new List<string>(); System.Reflection.MemberInfo[] mis = type.GetMembers(); foreach (System.Reflection.MemberInfo mi in mis) { Attribute[] attrs = System.Attribute.GetCustomAttributes(mi); foreach (Attribute at in attrs) { if (at is EnumStringAttribute) { list.Add(((EnumStringAttribute)at).GetEnumString()); } } } typeHash[type.ToString()] = list; return list; } } static Hashtable enumValueHash = new Hashtable(); /// <summary> /// 由枚举类型及枚举显示字符串得到枚举数值。 /// 如 由 SexType "男" 得到 (int)SexType.Male /// </summary> /// <param name="enumType"></param> /// <param name="enumDisStr"></param> /// <returns></returns> public static int GetEnumValue(Type enumType, string enumDisStr) { string key = enumType.ToString() + enumDisStr; if (enumValueHash.Contains(key)) { return (int)enumValueHash[key]; } else { int ret = -1; System.Reflection.MemberInfo[] mis = enumType.GetMembers(); foreach (System.Reflection.MemberInfo mi in mis) { Attribute[] attrs = System.Attribute.GetCustomAttributes(mi); foreach (Attribute at in attrs) { if (at is EnumStringAttribute) { EnumStringAttribute esr = (EnumStringAttribute)at; if (esr.GetEnumString() == enumDisStr) { ret = (int)System.Enum.Parse(enumType, mi.Name); break; } } } if (ret != -1) break; } enumValueHash[key] = ret; return ret; } } static Hashtable enumStringHash = new Hashtable(); /// <summary> /// 有枚举类型及枚举值得到显示字符串。 /// 如 由 SexType (int)SexType.Male 得到 "男" /// </summary> /// <param name="enumType"></param> /// <param name="enumVal"></param> /// <returns></returns> public static string GetEnumDisString(Type enumType, int enumVal) { string key = enumType.ToString() + enumVal.ToString(); if (enumStringHash.Contains(key)) { return (string)enumStringHash[key]; } else { string ret = ""; System.Reflection.MemberInfo[] mis = enumType.GetMembers(); foreach (System.Reflection.MemberInfo mi in mis) { Attribute[] attrs = System.Attribute.GetCustomAttributes(mi); foreach (Attribute at in attrs) { if (at is EnumStringAttribute) { EnumStringAttribute esr = (EnumStringAttribute)at; //object obj = System.Enum.Parse(enumType, mi.Name); if ((int)System.Enum.Parse(enumType, mi.Name) == enumVal) { ret = esr.GetEnumString(); break; } } } if (ret != "") break; } enumStringHash[key] = ret; return ret; } } private static ImageCodecInfo GetEncoderInfo(string mimeType) { // Get image codecs for all image formats ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders(); // Find the correct image codec for (int i = 0; i < codecs.Length; i++) if (codecs[i].MimeType == mimeType) return codecs[i]; return null; } public static byte[] ConvertToJpgBuff(Image bmp, long quality) { // Encoder parameter for image quality EncoderParameter qualityParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality); // JPEG image codec ImageCodecInfo jpegCodec = GetEncoderInfo("image/jpeg"); EncoderParameters encoderParams = new EncoderParameters(1); encoderParams.Param[0] = qualityParam; MemoryStream msJpg = new MemoryStream(); bmp.Save(msJpg, jpegCodec, encoderParams); bmp.Dispose(); return msJpg.ToArray(); } /// <summary> /// Convert Image to Byte[] /// </summary> /// <param name="image"></param> /// <returns></returns> public static byte[] ImageToBytes(Image image) { ImageFormat format = image.RawFormat; using (MemoryStream ms = new MemoryStream()) { if (format.Equals(ImageFormat.Jpeg)) { image.Save(ms, ImageFormat.Jpeg); } else if (format.Equals(ImageFormat.Png)) { image.Save(ms, ImageFormat.Png); } else if (format.Equals(ImageFormat.Bmp)) { image.Save(ms, ImageFormat.Bmp); } else if (format.Equals(ImageFormat.Gif)) { image.Save(ms, ImageFormat.Gif); } else if (format.Equals(ImageFormat.Icon)) { image.Save(ms, ImageFormat.Icon); } else image.Save(ms, ImageFormat.Jpeg); byte[] buffer = new byte[ms.Length]; //Image.Save()会改变MemoryStream的Position,需要重新Seek到Begin ms.Seek(0, SeekOrigin.Begin); ms.Read(buffer, 0, buffer.Length); return buffer; } } /// <summary> /// Convert Byte[] to Image /// </summary> /// <param name="buffer"></param> /// <returns></returns> public static Image BytesToImage(byte[] buffer) { MemoryStream ms = new MemoryStream(buffer); Image image = System.Drawing.Image.FromStream(ms); return image; } /// <summary> /// Convert Byte[] to a picture and Store it in file /// </summary> /// <param name="fileName"></param> /// <param name="buffer"></param> /// <returns></returns> public static string CreateImageFromBytes(string fileName, byte[] buffer) { string file = fileName; Image image = BytesToImage(buffer); ImageFormat format = image.RawFormat; if (format.Equals(ImageFormat.Jpeg)) { file += ".jpeg"; } else if (format.Equals(ImageFormat.Png)) { file += ".png"; } else if (format.Equals(ImageFormat.Bmp)) { file += ".bmp"; } else if (format.Equals(ImageFormat.Gif)) { file += ".gif"; } else if (format.Equals(ImageFormat.Icon)) { file += ".icon"; } System.IO.FileInfo info = new System.IO.FileInfo(file); System.IO.Directory.CreateDirectory(info.Directory.FullName); File.WriteAllBytes(file, buffer); return file; } public static System.DateTime ConvertIntDateTime(long d) { System.DateTime time = System.DateTime.MinValue; System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); time = startTime.AddMilliseconds(d); return time; } public static long ConvertDateTimeInt(System.DateTime time) { //double intResult = 0; System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1, 0, 0, 0, 0)); long t = (time.Ticks - startTime.Ticks) / 10000; //除10000调整为13位 return t; } /// <summary> /// 压缩缓冲区 /// </summary> /// <param name="inBuff">输入待压缩缓冲区</param> /// <param name="outBuff">输出压缩后缓冲区</param> /// <returns></returns> public static Boolean CompressBuffer(byte[] inBuff, ref byte[] outBuff) { Boolean bLess = false; using (MemoryStream destination = new MemoryStream()) { using (GZipStream output = new GZipStream(destination, CompressionMode.Compress)) { output.Write(inBuff, 0, inBuff.Length); } destination.Flush(); outBuff = destination.ToArray(); bLess = (outBuff.Length < inBuff.Length); if (!bLess) outBuff = inBuff; } return bLess; } /// <summary> /// 解压缩缓冲区 /// </summary> /// <param name="inBuff">待解压缓冲区</param> /// <param name="outBuff">解压后缓冲区</param> /// <returns></returns> public static Boolean DecompressBuffer(byte[] inBuff, ref byte[] outBuff) { Stream source = new MemoryStream(inBuff); using (MemoryStream destination = new MemoryStream()) { using (GZipStream input = new GZipStream(source, CompressionMode.Decompress, true)) { byte[] bytes = new byte[4096]; int n; while ((n = input.Read(bytes, 0, bytes.Length)) != 0) { destination.Write(bytes, 0, n); } } destination.Flush(); destination.Position = 0; outBuff = destination.ToArray(); } return true; } /// <summary> /// 从指定目录获取指定扩展名的文件 /// </summary> /// <param name="path"></param> /// <param name="extNameArr"></param> /// <returns></returns> public static List<FileInfo> GetDirFiles(string path, params string[] extNameArr) { List<FileInfo> lst = new List<FileInfo>(); try { string[] dir = Directory.GetDirectories(path); //文件夹列表 DirectoryInfo fdir = new DirectoryInfo(path); FileInfo[] file = fdir.GetFiles(); if (file.Length != 0 || dir.Length != 0) //当前目录文件或文件夹不为空 { foreach (FileInfo f in file) //显示当前目录所有文件 { foreach(string extName in extNameArr) { if (extName.ToLower().IndexOf(f.Extension.ToLower()) >= 0) { lst.Add(f); break; } } } foreach (string d in dir) { GetDirFiles(d, extNameArr);//递归 } } } catch (Exception ex) { Console.WriteLine(ex.Message); } return lst; } public static int DBM2Int(string dbm) { if (string.IsNullOrEmpty(dbm) || dbm.Length != 3) { Debug.Assert(false, "节点DBM不能为空,且长度必须为3," + dbm); } int id = 0; char[] arr = dbm.ToCharArray(); for (int i = 0; i < arr.Length; i++) { id <<= 8; id |= (byte)arr[i]; } return id; } public static string Int2DBM(int id) { char[] arr = new char[3]; for (int i = 2; i >= 0; i--) { arr[i] = (char)(id & 0xFF); id >>= 8; } return new string(arr); } #region 将类和结构序列化和反序列化的方法 /// <summary> /// 序列化(把类和结构序列化) /// </summary> /// <param name="msg">结构信息</param> /// <returns></returns> //public static byte[] Serialize(object obj) //{ // try // { // string json = JsonConvert.SerializeObject(obj); // byte[] buffer = Encoding.UTF8.GetBytes(json); // return buffer; // } // catch (Exception e) // { // Console.WriteLine(e.Message); // //OutPutLog.WriteLog(LogLevel.Error, "Util.Serialize()错误 " + e.Message, LogObjType.Util.ToString()); // } // return null; //} public static byte[] Serialize(object obj) { try { IFormatter inFormatter = new BinaryFormatter(); MemoryStream stm = new MemoryStream(); inFormatter.Serialize(stm, obj); byte[] buffer = stm.ToArray(); stm.Close(); stm.Dispose(); return buffer; } catch (Exception e) { Console.WriteLine(e.Message); //OutPutLog.WriteLog(LogLevel.Error, "Util.Serialize()错误 " + e.Message, LogObjType.Util.ToString()); } return null; } /// <summary> /// 反序列化(类和结构的反序列化) /// </summary> /// <param name="buffer">串行数据</param> /// <returns></returns> //public static object Deserialize(byte[] buffer) //{ // try // { // string json = Encoding.UTF8.GetString(buffer); // return JsonConvert.DeserializeObject(json) ?? null; // } // catch (Exception e) // { // Console.WriteLine(e.Message); // //OutPutLog.WriteLog(LogLevel.Error, "Util.Deserialize() " + e.Message, LogObjType.Util.ToString()); // } // return null; //} public static object Deserialize(byte[] buffer) { try { MemoryStream stream = new MemoryStream(buffer); BinaryFormatter outFormatter = new BinaryFormatter(); object obj = outFormatter.Deserialize(stream); stream.Close(); stream.Dispose(); return obj; } catch (Exception e) { Console.WriteLine(e.Message); //OutPutLog.WriteLog(LogLevel.Error, "Util.Deserialize() " + e.Message, LogObjType.Util.ToString()); } return null; } #endregion } } 转换.net8.0
最新发布
08-20
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值