473,583 Members | 2,875 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

displaying images on a website from binary

I have several images i want to display in an ASP.Net application. The
images are being passed to me in binary format from another application. Is
there a good way to write them directly to an HMTL page without having to
save them to the server and create a URL to the virtual directory?

FYI: I currently am doing this with just single images. I do a
Response.Binary Write(byte) to display the one image. The advantage is that I
never have to worry about deleting the images at some later time.
Unfortunatly, this method does not lend itself to multiple images.
Jan 27 '06 #1
3 2352
simple example

1. My example Database stucture is as follows:
[FileId] UNIQUEIDENTIFIE R PRIMARY CLUSTERED KEY
[Data] IMAGE NOT NULL

2. ViewImage.aspx. cs code
-- BEGIN CODE --
using System;
using System.Data;
using System.Data.Sql Client;
using System.Web;
using System.Web.UI;
using System.Web.UI.W ebControls;
using System.Web.UI.W ebControls.WebP arts;
using System.Web.UI.H tmlControls;

public partial class ViewImage : System.Web.UI.P age
{
protected void Page_Load(objec t sender, EventArgs e)
{
Guid id;

try
{
id = new Guid(Request.Qu eryString["id"]);
}
catch
{
// display a default image or message
// saying id is invalid
return;
}

this.AttachImag eContent(id);

}

/// <summary>
///
/// </summary>
/// <param name="id"></param>
private void AttachImageCont ent(Guid id)
{
byte[] content = this.GetImageCo ntent(id);

Response.ClearC ontent();
Response.Conten tType = "image/jpg"; // get it from database
Response.Output Stream.Write(co ntent, 0, content.Length) ;
Response.End();
}

private const string ConnectionStrin g =
"server=(local) ;uid=;password= ;" +
"database=BlobD atabase;pooling =true;max pool size=1;min pool size=1;";

/// <summary>
///
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
private byte[] GetImageContent (Guid id)
{
// should be a stored procedure
string query = "SELECT [Data] FROM [File] WHERE [FileId] = @FileId";

SqlConnection connection = new SqlConnection(C onnectionString );
SqlCommand command = new SqlCommand(quer y, connection);
SqlParameter parameter = new SqlParameter("@ FileId",
SqlDbType.Uniqu eIdentifier);

parameter.Direc tion = ParameterDirect ion.Input;
parameter.Value = id;

command.Command Timeout = 120;
command.Command Type = CommandType.Tex t;
command.Paramet ers.Add(paramet er);

try
{
connection.Open ();
return (byte[]) command.Execute Scalar();
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (connection.Sta te != ConnectionState .Closed)
connection.Clos e();
}

}
}

-- END CODE --

3. Aspx Page html code

-- BEGIN CODE --
<%@ Page Language="C#" AutoEventWireup ="true" CodeFile="Defau lt.aspx.cs"
Inherits="_Defa ult" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dt d">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitl ed Page</title>
<style type="text/css">
</style>
</head>
<body>
<form id="form1" runat="server">
<asp:GridView ID="GridView1" runat="server" AutoGenerateCol umns=False>
<Columns>
<asp:TemplateFi eld>
<ItemTemplate >
<img
src='ViewImage. aspx?id=<%#Data Binder.Eval(Con tainer.DataItem , "FileId")%> '/>
</ItemTemplate>
</asp:TemplateFie ld>
<asp:BoundFie ld DataField="Firs tName"/>
</Columns>
</asp:GridView>
</form>
</body>
</html>
-- END CODE --

4. Apsx behind c# code

-- BEGIN CODE --

using System;
using System.Data;
using System.Configur ation;
using System.Web;
using System.Web.Secu rity;
using System.Web.UI;
using System.Web.UI.W ebControls;
using System.Web.UI.W ebControls.WebP arts;
using System.Web.UI.H tmlControls;

public partial class _Default : System.Web.UI.P age
{
protected void Page_Load(objec t sender, EventArgs e)
{
GridView1.DataS ource = GetDataSource() ;
GridView1.DataB ind();
}

private DataTable GetDataSource()
{
DataTable table = new DataTable();

table.Columns.A dd("FileId", typeof(string)) ;
table.Columns.A dd("FirstName" , typeof(string)) ;

DataRow row = table.NewRow();

row[0] = "e8302aa9-e82c-4d20-b3ae-79f8c5009dfb";
row[1] = "George W Bush";

table.Rows.Add( row);

return table;

}

}

-- END CODE --

Hope this helps

--
Milosz Skalecki
MCP, MCAD
"CLEAR-RCIC" wrote:
I have several images i want to display in an ASP.Net application. The
images are being passed to me in binary format from another application. Is
there a good way to write them directly to an HMTL page without having to
save them to the server and create a URL to the virtual directory?

