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


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

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

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

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直接輸出到頁面顯示)。產生的數組並不是二進制構成的數據流而是一串字節,如下:

所以建議先將圖片壓縮一下,不然會很大。

第二步,將得到的二進制字節碼轉換為圖片格式。

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;
  }
}
 
         

 

 
        

 

結果如下:

 

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

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

存入圖片到數據庫:

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();
}

 

 

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

 

新人報道,請多指教!

 


免責聲明!

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



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