如何使用 c# 在 postgres 数据库中显示我的图片

本文关键字:显示 我的 数据库 何使用 postgres | 更新日期: 2023-09-27 18:35:31

我可以在我的帖子中保存我的图片,该图片位于图片框中。但是在如何使用 c# 在帖子数据库中显示我的图片之后?

FileStream fs = new FileStream(resimPath, FileMode.Open, FileAccess.Read); 
        BinaryReader br = new BinaryReader(fs);
        byte[] resim = br.ReadBytes((int)fs.Length);
        br.Close();
        fs.Close();            
        PostgisBaglan.Open();
        strEksenCizgisiUpdate = "INSERT INTO reismDatabase(resimismi,resimkendi) values('resim3','"+resim+"');";
        NpgsqlCommand EksenCizgisiUpdateCommand = new NpgsqlCommand(strEksenCizgisiUpdate, PostgisBaglan);
        EksenCizgisiUpdateCommand.ExecuteNonQuery();
        PostgisBaglan.Close();

 openFileDialog1.Filter = "Jpeg Dosyası (*.jpg)|*.jpg|Gif Dosyası (*.gif)|*.gif|Png Dosyası (*.png)|*.png|Tif Dosyası (*.tif)|*.tif";
        if (openFileDialog1.ShowDialog() == DialogResult.OK)
        {
            pictureBox1.Image = Image.FromFile(openFileDialog1.FileName);
            resimPath = openFileDialog1.FileName.ToString();
        }

如何使用 c# 在 postgres 数据库中显示我的图片

不能显示"来自数据库"的图像。

在应用程序中,需要从数据库中读取图像,然后显示它。

假设您的表如下所示:

create table reismDatabase (
  resimismi text,     -- or some variant
  resimkendi bytea
);

这将是将表内容读入图片对象的代码:

NpgSqlCommand cmd = new NpgsqlCommand("select resimismi, resimkendi from reismDatabase",
    conn);
NpgsqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
    string photoName = reader.GetString(0);
    Byte[] photoContents = (Byte[])Reader.GetValue(1);
    Image photo;
    if (photoContents != null)
    {
        using (Stream st = new System.IO.MemoryStream(photoContents))
            photo = Image.FromStream(st);
    }
}
reader.Close();

从那里,您可以将photo分配给您的pictureBox.Image

我找到了我的解决方案。

Postgisconn.Open();
        str= "INSERT INTO testimage (id, image) VALUES (1, lo_import('C://test.jpg'));";
        NpgsqlCommand cmmnd= new NpgsqlCommand(str, Postgisconn);
        cmmnd.ExecuteNonQuery();
        Postgisconn.Close();

我通过此查询将我的图像保存在我的数据库中。

pictureBox1.Image.Dispose();
        Postgisconn.Open();
        str= "SELECT lo_export(testimage.image, 'C://outputimage.jpg') FROM testimage WHERE id =1;";
        NpgsqlCommand cmmnd= new NpgsqlCommand(str, Postgisconn);
        cmmnd.ExecuteNonQuery();
        Postgisconn.Close();.
        pictureBox1.Image = Image.FromFile("C://outputimage.jpg");

通过此查询,我将我的数据库图像显示到图片框。

感谢所有回答我问题的人。