Wednesday, March 21, 2012

Image data read from SQL Server does not show up

Hi Guys,

I've been strugling with this problem all morning today.

Basically I store images in SQL Server 2000 database and then whould like to show them with


<img src="http://pics.10026.com/?src=viewImage.aspx?image_id=10" border=1>

My table structure is setup this way


TABLE [userImages] (
[imageFilename] [nvarchar] (128) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[imageContentType] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[imageFileSize] [bigint] NULL ,
[imageFileImage] [image] NULL )

and in viewImage.aspx I have:


if (dr.Read())
{

Response.ContentType = dr.GetString(dr.GetOrdinal("imageContentType"));
Response.BinaryWrite( (byte[]) dr["imageFileImage"] );
}

I have no prolems retrieving the data from DB. But the image does not display(in IE it shows a broken link image)

What's even more puzzling is I CAN display the same image from HDD like so:


FileStream fs = File.OpenRead("D:\\my_image.png");
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
fs.Close();

Response.ContentType = "application/octet-stream";
Response.BinaryWrite(buffer);

Am I missing something very obvious. I tried playing around with different ContentType's same result.

In my case I am forced to store images in the DB.

I've seen other examples on the net and theirs work. Please help.

Sincerely,
Vlad OrlovskyI found code very similar to yours in an article written by Dave Wanta:Retrieving Images from a Database ( C# ) - Part II

I adapted the code slightly to display the logo from the pub_info table in the Pubs database, and it worked fine for me (code below).

My gut feeling is that the ContentType you are using might not be correct?


using System;
using System.Collections;
using System.Configuration;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace CSharpTest
{
public class ViewImage : System.Web.UI.Page
{
private void Page_Load(object sender, System.EventArgs e)
{
//build our query statement
string sqlText = "SELECT logo, 'image/gif' AS contenttype FROM pub_info WHERE pub_id = @.pub_id ";
SqlConnection connection = new SqlConnection( "server=(local);database=pubs;Trusted_Connection=yes");
SqlCommand command = new SqlCommand( sqlText, connection);
command.Parameters.Add(new SqlParameter("@.pub_id", SqlDbType.Char,4)).Value=Request.QueryString["img"];

//open the database and get a datareader
connection.Open();
SqlDataReader dr = command.ExecuteReader();

if ( dr.Read()) //yup we found our image
{
Response.ContentType = dr["contenttype"].ToString();
Response.BinaryWrite( (byte[]) dr["logo"] );
}
connection.Close();

}
}
}

Terri

No comments:

Post a Comment