views:

120

answers:

5

I have a method that returns an Image.

How can I assign that Image to my ImageButton control so it has that image set?

+2  A: 

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.

John Fisher
How could I temporarily save the image to a file so I can assign it?
Sergio Tapia
yourImage.Save(...)
John Fisher
A: 

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.

Keith
How can I save the image to my webserver using code?
Sergio Tapia
image.Save(Server.MapPath("~/your/images/folder"));
Keith
+1  A: 

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

Jaimal Chohan
A: 

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.

Stephen lacy
A: 

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).

Alex