gpt4 book ai didi

c# - 从数据库加载后获取黑色图像

转载 作者:行者123 更新时间:2023-11-29 10:56:03 27 4
gpt4 key购买 nike

经过相当长一段时间的尝试和寻找一些答案后,我无法从 MySQL 加载图像。

基本上,用户从OpenFileDialog中选择一张图片,然后将其加载到PictureBox中(这很好用)。
然后用户单击一个按钮,将图片转换为 byte[] 并将其保存在数据库中。
最后,当我尝试将图片加载到另一个 PictureBox 中时,它全黑了。

将图片添加到数据库时:

public void PictureToDB(Image img)
{
MemoryStream tmpStream = new MemoryStream();
img.Save(tmpStream, ImageFormat.Png);
tmpStream.Seek(0, SeekOrigin.Begin);
byte[] imgBytes = new byte[5000];
tmpStream.Read(imgBytes, 0, 5000);

string query = "Update TABLE Set IMG = @imgBytes";
MySqlParameter param = new MySqlParameter("@img", imgBytes);

//Skipping connection to db and all... it works
}

从数据库获取图片:

public void DBToPicture()
{
string query = "Select IMG From TABLE Where ...";
//Skipping Command lines ...
MySqlDataReader reader = command.ExecuteReader();
DataTable myDT.Load(reader);

Byte[] data = new Byte[0];
data = (Byte[])(myDT.Rows[0]["PHOTOLOISANT"]);
MemoryStream mem = new MemoryStream(data);
MyPictureBox.Image = Image.FromStream(mem);
}

更多信息:

  • MySQL 中的类型为 varbinary(8000) 并包含此“89504e470d0a1a0a0000000d4948445200000280000001e00802000000bab34bb3000000017352474200aece1ce900000004 67414d41002e2e2e”更新
  • 之后
  • 图像在第一个 PictureBox 中加载时会转换为位图。

最佳答案

用于存储:

conn = new MySqlConnection("server=" + hostname + ";uid=" + username + ";pwd=" + password + ";database=databaseimage;Charset=latin1;");
conn.Open();
FileStream fs;
Byte[] bindata;
MySqlParameter picpara;
cmd = new MySqlCommand("INSERT INTO mypic (pic) VALUES(?pic)", conn);
picpara = cmd.Parameters.Add("?pic", MySqlDbType.MediumBlob);
cmd.Prepare();

//txtPicPath is the path of the image, e.g. C:\MyPic.png

fs = new FileStream(txtPicPath.Text, FileMode.Open, FileAccess.Read);
bindata = new byte[Convert.ToInt32(fs.Length)];
fs.Read(bindata, 0, Convert.ToInt32(fs.Length));
fs.Close();

picpara.Value = bindata;
cmd.ExecuteNonQuery();

要检索它:

if (conn == null) // Just to make sure that the connection was not severed
{


conn = new MySqlConnection("server=" + hostname + ";uid=" + username + ";pwd=" + password + ";database=databaseimage;Charset=latin1;");
conn.Open();

}
MemoryStream ms = new MemoryStream();
FileStream fs;
Byte[] bindata;

cmd = new MySqlCommand("SELECT pic FROM mypic WHERE id=3", conn);
bindata = (byte[])(cmd.ExecuteScalar());



ms.Write(bindata, 0, bindata.Length);
pb2.Image = new Bitmap(ms);

fs = new FileStream(name, FileMode.Create, FileAccess.Write);
ms.WriteTo(fs);

我将使用这些步骤从 MySql 存储和检索图像。

真诚的,

蒂亚古·拉詹德兰

**如果回复有帮助,请将其标记为答案,如果没有帮助,请取消标记。

关于c# - 从数据库加载后获取黑色图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43006955/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com