圖片二進制轉換與存入數據庫相關

關於轉換問題,剛開始我須要從數據庫讀出一個二進制數據流,並將其轉換成一個Image格式。sql

在不涉及數據庫的狀況下,我先將一個圖片轉換成一個二進制數組顯示出來,再寫一個方法將其轉換成圖片image格式。數據庫

1、 先不涉及數據庫,將圖片轉換成二進制,在將二進制轉換成圖片。數組

1.protected void Button1_Click(object sender, EventArgs e)
  {
  string str = null;
  PictureToBinary ptb = new PictureToBinary();
  // str = Convert.ToBase64String( ptb.Data("E:/workspace/asp/TEST/PictureTurnToBinary/PictureTurnToBinary/img/Tulips.jpg"));

  Image newImage = Image.FromFile(Server.MapPath("Tulips.jpg"));
  str =Convert.ToBase64String( ptb.PhotoImageInsert(newImage));
  Label1.Text = str;
//label能夠用response代替(response.write(str);)
 
 

 


  }

 

 

第一步,我將圖片轉換成二進制數組,並轉換成string格式,用一個Label展示(也能夠用Response直接輸出到頁面顯示)。產生的數組並非二進制構成的數據流而是一串字節,以下:函數

因此建議先將圖片壓縮一下,否則會很大。spa

第二步,將獲得的二進制字節碼轉換爲圖片格式。3d

2. protected void Button2_Click(object sender, EventArgs e)
   {
     PictureToBinary ptb = new PictureToBinary();
     Image newImage = Image.FromFile(Server.MapPath("Tulips.jpg"));
     WritePhoto(ptb.PhotoImageInsert(newImage));
   }
//圖片輸出到頁面
 public void WritePhoto(byte[] streamByte)
   {
     Response.ContentType = "image/JPEG";
     Response.BinaryWrite(streamByte);
  }
 public class PictureToBinary
  {

    public PictureToBinary()
    {
      //
      // TODO: 在此處添加構造函數邏輯
      //

   }

public byte[] PhotoImageInsert(System.Drawing.Image imgPhoto)
  {
  //將Image轉換成二進制流數據

  MemoryStream mstream = new MemoryStream();
  imgPhoto.Save(mstream, System.Drawing.Imaging.ImageFormat.Bmp);
  byte[] myData = new Byte[mstream.Length];
    mstream.Position = 0;
  mstream.Read(myData, 0, myData.Length);
    mstream.Close();
  return myData;
  }
}
 
 

 

 

 

結果以下:code

 

 2、將獲得的二進制數據保存到數據庫,再將其讀出。orm

 須要用到這麼幾個控件:一個fileLoad控件,兩個按鈕,分別是存入和讀取。blog

存入圖片到數據庫:圖片

protected void Saveintodatabase_Click(object sender, EventArgs e)
{
  //將圖片保存到數據庫
  //加載文件,並以字節數組格式存入數據庫
  HttpPostedFile loadPhoto = FileUpload1.PostedFile;
  //獲取記載圖片內容長度
  int photoLength = loadPhoto.ContentLength;
  //存爲字節數組
  byte[] photoArray = new byte[photoLength];
  Stream photoStream = loadPhoto.InputStream;
  photoStream.Read(photoArray, 0, photoLength);
  //鏈接數據庫讀取文件
  SqlConnection conn = new SqlConnection();
  conn.ConnectionString = "Data Source=localhost;Database=Test;User Id=sa;Pwd=123456789";
  string sql = "insert into Test_Picture values(@image,3)";
  SqlCommand cmd = new SqlCommand(sql,conn);
  cmd.CommandType = System.Data.CommandType.Text;
  cmd.Parameters.Add("@image",SqlDbType.Image);
  cmd.Parameters["@image"].Value = photoArray;
  conn.Open();
  //執行sql,成功執行返回1,不然返回0(insert,update,delete),其餘命令返回-1
  int row = cmd.ExecuteNonQuery();
  Response.Write(row);
  conn.Close();
}

 

讀取文件:

protected void PhotoShowInWebSite_Click(object sender, EventArgs e)
{
  //讀取數據庫圖片文件,並保存到本地。
  SqlConnection conn = new SqlConnection();
  conn.ConnectionString = "Data Source=localhost;Database=Test;User Id=sa;Pwd=123456789";

  //選擇你須要的字段值,這邊就直接賦值了
  string sql = "select Picture from Test_Picture where Number = 3";
  SqlCommand cmd = new SqlCommand(sql, conn);
  byte[] MyData = new byte[0]; 
  try
  {
    conn.Open();
    SqlDataReader mySqlDataReader;
    mySqlDataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
    if (mySqlDataReader.Read())
    {
      Response.Clear();

      Response.ContentType = "image/JPEG";
      Response.BinaryWrite((byte[])mySqlDataReader["Picture"]);

      /*將圖片寫入到本地d盤      

      //圖片字節流

      MyData = (byte[])mySqlDataReader["Picture"];

      int ArraySize = MyData.GetUpperBound(0);
      FileStream fs = new FileStream(@"d:\02.jpg", FileMode.OpenOrCreate, FileAccess.Write);
      fs.Write(MyData, 0, ArraySize);
      fs.Close();

      */

    }
    
  } catch (SqlException SQLexc)
  {
    Response.Write(SQLexc.ToString());
  }

    conn.Close();
}

 

 

以上爲整理的爲圖片二進制轉換與存取數據庫相關的內容。

 

新人報道,請多指教!

相關文章
相關標籤/搜索