从二进制数据中检索图像时遇到问题。
我将图片保存为数据库varbinary(max)
并且工作正常,但是当我想在我的应用中显示我的图片时,MemoryStream
会在函数byteArrayToImage
中抛出错误< / p>
无效参数
这些是我将Image转换为二进制和二进制转换为图像的函数:
public byte[] imageToByteArray(System.Drawing.Image imageIn)
{
MemoryStream ms = new MemoryStream();
imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
return ms.ToArray();
}
public Image byteArrayToImage(byte[] byteArrayIn)
{
MemoryStream ms = new MemoryStream(byteArrayIn);
System.Drawing.Image returnImage = Image.FromStream(ms);
return returnImage;
}
这是添加代码:
private void button2_Click(object sender, EventArgs e)
{
openFileDialog1.Filter = "All Images|*.jpg; *.bmp; *.png";
byte[] img = imageToByteArray(pictureBox1.Image);
string CorrectFileName = System.IO.Path.GetFileName(openFileDialog1.FileName);
String HotelName = comboBox1.Text;
String RoomName = comboBox2.Text;
Dictionary<string, object> parametri = new Dictionary<string, object>(){
{ "Name", CorrectFileName },
{ "RoomName1", RoomName },
{ "HotelName1", HotelName },
{ "PictureDate", img }
};
AppHotels.DbHelper.IzvrsiProceduru("AddPicture", parametri);
MessageBox.Show("Image added");
}
这是显示图片的代码:
(我设置了一个断点来查看字节数组,看起来很好!ByteArr
返回byte [26])
private void button3_Click(object sender, EventArgs e)
{
flowLayoutPanel1.Controls.Clear();
String HotelName = comboBox3.Text;
Dictionary<string, object> parametri = new Dictionary<string, object>(){
{ "HotelName", HotelName }
};
DataTable d = new DataTable();
d = AppHotels.DbHelper.IzvrsiProceduru("ShowPictures", parametri);
byte[] byteArr = GetBytes((String)d.Rows[0]["PictureDate"]);
Button b = new Button();
b.BackgroundImageLayout = ImageLayout.Stretch;
b.BackgroundImage = byteArrayToImage(byteArr);
b.Height = 250;
b.Width = 200;
flowLayoutPanel1.Controls.Add(b);
}
我很抱歉这篇长篇文章。谢谢大家的阅读。
答案 0 :(得分:0)
我通过使用此代码从数据库获取字节数组来解决问题:
private void button1_Click_2(object sender, EventArgs e)
{
byte[] imgData;
using (SqlConnection conn = new SqlConnection(AppHotels.DbHelper.getConn()))
{
conn.Open();
string cmdText = "SELECT PictureDate from dbo.Pictures ";
SqlCommand cmd = new SqlCommand(cmdText, conn);
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
long bufLength = reader.GetBytes(0, 0, null, 0, 0);
imgData = new byte[bufLength];
reader.GetBytes(0, 0, imgData, 0, (int)bufLength);
MemoryStream ms = new MemoryStream(imgData);
ms.Position = 0;
Button b = new Button();
b.BackgroundImageLayout = ImageLayout.Stretch;
b.BackgroundImage = Image.FromStream(ms);
b.Height = 250;
b.Width = 200;
flowLayoutPanel1.Controls.Add(b);
}
}
}
}