圖片保存到數據庫以及C#讀取圖片


圖片保存到數據庫,如果是sqlserver就是Image類型,如果保存到Oracle就是blob類型,在c#中相對應的就是byte[]類型,同時只需要對讀出的數據強制轉換就行(byte[])object.

1. 將圖片保存為byte數組

    //參數是圖片路徑,返回Byte[]類型

   

 public byte[] GetPictureData(string imagepath)
    {
       FileStream file = new FileStream(imagepath, FileMode.Open);
       byte[] by = new byte[file.Length];
       file.Read(by, 0, by.Length);
       file.Close();
       return by;
    }

 

    //參數是Image,返回Byte[]類型

    

public byte[] GetPictureData(System.Drawing.Image imgPhoto)
    {
       //將Image轉換成流數據,並保存為byte[]
       MemoryStream mstream=new MemoryStream();
       imgPhoto.Save(mstream,System.Drawing.Imaging.ImageFormat.Bmp);
       byte[]byData=new Byte[mstream.Length];
       mstream.Position=0;
       mstream.Read(byData,0,byData.Length);
       mstream.Close();
       return byData;
    }  

 

2. 將byte數組轉換為圖片

    

//參數是Byte[]類型,返回值是Image對象

    public System.Drawing.Image ReturnPhoto(byte[] streamByte)
    {
        MemoryStream me = new MemoryStream(streamByte);
        return System.Drawing.Image.FromStream(ms);
    }  

    //參數是Byte[]類型,沒有返回值,這是針對asp.net中把圖片從輸出到網頁上
    public void WritePhoto(byte[] streamByte)
    {
        Response.ContentType="image/GIF";
        Response.BinaryWrite(streamByte);
    }

 

3. byte[]和string的轉換   

    //byte[] 轉換為string
    byte[] by;
    string str=System.Convert.ToBase64String(by);
    //string轉換為byte[]
    string str;
    byte[] by=System.Convert.FromBase64String(str);

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM