How can I set an Image received from a method to the ImageButton? - asp.net

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

Related

Display resized image as a return value and not as page content

On Page_Load, I want the page to display an image the same way it displays when you "Open image in a new tab". In other words, I want the page to display as content type Image/jpeg instead of rendering the image in img HTML tag.
I successfully displayed an image this way using the below code on Page_Load:
Page.Response.ContentType="image/jpeg"
Page.Response.WriteFile("Path_to_the_Image")
However, my case requires displaying the image after being resized. I created a function that resizes the image and returns the resized image as Drawing.Bitmap
ResizeImage(bmSource As Drawing.Bitmap, TargetWidth As Int32, TargetHeight As Int32)
How can I use the returned value of that function and display it the same way I displayed the first image?
Page.Response.WriteFile() requires a String as an input. Is there a way where I can display the image of type Image or System.Bitmap directly into the page without having to save it in a temp folder and then use its path (As a String) and pass it to Page.Response.WriteFile?
Page.Response.ContentType="image/jpeg"
Using resizedImage As Bitmap = ResizeImage(source, 100, 100)
source.Dispose()
resizedImage.Save(Page.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg)
End Using
Page.Response.Flush()
That should work, maybe there's some error in my syntax. I do not often code in vb.net so.
Edited the code because of #Joel Coehoorn note

Why does ReportViewer image to Azure Blob Image results in an empty source?

I have uploaded some images to Azure blob storage (sample) which need to be referenced from a ReportViewer.
Right now, i have an image control bound to the results of a stured procedure that lists a couple images based on some criteria. The SP is outputting the list of images correctly (the sample link being one of them) but all i get from the image control is an empty block wrapping an img with an empty src.
The behaviour is still present even if i hardwire the sample image link into the image control instead of binding it to the query results (Only difference being that i now get a proper image in the Visual Studio preview).
I have tried disabling all proxies, whitelisting my azure blob domain from the default proxy but have met no success.
Right now my app is running on my development machine.
Update:
Hardwiring the sample link into the image control somehow works now, but i am still facing the main issue: databinding the image control to a sp-produced value results in an empty src. Setting the image source to external and the image to [RValues] is still not working. (Setting a text control to [RValues] will output a valid absolute url pointing to the correct image so i doubt that's the problem)
Update 2: The image is showing as a red x on the PDF export
Your question has nothing to do with Windows Azure.
In order to reference external images into your reports you need to do a couple of things. First of all you have to enable external images in your report viewer control:
ReportViewer1.LocalReport.EnableExternalImages = True
Also you need to set the source as external. And last but not least make sure the reportviewer httpHandler is properly registered with the web.config.
For more information check the relevant question here and documentation here.
If you're using Azure Storage SDK to upload the blobs, you're probably not specifying content type. By default Azure Storage assigns application/octet-stream to them and serves them using this content type when you access the files via url. ReportViewer doesn't work well with external images served like that.
So when uploading the image, make sure to specify ContentType property of the blob.
var blockBlob = container.GetBlockBlobReference("your-image.jpg");
blockBlob.Properties.ContentType = "image/jpeg";
await blockBlob.UploadFromStreamAsync(stream);
public async Task SaveFile(byte[] bytes, string feature, string fileName, string tenant)
{
CloudBlobDirectory blobDirectory = GetImageStorage(tenant, feature);
CloudBlockBlob blockBlob = blobDirectory.GetBlockBlobReference(fileName);
blockBlob.Properties.ContentType = "image/jpeg";
using (var ms = new MemoryStream(bytes))
{
await blockBlob.UploadFromStreamAsync(ms);
}
}

Resizing FileReference image then reuploading, only reuploads original image

I can;t figure out how to do this. Someone selects and image after calling FileReference.browse(). I take that image and make a thumbnail in flash.
Then I upload that image like so:
var newFileReq:URLRequest = new URLRequest(FILE_UPLOAD_TEMP);
newFileReq.contentType = "application/octet-stream";
var fileReqVars:URLVariables = new URLVariables();
fileReqVars.image = myThumbImage;
fileReqVars.folder = "Thumbs";
newFileReq.data = fileReqVars;
newFileReq.method = URLRequestMethod.POST;
//upload the first image
fileRef.addEventListener(Event.COMPLETE, onFirstFileUp);
fileRef.upload(newFileReq, "Filedata");
All this does it upload the original image. How do I change the fileRef to upload the new thumb? I have traced out the size of the "myThumbImage" and it is correct. I have placed it visually on the stage after creating the thumb, and it seems like it works. But when I upload it to an aspx page (that basically just throws it into a folder), it uploads the original larger image.
It won't work this way. FileReference.upload can only upload the file you opened, you can not override the image for security reasons.
What you should do to achieve this is encode the thumbnail data properly using Base64 (and use something like as3corelib to encode it to jpeg or png first if your thumb is just a bare bitmap data), and then use URLLoader to post the thumb to the server.

How to assign Bitmap to ImageControl

I am trying to bind image to image control, but image is bitmap data. How can I?
Do you mean that you have an image as binary data and you want to display it without saving it in a file? If yes, then one solution will be to create a separate aspx page or an http handler to return the image. You need to set the content type and length accordingly and use Response.BinaryWrite for serving the image.
See here for some more suggestions.

chart stream not rendering correctly

My controller, in a nutshell is this:
chart1.SeriesCollection.Add(SC);
using (MemoryStream ms = chart1.GetChartStream())
{
return File(ms.ToArray(), "image/png");
}
My view is this:
$('#targetDiv').load("Home/GetImage");
And I'm getting garbled characters when rendered. Any ideas?
thanks,
rodchar
You need to use an img tag:
<img src="Home/GetImage" alt="" />
When you write $('#targetDiv').load("Home/GetImage"); you are basically saying: send a GET requets to Home/GetImage using Ajax and if the request succeeds update the contents of #targetDiv with the result. As your controller action sends binary data, this binary data will be injected into the div.
You should set the content type of your response to accommodate the fact you're sending back an image. If you don't your binary stream will be interpreted as text, hence the garbled stuff you get.
There's a related question here: Can an ASP.NET MVC controller return an Image?
Try adding this to your code, before you read the file and send it back
this.Response.Clear();
this.Response.ContentType = "image/png";
on the markup side instead of putting the content into a div you need to put it into an image tag.

Resources