FYI: I currently am doing this with just single images. I do a
Response.Binary Write(byte) to display the one image. The advantage is that I
never have to worry about deleting the images at some later time.
Unfortunatly, this method does not lend itself to multiple images.

Jan 27 '06 #2
If I understand you correctly, you already know how to send the image to the
client.

It sounds like you want to put them into a page, whether it is an HTML page
or an ASP.Net (HTML) page, on the client.

Forgive me if I tell you anything you already know. An HTML document is
text. It contains no binary data. It can contain multiple image elements
which contain a reference to a URL where the image file is located.

Now, as you've already successfully streamed an image to a browser, I'll
assume you know about setting the Response.Conten tType, and so on. The only
thing left to do is to take the page you have created to do this, and adapt
it to serve multiple images. This can most easily be done using a
QueryString. The image tag in the HTML document might look like the
following:

<img src="imagePage. aspx?id=1234">

The image page then reads the Request.QuerySt ring to determine the image to
send. It then sends the image just as you have already done. In other words,
the ASPX page is treated as if it were the image.

You should be able to see how you can have multiple references to the same
ASPX page using different QueryStrings in the same HTML document.

--
HTH,

Kevin Spencer
Microsoft MVP
..Net Developer
Who is Mighty Abbott?
A twin turret scalawag.

"CLEAR-RCIC" <CL*******@disc ussions.microso ft.com> wrote in message
news:48******** *************** ***********@mic rosoft.com...
I have several images i want to display in an ASP.Net application. The
images are being passed to me in binary format from another application.
Is
there a good way to write them directly to an HMTL page without having to
save them to the server and create a URL to the virtual directory?

FYI: I currently am doing this with just single images. I do a
Response.Binary Write(byte) to display the one image. The advantage is
that I
never have to worry about deleting the images at some later time.
Unfortunatly, this method does not lend itself to multiple images.

Jan 27 '06 #3
This is a good solution but I was hoping to not store the images in a
database or at all for that matter. I just want to write multiple images to
a page and forget about it.

"Milosz Skalecki" wrote:
simple example

1. My example Database stucture is as follows:
[FileId] UNIQUEIDENTIFIE R PRIMARY CLUSTERED KEY
[Data] IMAGE NOT NULL

2. ViewImage.aspx. cs code
-- BEGIN CODE --
using System;
using System.Data;
using System.Data.Sql Client;
using System.Web;
using System.Web.UI;
using System.Web.UI.W ebControls;
using System.Web.UI.W ebControls.WebP arts;
using System.Web.UI.H tmlControls;

public partial class ViewImage : System.Web.UI.P age
{
protected void Page_Load(objec t sender, EventArgs e)
{
Guid id;

try
{
id = new Guid(Request.Qu eryString["id"]);
}
catch
{
// display a default image or message
// saying id is invalid
return;
}

this.AttachImag eContent(id);

}

/// <summary>
///
/// </summary>
/// <param name="id"></param>
private void AttachImageCont ent(Guid id)
{
byte[] content = this.GetImageCo ntent(id);

Response.ClearC ontent();
Response.Conten tType = "image/jpg"; // get it from database
Response.Output Stream.Write(co ntent, 0, content.Length) ;
Response.End();
}

private const string ConnectionStrin g =
"server=(local) ;uid=;password= ;" +
"database=BlobD atabase;pooling =true;max pool size=1;min pool size=1;";

/// <summary>
///
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
private byte[] GetImageContent (Guid id)
{
// should be a stored procedure
string query = "SELECT [Data] FROM [File] WHERE [FileId] = @FileId";

SqlConnection connection = new SqlConnection(C onnectionString );
SqlCommand command = new SqlCommand(quer y, connection);
SqlParameter parameter = new SqlParameter("@ FileId",
SqlDbType.Uniqu eIdentifier);

parameter.Direc tion = ParameterDirect ion.Input;
parameter.Value = id;

command.Command Timeout = 120;
command.Command Type = CommandType.Tex t;
command.Paramet ers.Add(paramet er);

try
{
connection.Open ();
return (byte[]) command.Execute Scalar();
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (connection.Sta te != ConnectionState .Closed)
connection.Clos e();
}

}
}

-- END CODE --

3. Aspx Page html code

