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.BinaryWrite(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. | | | | re: displaying images on a website from binary
simple example
1. My example Database stucture is as follows:
[FileId] UNIQUEIDENTIFIER PRIMARY CLUSTERED KEY
[Data] IMAGE NOT NULL
2. ViewImage.aspx.cs code
-- BEGIN CODE --
using System;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class ViewImage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Guid id;
try
{
id = new Guid(Request.QueryString["id"]);
}
catch
{
// display a default image or message
// saying id is invalid
return;
}
this.AttachImageContent(id);
}
/// <summary>
///
/// </summary>
/// <param name="id"></param>
private void AttachImageContent(Guid id)
{
byte[] content = this.GetImageContent(id);
Response.ClearContent();
Response.ContentType = "image/jpg"; // get it from database
Response.OutputStream.Write(content, 0, content.Length);
Response.End();
}
private const string ConnectionString =
"server=(local);uid=;password=;" +
"database=BlobDatabase;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(ConnectionString);
SqlCommand command = new SqlCommand(query, connection);
SqlParameter parameter = new SqlParameter("@FileId",
SqlDbType.UniqueIdentifier);
parameter.Direction = ParameterDirection.Input;
parameter.Value = id;
command.CommandTimeout = 120;
command.CommandType = CommandType.Text;
command.Parameters.Add(parameter);
try
{
connection.Open();
return (byte[]) command.ExecuteScalar();
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (connection.State != ConnectionState.Closed)
connection.Close();
}
}
}
-- END CODE --
3. Aspx Page html code
-- BEGIN CODE --
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"
Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
<style type="text/css">
</style>
</head>
<body>
<form id="form1" runat="server">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns=False>
<Columns>
<asp:TemplateField>
<ItemTemplate>
<img
src='ViewImage.aspx?id=<%#DataBinder.Eval(Containe r.DataItem, "FileId")%>'/>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="FirstName"/>
</Columns>
</asp:GridView>
</form>
</body>
</html>
-- END CODE --
4. Apsx behind c# code
-- BEGIN CODE --
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
GridView1.DataSource = GetDataSource();
GridView1.DataBind();
}
private DataTable GetDataSource()
{
DataTable table = new DataTable();
table.Columns.Add("FileId", typeof(string));
table.Columns.Add("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:
[color=blue]
> 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.BinaryWrite(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.[/color] | | | | re: displaying images on a website from binary
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.ContentType, 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.QueryString 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" <CLEARRCIC@discussions.microsoft.com> wrote in message
news:48AAC079-3683-47B0-A8D6-8A1F519DB846@microsoft.com...[color=blue]
>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.BinaryWrite(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.[/color] | | | | re: displaying images on a website from binary
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:
[color=blue]
> simple example
>
> 1. My example Database stucture is as follows:
> [FileId] UNIQUEIDENTIFIER PRIMARY CLUSTERED KEY
> [Data] IMAGE NOT NULL
>
> 2. ViewImage.aspx.cs code
> -- BEGIN CODE --
> using System;
> using System.Data;
> using System.Data.SqlClient;
> using System.Web;
> using System.Web.UI;
> using System.Web.UI.WebControls;
> using System.Web.UI.WebControls.WebParts;
> using System.Web.UI.HtmlControls;
>
> public partial class ViewImage : System.Web.UI.Page
> {
> protected void Page_Load(object sender, EventArgs e)
> {
> Guid id;
>
> try
> {
> id = new Guid(Request.QueryString["id"]);
> }
> catch
> {
> // display a default image or message
> // saying id is invalid
> return;
> }
>
> this.AttachImageContent(id);
>
> }
>
> /// <summary>
> ///
> /// </summary>
> /// <param name="id"></param>
> private void AttachImageContent(Guid id)
> {
> byte[] content = this.GetImageContent(id);
>
> Response.ClearContent();
> Response.ContentType = "image/jpg"; // get it from database
> Response.OutputStream.Write(content, 0, content.Length);
> Response.End();
> }
>
> private const string ConnectionString =
> "server=(local);uid=;password=;" +
> "database=BlobDatabase;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(ConnectionString);
> SqlCommand command = new SqlCommand(query, connection);
> SqlParameter parameter = new SqlParameter("@FileId",
> SqlDbType.UniqueIdentifier);
>
> parameter.Direction = ParameterDirection.Input;
> parameter.Value = id;
>
> command.CommandTimeout = 120;
> command.CommandType = CommandType.Text;
> command.Parameters.Add(parameter);
>
> try
> {
> connection.Open();
> return (byte[]) command.ExecuteScalar();
> }
> catch (Exception ex)
> {
> throw ex;
> }
> finally
> {
> if (connection.State != ConnectionState.Closed)
> connection.Close();
> }
>
> }
> }
>
> -- END CODE --
>
> 3. Aspx Page html code
>
> -- BEGIN CODE --
> <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"
> Inherits="_Default" %>
>
> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
> "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
> <html xmlns="http://www.w3.org/1999/xhtml" >
> <head runat="server">
> <title>Untitled Page</title>
> <style type="text/css">
> </style>
> </head>
> <body>
> <form id="form1" runat="server">
> <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns=False>
> <Columns>
> <asp:TemplateField>
> <ItemTemplate>
> <img
> src='ViewImage.aspx?id=<%#DataBinder.Eval(Containe r.DataItem, "FileId")%>'/>
> </ItemTemplate>
> </asp:TemplateField>
> <asp:BoundField DataField="FirstName"/>
> </Columns>
> </asp:GridView>
> </form>
> </body>
> </html>
> -- END CODE --
>
> 4. Apsx behind c# code
>
> -- BEGIN CODE --
>
> using System;
> using System.Data;
> using System.Configuration;
> using System.Web;
> using System.Web.Security;
> using System.Web.UI;
> using System.Web.UI.WebControls;
> using System.Web.UI.WebControls.WebParts;
> using System.Web.UI.HtmlControls;
>
> public partial class _Default : System.Web.UI.Page
> {
> protected void Page_Load(object sender, EventArgs e)
> {
> GridView1.DataSource = GetDataSource();
> GridView1.DataBind();
> }
>
> private DataTable GetDataSource()
> {
> DataTable table = new DataTable();
>
> table.Columns.Add("FileId", typeof(string));
> table.Columns.Add("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:
>[color=green]
> > 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.BinaryWrite(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.[/color][/color] |  | Similar .NET Framework bytes | | | /bytes/about
We are a network of experts and professionals in IT and software development that help one another with answers to tough questions and share insights.
Get the best answers to your questions from over 226,501 network members.
|