1. 程式人生 > >C#中二進位制陣列和圖片之間的相互轉換

C#中二進位制陣列和圖片之間的相互轉換

二進位制陣列和影象相互轉換的函式: 

      //影象轉換成二進位制

       private byte[] ImageToByte(Image Picture)
        {
            MemoryStream ms = new MemoryStream();
            if (Picture == null)
                return new byte[ms.Length];
            Picture.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            byte[] BPicture = new byte[ms.Length];
            BPicture = ms.GetBuffer();
            return BPicture;
        }
        //二進位制轉換為影象
        private Image ByteToImage(byte[] btImage)
        {
            if (btImage.Length == 0)
                return null;
            System.IO.MemoryStream ms = new System.IO.MemoryStream(btImage);
            System.Drawing.Image image = System.Drawing.Image.FromStream(ms);
            return image;
        }

1、定義物件

public class PicClass
{
        public List<byte[]> img { get; set; }    //圖片
}

//生成圖片的方法
PicClass pc = new PicClass();

List<byte[]> imgs = new List<byte[]>();
byte[] img = new byte[0];
img = (byte[])pic.image;       //pic.image是返回的圖片的二進位制陣列
imgs.Add(img);
pc.img = imgs;                    

Image image = ByteToImage(btimage);  //將二進位制陣列轉換成image圖片
pictureBox1.Image = image;                   //圖片顯示在picturebox框裡

//生成視訊的方法

List<byte[]> imgs = new List<byte[]>();
myPic pic = new myPic();                             //服務定義的物件
pic=client.queryVioVideo("", "", "", "");       //呼叫服務獲取視訊流
byte[] img = new byte[0];
img = (byte[])pic.video;       //pic.video是接收的視訊的二進位制陣列
PicClass pc = new PicClass();
imgs.Add(img);
pc.img=imgs;
File.WriteAllBytes("D://1.avi", pc.img.First()); //將視訊流寫入到檔案裡

 將此記錄下來以備以後查用