Display image from Web folder if image from database is null?

This has probably already been posted somewhere but I'm having trouble finding it.  I am displaying images from a SQL database in a detailsview.  If that field is null I would like to display a default .jpg from my web folders.  I see that it is easy to do with an asp:ImageField and the NullImageUrl, but I am using a TemplateField with the following type of setup and the NullImageUrl is not available to me? 

<asp:TemplateField HeaderText="Photo (if available)">

<ItemTemplate>

<img src="Handler.ashx?PhotoID=<%#Eval("ID") %>" alt=""/>

</ItemTemplate>

 

0
mbackues
3/21/2008 3:16:45 PM
asp.net.presentation-controls 72751 articles. 3 followers. Follow

9 Replies
1120 Views

Similar Articles

[PageSpeed] 36

Hi,

in your HttpHandler, the .ashx file, you could check if teh PhotoID is null and if it is output a default image instead of the requested one (when the id is not null).

Grz, Kris. 


Read my blog. Handy Firefox plugins for web developers.


Workaround for non working Mark as answer buttons.
0
XIII
3/21/2008 3:29:06 PM

Ok that sounds very logical, but what would the syntax be to show the default image?  In my case the ID would not be null, just the field from the table.  The Photo is stored with the rest of the info for a person.  Thank you for your assistance!!

here is the code from my handler.ashx:

public static Stream GetPhoto(int photoid)

{

using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["CISConnectionString"].ConnectionString))

{

using (SqlCommand command = new SqlCommand("Select [photo] FROM Exclusions WHERE ([id]=@id)", connection))

{

command.Parameters.Add(
new SqlParameter("@id", photoid));

connection.Open();

object result = command.ExecuteScalar();

try

{

return new MemoryStream((byte[])result);

}

catch

{

return null;

}

}

}

}

 

public void ProcessRequest(HttpContext context)

{

//Set up the response settings

context.Response.ContentType = "image/jpeg";

context.Response.Cache.SetCacheability(HttpCacheability.Public);

context.Response.BufferOutput = false;

// Setup the PhotoID Parameter

Int32 id = -1;

Stream stream = null;

id = Convert.ToInt32(context.Request.QueryString["PhotoID"]);

stream = GetPhoto(id);

if (stream != null)

{

const int buffersize = 1024 * 16;

byte[] buffer2 = new byte[buffersize];

int count = stream.Read(buffer2, 0, buffersize);while (count > 0)

{

context.Response.OutputStream.Write(buffer2, 0, count);

count = stream.Read(buffer2, 0, buffersize);

}

}

else

{

//show default image App_Themes/White/Images/no_image.jpg

}

}

 

0
mbackues
3/21/2008 3:57:13 PM

bump

0
mbackues
3/21/2008 6:53:23 PM

Hmm, just a thought but if the id's there and the image can be null can't you just include that in your query?

Something like

Select [photo] FROM Exclusions WHERE [id]=@id and photo is not null

Grz, Kris.


Read my blog. Handy Firefox plugins for web developers.


Workaround for non working Mark as answer buttons.
0
XIII
3/23/2008 12:01:15 PM

Hi mbackues ,

Try this.

 

        Bitmap bmap = new Bitmap(@"C:\Temp\TEST.JPG");
        context.Response.ContentType = "image/jpeg";
        context.Response.BufferOutput = false;
        bmap.Save(context.Response.OutputStream, ImageFormat.Jpeg);


 

Samu Zhang
Microsoft Online Community Support

Please remember to click “Mark as Answer” on the post that helps you, and to click “Unmark as Answer” if a marked post does not actually answer your question.
0
Samu
3/24/2008 3:19:42 AM

Thank you both for your notes.  Yes, if the photo field from the database is null, I want to display a default image in on the page in the image field, in the same place

that the image from the database is displayed if it is not null.

 

Can I simply store this default image within my website where the other images are stored?  What I don't know is the syntax to show the image

from that web folder after checking to see if the photo field is null.

The default image is in my App_Themes/White/Images folder within my website.

 

Samu I don't understand the use of the Save( ) command you've shown above, but thank you so much for your response!

0
mbackues
3/25/2008 6:56:48 PM

mbackues:
I don't understand the use of the Save( ) command

It saves the image to the outputstream. It's an alternative of the code that you use to write to the outputstream in your original code. The code provided by Samu can be used to stream out the image that you have in the App_Themes/... folder. Use the Server.MapPath() method to get the location of the image (like c:\...\Images\myimage.png for example).

Grz, Kris.


Read my blog. Handy Firefox plugins for web developers.


Workaround for non working Mark as answer buttons.
0
XIII
3/25/2008 9:24:14 PM

I am trying to add the code recommended above as shown below but I am getting another error:

 

public void ProcessRequest(HttpContext context)

