我正在为我的项目使用Windows Form和MySQL。因为我想保存图像并检索它。
我已经创建了一个名为'image'的表,
CREATE TABLE `image` (
`id` INT(15) NOT NULL AUTO_INCREMENT,
`extension` VARCHAR(50) NOT NULL,
`image` LONGBLOB NOT NULL,
PRIMARY KEY (`id`)
)
ENGINE=MyISAM
ROW_FORMAT=DEFAULT
AUTO_INCREMENT=2
并且
OpenFileDialog open = new OpenFileDialog();
// image filters
open.Filter = "Image Files(*.jpg; *.jpeg; *.gif; *.bmp; *.png)|*.jpg; *.jpeg; *.gif; *.bmp; *.png";
if (open.ShowDialog() == DialogResult.OK)
{
txt_imagePath.Text = open.FileName;
}
hp.getConnStr();
try
{
MySqlConnection connection = new MySqlConnection(hp.myConnStr);
MySqlCommand command = connection.CreateCommand();
command.CommandText = "insert into image (image) values ('"+txt_imagePath.Text +"')";
command.Connection.Open();
command.ExecuteNonQuery();
command.Connection.Close();
}
在“浏览”按钮单击事件中,..
文件已成功保存。现在我想检索那张图片并在图片框中显示。所以我试试这个波纹管代码,..
MySqlConnection connection = new MySqlConnection(hp.myConnStr);
MySqlCommand command = connection.CreateCommand();
MySqlDataReader Reader;
command.CommandText = "select image from image";
connection.Open();
Reader = command.ExecuteReader();
while (Reader.Read())
{
pictureBox1.Image = new Bitmap(Reader[0].ToString());
}
connection.Close();
但没用。
请帮帮我。
答案 0 :(得分:0)
我希望这样的事情会有所帮助:
public Bitmap loadImage(int imgID) { MySqlDataReader myData; MySqlCommand cmd = new MySqlCommand(); string SQL; byte[] rawData; MemoryStream ms; UInt32 FileSize; Bitmap outImage; SQL = "SELECT ImageName, ImageSize, Image FROM Images WHERE ImageID ="; SQL += imgID.ToString(); try { cmd.Connection = connection; cmd.CommandText = SQL; myData = cmd.ExecuteReader(); if (!myData.HasRows) throw new Exception("There are no blobs to save"); myData.Read(); FileSize = myData.GetUInt32(myData.GetOrdinal("ImageSize")); rawData = new byte[FileSize]; myData.GetBytes(myData.GetOrdinal("Image"), 0, rawData, 0, (Int32)FileSize); ms = new MemoryStream(rawData); outImage = new Bitmap(ms); ms.Close(); ms.Dispose(); myData.Close(); myData.Dispose(); cmd.Dispose(); return outImage; } catch (MySqlException ex) { MessageBox.Show(ex.Message); return null; } }
答案 1 :(得分:0)
您应该将blob字段读为MemoryStream
并使用Image
设置为控件的Image.FromStream()
属性。
答案 2 :(得分:0)
while (Reader.Read())
{
pictureBox1.Image = new Bitmap(new MemoryStream((byte[])Reader.GetValue(0)));
}
这应该这样做。 reader.GetValue()返回MySQL blob上的字节数组,这就是诀窍。