2013-07-24 75 views
0

我使用以下代码检索图像和其他信息给用户。我还想在图像下方的文本框中获取图像文件路径显示。我一直在试图做到这一点,但没有成功。如何使用C#从mySQL获取图像文件路径

以下是我编写的代码,除了从mysql显示获取图像位置外,我还有其他事情要解决。

任何人都可以帮助我!

private void showData_Click(object sender, EventArgs e) 
      { 
       string myConnection = "datasource = localhost; port=3306; username=root; password=root"; 
       string Query = "select * from MawkMo.Enlist_info;"; 
       MySqlConnection sqlConnection = new MySqlConnection(myConnection); 
       MySqlCommand sqlCommand = new MySqlCommand(Query, sqlConnection); 
       MySqlDataReader myReader; 
       try 
       { 
        sqlConnection.Open(); 
        myReader = sqlCommand.ExecuteReader(); 
        while (myReader.Read()) 
        { 

    byte[] imgbyte = (byte[])(myReader["Photo"]); 
          if (imgbyte == null) 
          { 
           PhotoBox.Image = null; 
          } 
          else 
          { 
           //string imgPath = (string)sqlCommand.ExecuteScalar(); 
           //Photo_path.Text = imgPath; 
           MemoryStream mryStream = new MemoryStream(imgbyte); 
           PhotoBox.Image = System.Drawing.Image.FromStream(mryStream); 
          } 

         } 
        } 
       } 
       catch (Exception ex) 
       { 
        MessageBox.Show(ex.Message); 
       } 
+0

你为什么要将图像存储为BLOB。它不是一个好的选择。浏览器无法缓存文件。总是将图像存储在服务器上,然后可以将文件位置存储在数据库中。 – om471987

+0

@WYSIWYG这看起来不像是一个Web应用程序... –

+0

由于它直接存储在数据库中,因此图像不会显示为*“*”路径。 “MawkMo.Enlist_info”中是否有存储该路径名的列? –

回答

0

什么是PhotoBox.Image是?

MemoryStream imagebuf=new MemoryStream((byte[])myReader["Photo"]); 

//create image object 
System.Drawing.Image outImage=System.Drawing.Image.FromStream(imagebuf,true); 
outImage.Save(Server.MapPath(“PhotoTemp/”)+”2.gif”); 
+0

PhotoBox.Image是如果有图像将显示图像的框。 – user2042721

+0

系统无法识别此“Server.MapPath(”PhotoTemp /“)+”2.gif“” – user2042721

1

在代码的目前的形式,因为你没有实际存储的图像文件,你不能检索的映像文件的路径,你是把它作为一个系列数据库的字节。您不会在服务器硬盘上的任何位置找到图像文件,并且图像将无法在您的应用程序之外检索到。

如果有权访问独立于应用程序的图像是一个问题,或者如果您不希望图像存储在数据库中(性能问题),那么您需要重新设计数据库。在数据库保存中,您将发出Image.Save()方法将文件保存到特定位置,然后将该字符串(ImageLocation)存储到数据库中,而不是将图像本身存储为字节数组。检索过程就是检索ImageLocation字符串,并在Image.FromFile()方法中使用它。