通过服务器从MySQL数据库检索图像

本文关键字:数据库 检索 图像 MySQL 服务器 | 更新日期: 2023-09-27 17:59:05

我正在制作一个程序,该程序需要从MySQL数据库表中获取映像的本地目录。目前,我已经使我想要检索的图像的目录等于MySQL表中的C:'Users'User'Pictures'PictureName.PNG。我编写的方法能够通过Select语句从数据库中检索这些数据,并使用从Select语句中检索到的路径将PictureBox图像设置为新的Bitmap

我在网上找不到我想要的信息,因为大多数答案都与使用MySQL中的BLOB字段来存储图像有关,但我的问题是,如果我将数据库放在服务器上,并且上面也有图片,我的方法会根据这些更改进行扩展吗?还是我必须添加其他功能才能在服务器上工作?

下面是我的代码:

public void setImage() {
    string path = sql.RetrieveImage(SelectQuery.RetrievePicture());
    PictureBox1.Image = new Bitmap(path);
}
public string RetrieveImage(Query query) {
    string path = "";
    // OpenDatabaseConnection() will open up a connection to the database
    // through connection and if successful, will return true.
    if (this.OpenDatabaseConnection()) {
        // query.ToSql() returns a string format of the select statement
        // required to retrieve the local image directory 
        using (MySqlCommand cmd = new MySqlCommand(query.ToSql(), connection)) {
            MySqlDataReader dataReader = cmd.ExecuteReader();
            dataReader.Read();
            path = dataReader[0] + "";
            dataReader.Close();
        }
        this.CloseDatabaseConnection();
    }
    return path;
}

通过服务器从MySQL数据库检索图像

将图像存储在数据库中是个坏主意。IMO.,存储图像文件的路径是一种更好的方式

这个SO问题有一些链接,可以找到非常好的支持信息。

然而,如果你必须走这条路,那么是的,BLOB字段(或SQLServer中的VarBinary(MAX))就是实现这一点的方法。你可以将这些图像作为Byte[]数据检索。