C#中檔案和byte[]互換問題

來源:互聯網
上載者:User

    如何將圖片和聲音轉化成byte[],並通過webservice進行傳輸?
    如何將webservice傳輸過來的byte[],轉化成我們想要的檔案?
    (一)檔案轉化為byte[]
    方法一:使用MemoryStream(MemoryStream的資料來自記憶體中緩衝區)
    System.IO.MemoryStream m = new System.IO.MemoryStream();
    System.Drawing.Bitmap bp = new System.Drawing.Bitmap(pname );
    bp.Save(m, System.Drawing.Imaging.ImageFormat.Jpeg);//將此映像以指定的格式儲存到指定的流中。
    byte[] b = m.GetBuffer();//從記憶體緩衝區中讀取
    方法二:使用FileStream(FileStream對象的資料來自檔案)
    FileStream stream = new FileInfo(path).OpenRead();
    Byte[] buffer = new Byte[stream.Length];
    //從流中讀取位元組塊並將該資料寫入給定緩衝區buffer中
    stream.Read(buffer, 0, Convert.ToInt32(stream.Length));
    (二)將byte[]轉化成檔案
    WebReference.MyService obj = new WebReference.MyService();
    Byte[] b = obj.downWav ("1001");//1001某條記錄的pid,返回這條記錄中的圖片的byte[]
    MemoryStream m = new MemoryStream(b);
    string file =string.Format(@"{0}\e.wav",
    Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase));
    //將下載下來的檔案放在目前的目錄下,儲存為e.wav;當然如果是圖片,可以儲存為a.jpg
    FileStream fs = new FileStream(file, FileMode.OpenOrCreate);
    m.WriteTo(fs);
    m.Close();
    fs.Close();
    m = null;
    fs = null;

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.