PDA

View Full Version : how to view an image in access db


davidc2
07-19-2006, 06:34 AM
How can I view an image saved on an access database from an asp.net 2005 webpage?

I created a DataSource and on the "preview" (when I test it) there's the image but how can I like display it on a picture box or something?

Thx.

ericTheGoldfish
07-19-2006, 07:09 AM
you should be able to use a datareader to read the bytes from the database and write them to the page:

DataReader r = command.ExecuteReader();

if (r.Read()) {
byte[] bytes - (byte[])r["field_from_database"];
Response.BinaryWrite(bytes);
}
r.Close();

I would typically put this into a HttpHandler and use the handler in the src for an image tag

davidc2
07-19-2006, 07:13 AM
I'm a newbie can you please help me a little more? I didn't understand what you said about the handler

davidc2
07-19-2006, 07:16 AM
Ok here's what I've done:
- Created the Access Data Base
- In Visual Studio created a Data Source that calls that database, now what?

ericTheGoldfish
07-19-2006, 07:42 AM
I usually create an image handler class(.ashx file):

public class ImageFromDB : IHttpHandler {
public void ProcessRequest(HttpContext context) {
string connectionString =
WebConfigurationManager.ConnectionStrings["Pubs"].ConnectionString;
// Get the ID for this request.
string id = context.Request.QueryString["id"];
if (id == null) throw new ApplicationException("Must specify ID.");
// Create a parameterized command for this record.
SqlConnection con = new SqlConnection(connectionString);
string SQL = "SELECT logo FROM pub_info WHERE pub_id=@ID";
SqlCommand cmd = new SqlCommand(SQL, con);
cmd.Parameters.AddWithValue("@ID", id);
try {
con.Open();
SqlDataReader r =
cmd.ExecuteReader(CommandBehavior.SequentialAccess);
if (r.Read()) {
int bufferSize = 100; // Size of the buffer.
byte[] bytes = new byte[bufferSize]; // The buffer.
long bytesRead; // The # of bytes read.
long readFrom = 0; // The starting index.
// Read the field 100 bytes at a time.
do {
bytesRead = r.GetBytes(0, readFrom, bytes, 0, bufferSize);
context.Response.BinaryWrite(bytes);
readFrom += bufferSize;
} while (bytesRead == bufferSize);
}
r.Close();
}
finally {
con.Close();
}
}

public bool IsReusable {
get { return true; }
}
}

You will then need to register the handler in the web.config file:

<httpHandlers>
<add verb="GET" path="ImageFromDB.ashx" type="ImageFromDB" />
</httpHandlers>

You should then be able to call the image as follows:

<img src="ImageFromDB.ashx?ID=1389" />

davidc2
07-19-2006, 07:55 AM
Can you create the files and put them on a zip?

I'm totally lost, you aren't talking to an expert.

Please.

And if you do please include the access database

ericTheGoldfish
07-19-2006, 11:17 PM
Check your private messages

davidc2
07-20-2006, 03:53 AM
I wonder if someone can help me do this in visual basic, thanks anyway eric