How do I place a picture on the form? - devexpress

Question on the NWindLayout demo
dxdemo://Win/XtraGrid/MainDemo/NWindLayout
scrin1
scrin2
How to place an image in the field?
Do I need to store the picture in the database?
or
The picture is stored on a local disk, and the database stores a link to the picture and the "Photo" field displays the photo according to the link?

As far as I understand, you have a column in your database, whose data are strings representing paths to images. And you are assigning PictureEdit as an in-place editor for the column. If so, the approach with using an unbound column is recommended since the PictureEdit editor does not provide the capability to show an image by setting a string path as an editor's value:
void gridView1_CustomUnboundColumnData(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDataEventArgs e) {
GridView view = sender as GridView;
if(e.Column.FieldName == "Image" && e.IsGetData) {
string fileName = view.GetRowCellValue(view.GetRowHandle(e.ListSourceRowIndex), "ImagePath");
e.Value = /* get image from cache by filename or load image from file and add to cache */
}
}
Take a look at the How to display external images in Grid if its data source contains links to the images example to see this approach in action.

Related

Where to store and how to remove images in a photo gallery?

I'm working on a photo gallery using ASP.NET.
I'm storing user's images in a SQL database. I'm not sure how should displaying images look like.
Let's say there is 1 picture per user, I was doing something like that:
get image from database
save it on server's disc as "file.jpg"
ASP:Image.uri = "file.jpg"
And that worked fine until I found out that If few users loads that page at the very same time, It might not work properly.
Then I though changing "file.jpg" into some random string would help me:
get image from database
save it on server's disc as "ABCDUDHDJSAKFHADGJKHAKADFAD.jpg"
ASP:Image.uri = "ABCDUDHDJSAKFHADGJKHAKADFAD.jpg"
File.Delete("~/ABCDUDHDJSAKFHADGJKHAKADFAD.jpg");
But it wasnt possible to delete this file because it was still being used by a server.
What would be the proper way to solve my problem? User in my photo gallery will eventually see 12 photos at the same time.
What I usually do is serve images from DB using a generic handler (ashx file).
What you need to do is create an ashx file and use something along these lines:
context.Response.BinaryWrite(myImage);
The you create image tags like so:
<img alt="whatever" src="/images.ashx?iid=1243 />
Where iid is the unique ID of the image in the DB.
You should not store the file actually. You should stream it. For example create a handler which returns the image from an user with a specific ID and call it with that ID like image.ashx?id=1. The handler could look like
Image image; // image from your database
using(MemoryStream ms = new MemoryStream())
{
image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
ms.WriteTo(context.Response.OutputStream);
}
Response.ContentType = "image/png";
This handler you can use like a static image file. So, you might even use it for a background-image:
<div style="background-image: url(image.ashx?id=1)">Username</div>

Asp: Repeater Image