{

//Set up the response settings

context.Response.ContentType = "image/jpeg";

context.Response.Cache.SetCacheability(HttpCacheability.Public);

context.Response.BufferOutput = false;

// Setup the PhotoID Parameter

Int32 id = -1;

Stream stream = null;

id = Convert.ToInt32(context.Request.QueryString["PhotoID"]);

stream = GetPhoto(id);

if (stream != null)

{

const int buffersize = 1024 * 16;

byte[] buffer2 = new byte[buffersize];

int count = stream.Read(buffer2, 0, buffersize);while (count > 0)

{

context.Response.OutputStream.Write(buffer2, 0, count);

count = stream.Read(buffer2, 0, buffersize);

}

}

else

{

System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(context.Server.MapPath("App_Themes/White/Images/no_image.jpg"));bmp.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);

}

}

I am getting an argument exception parameter not valid on the first line of the else statement.  Here is the stack trace text:

 System.ArgumentException was unhandled by user code
  Message="Parameter is not valid."
  Source="System.Drawing"
  StackTrace:
       at System.Drawing.Bitmap..ctor(String filename)
       at Handler.ProcessRequest(HttpContext context) in c:\Projects\ExclusionsWeb\Admin\Handler.ashx:line 74
       at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
       at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)

 

Help??  Thank you all for your time so far!

0
mbackues
3/26/2008 5:03:06 PM

Hi mbackues ,

I have tested the code and it works fine on my pc.

 

    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "image/jpeg";
        

        System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(context.Server.MapPath("App_Themes/Theme1/uu.jpg")); 
        bmp.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
        
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

 

 



Samu Zhang
Microsoft Online Community Support

Please remember to click “Mark as Answer” on the post that helps you, and to click “Unmark as Answer” if a marked post does not actually answer your question.
0
Samu
3/27/2008 9:01:34 AM
Reply:

Similar Artilces:

Displaying image from database(image datatype) to image control
Hie all...I'm a newbie at asp.net. I m currently using asp.net 2.0.I m having a problem with displaying images on my web form. Have tried looking thru all codes but i can't find a step by step tutorial for doing so. I understand that in asp.net 1.1, the detailsview can automatically be linked to the image field and display the image. But this is not possible now. So, i have decided to just display the image in an image control.from my understanding, 1. retrieve image from database and convert it to temporary image file in a file path. 2. use the image control's imageurl to point to the file....

Display image in image control from database?
Im looking for how to load an image in a database into an asp.net image control. I would like to be able to display images with assocated image captions in a page stored in a database. Samples I have found only deal with writing out the binary data directly into the page. Does anyone have a link on how to associate that image data in the database with an image control on the page? Have a look at this control in the control Gallery.  Should do what you want.JamesMy Blog: http://www.wintersfamily.plus.com/blogs/JamesWinters I found a few articles on this such as, http://blogs.ww...

Display Image from database in an Image control
I have uploaded images to a database and now I want to display the images in an image control.  How do I do it?  Any help is appreciated. http://aspalliance.com/articleViewer.aspx?aId=140 ThanksMark post(s) as "Answer" that helped youElectronic ScrewWebsite||Blog||Dub@i.net I've read the article before and it is not what I'm looking to do, only half of what I'm looking to do.  I need to retrieve the data information from a database and bind the image to an image control not a datagrid or gridview or datalist, a label control. Its literally it tho...

How to display a image from database on to image control of the webpage
Hi....... I wann to get the image from datbase(SQL-SERVER) and display on to webpage..by passing this image to image control on aspx..page I did the above displaying image with out image control on aspx page...but i couldn't get how to pass this image(stream of bytes) to image control.. as image control takes image from url....is there any way to pass the image to image cntrol... Thanks in Advance.... Jaya.......... hello check this page, i guess that's what u want !!! Retrieving Images from SqlServer in ASP .NETBilal Hadiar, MCP, MCTS, MCPD, MCTMicrosoft MVP - Te...

how to display image from web service in an image control
 Hi, I am using web service to fetch image from the video server, and displayed  in the web application, that is working fine,but I am using               Response.ContentType = "image/gif";              Response.BinaryWrite(arrpicture); but I want to display this image in the image control of the web application.Can any one help me out in this.Thanks,     You can do this using an HTTP Handler, using the same technique outlined...

