MySQL儲存jpg圖片 測試通過

來源:互聯網
上載者:User

1.MySQL下可通過blob,mediumbolb,longblob等類型來儲存圖片

2.不同的圖片檔案類似操作會有所不同,例如.bmp格式圖片

 

範例程式碼:

  //儲存圖片到MySQL

        private void btnOpenFile_Click(object sender, EventArgs e)
        {

    //開啟圖片檔案
            this.openFileDialog1.InitialDirectory = "C:\\";
            this.openFileDialog1.FileName = "";
            this.openFileDialog1.ShowDialog();

    //連接字串

            string connStr = "server=vitus;User Id=root;Password=******;Persist Security Info=True;database=Test";
            string sql = string.Format("insert into ImageTest values(@id,@picture)");

            FileStream fs = new FileStream(this.openFileDialog1.FileName,FileMode.Open);
            Byte[] bts = new Byte[fs.Length-1];
            fs.Read(bts,0,(int)fs.Length-1);

            MySqlConnection sqlConn = new MySqlConnection(connStr);
            MySqlCommand sqlComm = new MySqlCommand(sql,sqlConn);

            sqlComm.Parameters.Add("@id", MySqlDbType.Int32, 1);
            sqlComm.Parameters["@id"].Value = 2;
            sqlComm.Parameters.AddWithValue("@picture", bts);

            sqlConn.Open();
            sqlComm.ExecuteNonQuery();
            sqlConn.Clone();
        }

 

  //從MySQL中讀取並顯示圖片

        private void btnImageView_Click(object sender, EventArgs e)
        {
            string connStr = "server=vitus;User Id=root;Password=******;Persist Security Info=True;database=Test";
            string sql = string.Format("select * from ImageTest where id=2");

            MySqlConnection sqlConn = new MySqlConnection(connStr);
            MySqlCommand sqlComm = new MySqlCommand(sql, sqlConn);
            sqlConn.Open();
            MySqlDataReader dr = sqlComm.ExecuteReader(CommandBehavior.CloseConnection);
            Image image = null;
            while (dr.Read())
            {
                MemoryStream buff = new MemoryStream((byte[])dr[1]);
                image = Image.FromStream(buff, true);
                buff.Close();
            }

            this.pictureBox1.Image = image;
        }

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.