-- BEGIN CODE --
<%@ Page Language="C#" AutoEventWireup ="true" CodeFile="Defau lt.aspx.cs"
Inherits="_Defa ult" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dt d">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitl ed Page</title>
<style type="text/css">
</style>
</head>
<body>
<form id="form1" runat="server">
<asp:GridView ID="GridView1" runat="server" AutoGenerateCol umns=False>
<Columns>
<asp:TemplateFi eld>
<ItemTemplate >
<img
src='ViewImage. aspx?id=<%#Data Binder.Eval(Con tainer.DataItem , "FileId")%> '/>
</ItemTemplate>
</asp:TemplateFie ld>
<asp:BoundFie ld DataField="Firs tName"/>
</Columns>
</asp:GridView>
</form>
</body>
</html>
-- END CODE --

4. Apsx behind c# code

-- BEGIN CODE --

using System;
using System.Data;
using System.Configur ation;
using System.Web;
using System.Web.Secu rity;
using System.Web.UI;
using System.Web.UI.W ebControls;
using System.Web.UI.W ebControls.WebP arts;
using System.Web.UI.H tmlControls;

public partial class _Default : System.Web.UI.P age
{
protected void Page_Load(objec t sender, EventArgs e)
{
GridView1.DataS ource = GetDataSource() ;
GridView1.DataB ind();
}

private DataTable GetDataSource()
{
DataTable table = new DataTable();

table.Columns.A dd("FileId", typeof(string)) ;
table.Columns.A dd("FirstName" , typeof(string)) ;

DataRow row = table.NewRow();

row[0] = "e8302aa9-e82c-4d20-b3ae-79f8c5009dfb";
row[1] = "George W Bush";

table.Rows.Add( row);

return table;

}

}

-- END CODE --

Hope this helps

--
Milosz Skalecki
MCP, MCAD
"CLEAR-RCIC" wrote:
I have several images i want to display in an ASP.Net application. The
images are being passed to me in binary format from another application. Is
there a good way to write them directly to an HMTL page without having to
save them to the server and create a URL to the virtual directory?

FYI: I currently am doing this with just single images. I do a
Response.Binary Write(byte) to display the one image. The advantage is that I
never have to worry about deleting the images at some later time.
Unfortunatly, this method does not lend itself to multiple images.

Jan 27 '06 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
5025
by: Blaktyger | last post by:
How can this be done? Images are stored in a LONGBLOB field. When I try to display them, it prints out the binary data as it is... Thank you
3
3472
by: Dalan | last post by:
At first I was not certain what could cause Access 97 from displaying most jpeg images, but not all. After further testing, it seemed that all original images of less than 275 pixels per inch or less would display, but those close to 300 pixels/inch or greater would not (MS Access cannot recognize the file format xxx.jpg). The larger, original...
7
7584
by: Jim | last post by:
I am trying to display images that are stored in a database, and I am using a repeater control. What I still use the Response.BinaryWrite method with a binding expression, if so, what with the code look like?
15
9788
by: mleaver | last post by:
I want to open a second window and display a binary image that is returned from a java program via XMLRPC. The data returned is a binary encoded base64 png file. If I write the data out to a file on my server, I can display it using the following javascript: var windowHandle =...
3
2506
by: velu | last post by:
Asp.Net 2 I am trying to display Image from Northwind Database. I ran a queary "SELECT CategoryID, CategoryName, Description, Picture FROM Categories" but the Dataview displayes all the fields except Picture. so i add a Imagefield to display images..but now i get cross icon.. below is the code. correct me where i am wrong....
10
13396
by: eholz1 | last post by:
Hello Members, I am setting up a photo website. I have decided to use PHP and MySQL. I can load jpeg files into the table (medium blob, or even longtext) and get the image(s) to display without a problem. I am using chunk_split(data) and the base64_encode and base64_decode on the files. I do a select from the database, and then echo the...
14
9467
by: Brad | last post by:
I have a .net 2.0 web application project that creates a pdf file, saves the pdf to disk (crystal reports does this part), and then my code reads the pdf file and writes it to the httpresponse The web app works great on win2003 and xp and the end result is a pdf file is displayed in the browser. When I run the same code on Vista, the...
2
2639
by: pammyspammy | last post by:
Hi - Some background info: I'm helping to redesign an internal website at work, and I've decided to use CSS, though I don't really have any experience with it. I figure now's a good time to learn...and what I know right now, I've pretty much learned in the last week or two. At work, we have access to only two browsers, IE 6.0 and...
14
2103
by: ashraf02 | last post by:
i used a code from a website that allows you to display images. however everything works fine from storing the image to the database but it does not display the image. the following code is the one i have used. Storing the images: <HTML> <HEAD><TITLE>Store binary data into SQL Database</TITLE></HEAD> <BODY>
0
7888
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7811
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
8159
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8314
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
0
8185
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6571
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5689
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5366
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3836
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.