retrieving images from database and displaying on Image control
Hi all i need a solution for displaying an image which must be retrieved from database table(photo displaying).I used the following code,but it shows error as "Invalid Parameter used"   page_load() {   cn.Open ();        SqlCommand command = new SqlCommand ("select *from image1 ", cn);                                 byte[] image = (byte[])( command.ExecuteScalar());     &n...

BUG: Image Controls in UpdateProgess Control: Can not use FindControl() methods to get Image
There is a single UpdateProgress control on the page. as such: <ajax:UpdateProgress  ID="UpdateProgress1" runat="server"   DisplayAfter="100" >         <ProgressTemplate>                <div style="border:2px solid #0099FF; background-color:#EFEFEF; padding:10px; width:200px; height:20px;">               Updating Panel            </div&...

Save Image Path into Database, Retrieve Image Path by Particular Image ID and Display Image through Gridview
Hi All, Currently, I have a file upload control in my aspx page to allow user to upload images. When the user clicks the SAVE button, the image will be saved in a particular folder named 'PMap' that located within the website. What I am trying to do here is to direct all uploaded images into a common image folder (in this case 'PMap') and then, retrieve the images and displayed it through a Gridview according to its respective image id. I have managed to store all uploaded images into a common image folder, PMap. However, I hope advice can be given on my following pro...

Display image in image control?
i am trying to retrive the image from sqlserver 2005 and how to put this image in image control in a web application?  See Saving and Displaying Photos in SQL Server using ASP.NETIf this post was useful to you, please mark it as answer. Thank you!...

displaying image in image control
I am inserting the image from the image control in the sql server database. now i want to read the image from the databse and show that image in the image control. i am able to read the image in streams and i am not able it to assign it to image control.kindly help. Hi,have a look at this linkhttp://www.aspdotnetcodes.com/Insert_Images_Database.aspxThanks,  hai go through the links http://www.odetocode.com/Articles/172.aspxhttp://chiragrdarji.wordpress.com/2007/03/05/storing-and-retrieving-image-in-sql-server/ Regards,M.VenkatesanMy Blog : http://venkat-dotnetsamples.blog...

How to display SQL Server Image column in a Image control in a web formview??
I have a SQL Server 2005 table with a column called WBTImage with a data type as image.  The images were already loaded into the table using a MSAccess program. I want to display the WBTImage column in a asp image control (imgTrain) on a web form.  There is no data binding property for the image column.  I have looked at many posts across many forumns and all of the solutions do not appear to work.  Some used the system.drawing,image.fromstream, some used binary.write, one showed a windows form with a data binding that I could not find and the other used a memorystream...

How to Display Image on Image control
 Dear All forum memberI am using <cc1:FileUploaderAjax> </cc1:FileUploaderAjax> for uploading image to database.I want to display the image in a image control as soon as user will finish his  browse for selecting Image before going to database. If any other way is possible with out using <cc1:FileUploaderAjax> </cc1:FileUploaderAjax> , that will also fine for me, but it should be ajax enabled.Mark As Answer if it helpsThanks & RegardGyana Ojha...

Help to retrieve image from database and display in Web.UI.WebControls.Image
Hi! I am a newbie. I want to retrieve image from database and display it in Web.UI.WebControls.Image.The control name is imgPicFace.And I want when it retrieve from database the control point like this >>>  imgPicFace.ImageUrl = "~/MyKad.bmp"; Please help and provide example code for me. Thank you.SAVE CODE:- 1 Bitmap b = new Bitmap(Server.MapPath("MyKad.bmp")); 2 System.Drawing.Image i = (System.Drawing.Image)b; 3 4 MemoryStream streamP = new MemoryStream(); 5 ...

how to save image on server and add image url to database for display on web page
I am trying to figure out how to allow a user to insert a new record into the database with the option of adding an image to the item.  The picture would then be saved on a web server and the link to the picture would be saved in a column of the table.  I would then need to display the picture along with its other information such as a description when the user selects the record from a drop down list on the page.  I have been searching everywhere and cannot find a good guide to help me accomplish this.  Can someone please help me?   There are a bunch of starter k...

Web resources about - Display image from Web folder if image from database is null? - asp.net.presentation-controls

Database - Wikipedia, the free encyclopedia
A database is an organized collection of data . The data are typically organized to model aspects of reality in a way that supports processes ...

Database - Wikipedia, the free encyclopedia
... requiring information. For example, modelling the availability of rooms in hotels in a way that supports finding a hotel with vacancies. Database ...

Ben Carson calls for a database on 'every foreigner'
Boston Herald Ben Carson calls for a database on 'every foreigner' Boston Herald Republican presidential candidate, Dr, Ben Carson, center, ...

GOP rivals condemn Donald Trump for backing Muslim database
COLUMBIA, S.C. (AP) — Retired neurosurgeon Ben Carson said Saturday that he wants to expand the government's surveillance operations aimed at ...

Donald Trump wants "surveillance of certain mosques," database of refugees - Videos - CBS News
... rally in Birmingham, Alabama, Republican presidential candidate Donald Trump called for increased scrutiny over mosques, along with a database ...

Trump: ‘I Didn’t Suggest A Database’ For Registering Muslims
Trump: ‘I Didn’t Suggest A Database’ For Registering Muslims

US Republican rivals blast Donald Trump for Muslim database comments
US Republican rivals blast Donald Trump for Muslim database comments - Donald Trump said he would implement a database to keep track of Muslims ...

MapR And Big Data In The World's Largest Biometric Database Project
India?s Aadhaar project is one of the world?s most ambitious big data projects, aiming to collect, store, and utilize biometric information from ...

WATCH 'TROJAN HORSE' Trump wants database for Syrian refugees in US
WATCH 'TROJAN HORSE' Trump wants database for Syrian refugees in US

Presidential Candidates Condemn Donald Trump's 'Database' Comment
... and Democratic presidential candidates have condemned Donald Trump for his recent statements suggesting the United States should start a database ...

Resources last updated: 11/27/2015 12:05:26 AM