[英]C# Displaying Image from Database
I am having some issues displaying an image from a SQL Server database in a .NET application using C#. 我在使用C#从.NET应用程序中的SQL Server数据库中显示图像时遇到一些问题。 I've got the save part of the image working and it is storing the image as a series of byes in the database, but now I am running into issues trying to display it.
我已经完成了图像的保存部分的工作,并且将图像作为一系列常规存储在数据库中,但是现在我遇到了尝试显示它的问题。 Here is what I have:
这是我所拥有的:
using System;
using System.Configuration;
using System.Web;
using System.IO;
using System.Data;
using System.Data.SqlClient;
public class ShowImage : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
Int32 empno;
if (context.Request.QueryString["id"] != null)
empno = Convert.ToInt32(context.Request.QueryString["id"]);
else
throw new ArgumentException("No parameter specified");
context.Response.ContentType = "image/jpeg";
Stream strm = ShowEmpImage(empno);
byte[] buffer = new byte[4096];
int byteSeq = strm.Read(buffer, 0, 4096);
while (byteSeq > 0)
{
context.Response.OutputStream.Write(buffer, 0, byteSeq);
byteSeq = strm.Read(buffer, 0, 4096);
}
//context.Response.BinaryWrite(buffer);
}
public Stream ShowEmpImage(int empno)
{
string conn = CodProbs.Main.GetDSN();
SqlConnection connection = new SqlConnection(conn);
string sql = "SELECT CoverPhoto FROM Galleries WHERE GalleryID = @GalleryID";
SqlCommand cmd = new SqlCommand(sql, connection);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@GalleryID", empno);
connection.Open();
byte[] img = System.Text.Encoding.Unicode.GetBytes(Convert.ToString(cmd.ExecuteScalar()));
try
{
return new MemoryStream((byte[])img);
}
catch
{
return null;
}
finally
{
connection.Close();
}
}
public bool IsReusable
{
get
{
return false;
}
}
This is not resulting in any syntax errors and seems like it should be working. 这不会导致任何语法错误,并且看起来应该可以正常工作。 After stepping through it with the debugger, I can see that it is grabbing the proper data from the database.
在调试器中逐步了解它之后,我可以看到它正在从数据库中获取正确的数据。 However, I receive an error of: "The image ... cannot be displayed because it contains errors."
但是,我收到错误消息:“由于包含错误,图像无法显示。”
Any ideas on what the issue is here? 对这个问题有什么想法吗?
UPDATE Storing the image 更新存储图像
public static int AddGallery(GalleryDS galleryDS)
{
DataRow gallery = galleryDS.Tables[0].Rows[0];
int result = 0;
string sql = @"insert into Galleries (Title, Description, GalleryCategoryID, CreateDate, CreatedBy, CoverPhoto)
values (@Title, @Description, @GalleryCategoryID, @CreateDate, @CreatedBy, @CoverPhoto)
select scope_identity()";
using (SqlConnection conn = new SqlConnection(Main.GetDSN()))
{
SqlCommand command = new SqlCommand(sql, conn);
command.Parameters.AddWithValue("@Title", gallery["Title"]);
command.Parameters.AddWithValue("@Description", gallery["Description"]);
command.Parameters.AddWithValue("@GalleryCategoryID", 0);
command.Parameters.AddWithValue("@CreateDate", DateTime.Now);
command.Parameters.AddWithValue("@CreatedBy", gallery["CreatedBy"]);
command.Parameters.Add("@CoverPhoto", SqlDbType.VarBinary, Int32.MaxValue);
command.Parameters["@CoverPhoto"].Value = gallery["CoverPhoto"];
conn.Open();
result = Convert.ToInt32(command.ExecuteScalar());
conn.Close();
}
return result;
}
The ShowEmpImage method shouldn't convert it to a stream and then write it. ShowEmpImage方法不应将其转换为流,然后将其写入。 That's a waste of time.
那是浪费时间。
Change the definition to: 将定义更改为:
public Byte[] ShowEmpImage(int empno) {
string sql = "SELECT CoverPhoto FROM Galleries WHERE GalleryID = @GalleryID";
Byte[] result = null;
using (SqlConnection conn = new SqlConnection(CodProbs.Main.GetDSN())) {
using(SqlCommand cmd = new SqlCommand(sql, conn)) {
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@GalleryID", empno);
conn.Open();
result = (Byte[])cmd.ExecuteScalar();
}
}
return result;
}
To call it use the following: 要调用它,请使用以下命令:
Byte[] empImage = null;
empImage = ShowEmpImage(empno);
context.Response.Buffer = true;
context.Response.Clear();
context.Response.ContentType = "image/jpeg";
context.Response.Expires = 0;
context.Response.AddHeader("Content-Disposition", "attachment;filename=yourimagename.jpg");
context.Response.AddHeader("Content-Length", empImage.Length.ToString());
context.Response.BinaryWrite(empImage);
Side note: ALWAYS wrap unmanaged objects with the using
clause. 旁注:始终
using
子句包装非托管对象。 It cleans up after you and is simply good practice. 它会在您执行后进行清理,这只是一个好习惯。 Especially for database connections.
特别是对于数据库连接。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.