c# - 使用 ASP.NET Web 服务从 SQL Server 检索图像

标签 c# asp.net asp.net-3.5

我有一个带有 Image 表的 SQL Server (2008 R2),该表有一个类型为 image 的列。我使用

将我的图像插入此列
Stream fs = FileUpload1.PostedFile.InputStream;
BinaryReader br = new BinaryReader(fs);
Byte[] bytes = br.ReadBytes((Int32)fs.Length);

//insert the file into database
string strQuery = "insert into pm005.images(imageName, type, alt, img)" + " values (@Name, @ContentType, @Alt, @Data)";
SqlCommand cmd = new SqlCommand(strQuery);

cmd.Parameters.Add("@Name", SqlDbType.VarChar).Value = filename;
cmd.Parameters.Add("@ContentType", SqlDbType.VarChar).Value = contenttype;
cmd.Parameters.Add("@Alt", SqlDbType.VarChar).Value = TextBox1.Text;
cmd.Parameters.Add("@Data", SqlDbType.Binary).Value = bytes;
InsertUpdateData(cmd);
lblMessage.ForeColor = System.Drawing.Color.Green;
lblMessage.Text = "File Uploaded Successfully";

private Boolean InsertUpdateData(SqlCommand cmd)
{
    // Open a connection the the SQL Server
    SqlConnection con = new SqlConnection();
    con.ConnectionString = "server=sql-server;integrated security=SSPI;database=pm005";

    cmd.CommandType = CommandType.Text;
    cmd.Connection = con;
    try
    {
        con.Open();
        cmd.ExecuteNonQuery();
        return true;
    }
    catch (Exception ex)
    {
        Response.Write(ex.Message);
        return false;
    }
    finally
    {
        con.Close();
        con.Dispose();
    }
}

我相信这工作正常,因为插入返回 true,我可以看到数据库中的数据。

但是我一辈子都看不出我应该如何恢复这张图片。具体来说,我想要的是能够调用我的网络服务,将 imageID 传递给它并将图像(并且只有图像)返回给我。很像它用 PHP 完成的。这是我现在使用的代码。

[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public System.Drawing.Image  getImage(int imageID, string uName, string pword)
{
    string str="";
 try
 {
     SqlCommand cmd = getSQLCommand("SELECT img FROM pm005.images WHERE id="+imageID);

 byte[] Img = (byte[])cmd.ExecuteScalar();

  // Convert the image record to file stream and display it to picture control
  str = Convert.ToString(DateTime.Now.ToFileTime());
  FileStream fs = new FileStream(str, FileMode.CreateNew, FileAccess.Write);
  fs.Write(Img, 0, Img.Length);
  fs.Flush();
  fs.Close();

 }
 catch
 {

 }
 finally
 {

 }

 System.Drawing.Image theImage = System.Drawing.Image.FromFile(str);
 return theImage;

}

这给出了错误:

System.ArgumentException: The path is not of a legal form.
   at System.IO.Path.NormalizePath(String path, Boolean fullCheck, Int32 maxPathLength)
   at System.IO.Path.GetFullPathInternal(String path)
   at System.IO.Path.GetFullPath(String path)
   at System.Drawing.IntSecurity.UnsafeGetFullPath(String fileName)
   at System.Drawing.IntSecurity.DemandReadFileIO(String fileName)
   at System.Drawing.Image.FromFile(String filename, Boolean useEmbeddedColorManagement)
   at WebService2.Service1.getImage(Int32 imageID, String uName, String pword)

我看了这么多教程,除了“使用 PHP”之外没有找到任何可靠的答案。如果必须的话,我会的,但肯定有一种方法可以在 ASP.NET 中做到这一点?

最佳答案

尝试指定完整的文件路径:

FileStream fs = new FileStream(@"C:\Temp\YourFile.jpg", FileMode.CreateNew, FileAccess.Write);

编辑:

而不是使用文件系统,听起来您想在内存中执行此操作:

public byte[] imageToByteArray(System.Drawing.Image imageIn)
{
    MemoryStream ms = new MemoryStream();
    imageIn.Save(ms,System.Drawing.Imaging.ImageFormat.Gif);
    return  ms.ToArray();
}

public Image byteArrayToImage(byte[] byteArrayIn)
{
     MemoryStream ms = new MemoryStream(byteArrayIn);
     Image returnImage = Image.FromStream(ms);
     return returnImage;
}

...

 System.Drawing.Image theImage = null;
 try
 {
     SqlCommand cmd = getSQLCommand("SELECT img FROM pm005.images WHERE id="+imageID);
     byte[] Img = (byte[])cmd.ExecuteScalar();
     theImage = byteArrayToImage(Img);
 }
 catch
 {

 }
 finally
 {

 }    
 return theImage;    
} 

关于c# - 使用 ASP.NET Web 服务从 SQL Server 检索图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15870781/

相关文章:

c# - 使用 EF Core 获取存储过程的输出参数值?

c# - 文本更改事件未触发

asp.net - 使用带有重写 URL 的表单例份验证/授权

asp.net - "Internal connection fatal errors"是什么原因造成的

c# - 如何解决错误无法在 iis 7 中添加具有唯一键属性 'value' 的添加类型的重复集合条目

asp.net-mvc - PDF 预览和查看

c# - 如何检查两个控件是否在 Windows 窗体中重叠

c# - 应用关闭 Xamarin Forms 后丢失数据/文件

c# - 按下按钮后设置文本框焦点

c# - 从域中获取 SPF 记录