c#字节流转换方法大全:c#实现将字节流转换为图片

发布时间:2020-02-01编辑:脚本学堂
c#编程中如何实现字节流转换,这里分享几个c#字节流转换代码,包括C# 将字节流转换为图片的实例、C# 通讯时字节流和结构体互转、C# 文件和字节流的转换方法等。

一、C# 将字节流转换为图片的实例。
 

复制代码 代码示例:
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Drawing;
usingSystem.IO;
namespaceMicrosoft.Form.Base
{
classImageToByte
{
/// <summary>
/// 图片转换成字节流
/// </summary>
/// <param name="img">要转换的Image对象</param>
/// <returns>转换后返回的字节流</returns>
publicstaticbyte[] ImgToByt(Image img)
{
MemoryStream ms = newMemoryStream();
byte[] imagedata = null;
img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
imagedata = ms.GetBuffer();
returnimagedata;
}
/// <summary>
/// 字节流转换成图片
/// </summary>
/// <param name="byt">要转换的字节流</param>
/// <returns>转换得到的Image对象</returns>
publicstaticImage BytToImg(byte[] byt)
{
MemoryStream ms = newMemoryStream(byt);
Image img = Image.FromStream(ms);
returnimg;
}
//
/// <summary>
/// 根据图片路径返回图片的字节流byte[]
/// </summary>
/// <param name="imagePath">图片路径</param>
/// <returns>返回的字节流</returns>
privatestaticbyte[] getImageByte(stringimagePath)
{
FileStream files = newFileStream(imagePath, FileMode.Open);
byte[] imgByte = newbyte[files.Length];
files.Read(imgByte, 0, imgByte.Length);
files.Close();
returnimgByte;
}
}
}

二、C# 通讯时字节流和结构体互转
 

复制代码 代码示例:
//转换C#代码:
 
//结构体转换成字节流
public static byte[] StructToBytes<T>(T obj)
{
int size = Marshal.SizeOf(typeof(T));
   IntPtr bufferPtr = Marshal.AllocHGlobal(size);
try 
{
 Marshal.StructureToPtr(obj, bufferPtr, false);
 byte[] bytes = new byte[size];
 Marshal.Copy(bufferPtr, bytes, 0, size);
 
 return bytes;
}
  catch(Exception ex)
  {
throw new Exception("Error in StructToBytes ! " + ex.Message);
  }
finally 

  Marshal.FreeHGlobal(bufferPtr); 
}
}
 
//字节流转换成结构体
public static T BytesToStruct<T>(byte[] bytes, int startIndex = 0)
{
  if (bytes == null) return default(T);
  if (bytes.Length <= 0) return default(T);
int objLength = Marshal.SizeOf(typeof(T));
  IntPtr bufferPtr = Marshal.AllocHGlobal(objLength);
  try//struct_bytes转换
  {
Marshal.Copy(bytes, startIndex, bufferPtr, objLength);
return (T)Marshal.PtrToStructure(bufferPtr, typeof(T));
  }
  catch(Exception ex)
  {
throw new Exception("Error in BytesToStruct ! " + ex.Message);
  }
  finally
  {
Marshal.FreeHGlobal(bufferPtr);
  }
}
 
[StructLayout(LayoutKind.Sequential, Pack=1)]  //变量在内存中的对齐方式
public struct LolMsgHeader
{
public ushort wMsgLen;
public byte    header_ver;
public ushort  uAction; //动作行为
public uint  dwUid; //用户ID
public uint dwSeq; //包的序列号
public uint  dwPid; //当前服务ID
 
};
 
public struct LOLMoveMsg
{
[MarshalAs(UnmanagedType.SysUInt, SizeConst = LOLMsgConst.MASK_LEN)]
public WORD  mask; // 掩码
[MarshalAs(UnmanagedType.ByValArray, SizeConst = LOLMsgConst.NAME_LEN)]
public byte[] szName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = LOLMsgConst.NAME_LEN)]
public string targetName; //目的对象
public short x;
public short y;
public byte byReached; //到达目的地,未到达0,到达1
};
 
//注意,之前遇到过在ios真机上运行不起来的bug,在android真机和ios模拟器上都是OK的问题,
 

后来把所有的ByValArray改成ByValTStr解决了这个问题。
 
如果有可能,建议不要用数组,全部都用基本类型。

三、C# 文件和字节流的转换
1、读取文件,并转换为字节流 FileStream fs = new FileStream(filename,FileMode.Open, FileAccess.Read);
 

复制代码 代码示例:
byte[] infbytes = new byte[(int)fs.Length];
fs.Read(infbytes, 0, infbytes.Length);
fs.Close();
return infbytes;

2、将字节流写入文件
 

复制代码 代码示例:
FileStream fs = new FileStream("D:inf.dlv",FileMode.Create, FileAccess.Write);
fs.Write(infbytes, 0, inf.Length);
fs.Close();