hi,
I am facing a difficulty in understanding this example. from where the asp:repeater is taking the product images? and what is this path?
my questions are:
1) From where the background-image is taking the images, and what is this path?
2) How can I store Images in the database and assign them to each product accordingly (Binding the images with the products using the product_ID for example?
Code:
background-image: url('<%# Eval("ProductID", "../../../Img/Northwind/Products/{0}.jpg") %>');">
Best Regards.
About your question.
Technically, the repeater is not 'taking' images. It is generating CSS, with a reference to the background image. The browser displaying the page is then responsible for resolving the path and retrieving/displaying the images. In this case, the images are located 'up' a few directories from the location on which the page is found.
For serving images stored in a database, you have a few options.
The most common approach is to build an image handler; a simple ashx generic handler does the trick nicely.
Make the handler accept a productId via query string, grab the blob from the database using the productId, then write the blob with correct content type out to the response stream.
Once the handler is complete, you can reference the images by referring to the handler:
background-image: url('<%# Eval("ProductID", "/ImageHandler.ashx?ProductId={0}") %>');">
Edit: In response to your comment, a quick and dirty handler would look similar to this.
Obviously, you would need to add the actual logic to get the blob from the database.
public class ImageHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
int productId;
if (!int.TryParse(context.Request["productId"], out productId))
{
context.Response.End();
return;
}
byte[] blob = null; // get blob from DB
context.Response.ContentType = "image/jpeg";
context.Response.BinaryWrite(blob);
context.Response.End();
}
public bool IsReusable { get { return false; } }
}
1) From where the background-image is taking the images, and what is this path?
This is referencing to a physical folder on the hard drive. The folder has a collection of images called 1.jpg, 55.jpg etc which match up to the product id. In this sample they were probably just created manually but you could build an image upload system that would save image files with the same name as the product id of your products.
2) How can I store Images in the database and assign them to each product accordingly (Binding the images with the products using the product_ID for example?
Storing images in the database is different to whats going on here. As I say, this is just building a path to a file which has the same name as the product id. You -can- save your images in the database itself but I think this is a different discussion to the one you are looking at.
Basically the answer to your query is that in the sample they don't show you how to build a system which will let you add products to the database and upload images. It just shows you how to build some html based on existing database info and existing images.

How can I set an Image received from a method to the ImageButton?

I have a method that returns an Image.
How can I assign that Image to my ImageButton control so it has that image set?
Since you're dealing with HTML, you'll need to save the Image to a file, then use that file in the ImageButton's ImageUrl property.
I believe an ImageButton takes the path to an Image, not an actualy Image object, as the browser renders it a an tag.
What you could do is save thr image to disk, return the path to the image form your method and then have
<asp:ImgageButton id="imgButton1" runat="server" imageUrl="<%= GetImageUrl()>" />
The above syntax is not exact, it might be "<% Response.Write(GetImageUrl())>" but you get the picture
If this method returns an Image object, you will need to save out the image to a physical location on your webserver (somewhere like Server.MapPath("~/images/")). Then you will need to set the ImageUrl property of the ImageButton control to this location.
If this method returns a relative path to the image file, simply set the ImageUrl property of the ImageButton to the path returned by the method.
In short, you can't. Well not directly anyway.
You will have to write your image to file and point the image button at your image file
or you can have a web page that returns the image in the response and use that as your ImageUrl
The reason for this is that your ImageButton just renders to HTML which has no support for attaching images ATM.
You can try the following approach:
1) Firstly, get the binary data from the image:
public byte[] ImageToByteArray(System.Drawing.Image image)
{
MemoryStream ms = new MemoryStream();
image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
return ms.ToArray();
}
2) Secondary use Inline Images with Data URLs idea:
Inline images use the data URI scheme
to embed images directly within web
pages. As defined by RFC 2397, data
URIs are designed to embed small data
items as "immediate" data, as if they
were referenced externally. Using
inline images saves HTTP requests over
externally referenced objects.
System.Drawing.Image image = GetImageFromSomewhere(...);
byte[] imageData = ImageToByteArray(image);
string imageBase64 = Convert.ToBase64String(imageData);
string imageSrc = string.Format("data:image/gif;base64,{0}", imageBase64);
imgButton.Src = imageSrc;
But unfortunately, this won't work for IE5-7 (should work in IE8).

ASP.Net uploading an image for a users avatar

I dragged a file upload control to my Form, and I want to save the "image" the user chooses to an object[] Array so I can then save it.
I only need to know how to "grab" the image the user selects and save it as a byte[] array.Thanks
I would use the fileupload.SaveAs Method
if(myFileUpload.HasFile)
{
myFileUpload.SaveAs(filenmae);
}
Would you not consider outsourcing to gravatar, like in SO ?

How to generate HTML in a Pop Up window with Asp.Net

I have very simple html report generated from one of my objects on server. I generate html code at PageLoad because I need to clear that object from session and don't want ask external web service for data after user clicks on link button.
Roughly idea is that user clicks on button on page and the report will be displayed at new window.
As I said I have html generated at PageLoad and right now stored in unique file at server. I also thought that I could hide the html code in hidden control. But that wont work without extra work, that would convert html code into some nonsense string and restored later on.
I can manage to display my html code into current window by using Response.Write(myhtml as string);
So my question are:
where could I store my html code beyond file system (that is tricky with security issues)
how to display my htmlcode into new window on click event. What way could I use.
I found one possible solution described here.
UPDATE:
Just adding pieces of code. It displays html string in current window which is not exactly I want.
private void InitData(){
string filename = DateTime.Now.ToString("yyyyMMdd_HHmmssfff");
lbtnPrintOutOrder.CommandArgument = filename;
StreamWriter swXLS = new StreamWriter((MapPath("Files\\")) + filename);
string message = GetEmail();//get data form session object
swXLS.Write(message);//save data to file
swXLS.Close();
}
protected void lbtnPrintOutOrder_Command(object sender, System.Web.UI.WebControls.CommandEventArgs e)
{
string filePath = (MapPath("Files\\")) + e.CommandArgument.ToString();
string content;
using (StreamReader reader = File.OpenText(filePath)) {
content = reader.ReadToEnd();//get html from file
}
Response.Write(content);//load it to current window
Response.End();
}
One big question, is why do you need to clear the object from Session? Why cant you keep the object in session until after the string is displayed in the new window?
You could open an aspx page in the new window, use the string object stored in the session to output the html, and clear the session once the html is displayed.

Resources