Okay, this should be simple, but I just can't get it to work. I have an array of bytes, read from a png file. I'm trying to write a (very) simple HttpHandler to render the image:
context.Response.AddHeader("Content-Type", "image/png")
context.Response.BinaryWrite(bytes)
context.Response.End()
When I open the page in a browser, I just get gibberish,
�PNG IHDR���X��sRGB���gAMA�� �a pHYs���o�d` ...
It's obviously something with the header information I'm doing wrong. Any suggestions?
Try using the ContentType property instead of AddHeader:
context.Response.ContentType = "image/png";
...
Two more diagnostics:
If you use "save" in the browser and save it to a png file, does that render properly?
Use Wireshark to see what's really coming back in the response (which exact bytes etc)
Related
I am working with a web server that is only available on our internal network. I have a need to make an image it serves available to the public via our DMZ web server. The internal system has a GUI where anyone can upload any type of image so my HttpHandler must be flexible.
The bit of code I am currently using is:
WebResponse webResponse = WebRequest.Create(imagePath).GetResponse();
using (Stream stream = webResponse.GetResponseStream())
{
context.Response.Clear();
context.Response.ContentType = webResponse.ContentType;
stream.CopyTo(context.Response.OutputStream);
context.Response.End();
}
This seems to work and it serves up images correctly on HTML pages, but when I right click in Chrome and select "Open image in new tab" I get garbled up text like this:
Any suggestions to make my code better or is this okay?
Thanks!
EDIT: Seems like this code snippet does exactly what it should do. The problem was with the internally hosted image itself. It Served the exact same garbled text even before running through this HttpHandler.
Your content type header is probably not being set correctly.
Change it to context.Response.ContentType = "image/png";, but replace "png" with whatever the image time you are loading happens to be.
I'm so stuck on something i thought would be easy.
I have a DLL that returns an Image object.
I just cant figure out how to display that image on a webpage.
I've tried a few ways, and google a million different variations.
Is it not possible to just bind an Image object to an element on the page like an HtmlImage or a simple img?
Or do i need to convert the Image to a Stream? or a Bitmap? I'm really stuck!
Any help appreciated.....
V
With Asp.Net WebForm, the easiest way is to create a custom ashx file.
In Visual Studio, create a new Custom Handler (I'm not sure of the name of the template in Visual Studio). This will create a .ashx file.
In the code of this handler, write something like (does not have VS under the hand to test the syntax) :
public void ProcessRequest(System.Web.HttpContext context)
{
byte[] raw;
using(var ms = new MemoryStream()){
Image myImage = GetFromDll();
myImage.Save(ms, ImageFormat.Png);
raw=ms.ToArray();
}
context.Response.ContentType = "image/png";
context.Response.BinaryWrite(raw);
}
Then, in your browser, navigate to http://yourserver/app/yourhandler.ashx.
You can if you want add url parameter, and get it from the Request.QueryString collection
It's not as simple as binding. On the client side images are retrieved from the web server as a separate GET request, which means you have to have a URL that resolves to an image. The other option, as Asif suggested, is embedding your image in the HTML as a Base64 string, which is bad practice for shared images (see Steve B's comment).
You either have to provide an URL (route that returns the image file in MVC, or a custom page with proper content type and Response.Write in WebForms), or embed in html.
EDIT:
There is also a third option involving custom HTTP handlers. These have the advantage of bypassing the app framework and serving the content almost directly off the web server, see MSDN.
Convert your image to base64 string and then set it in the <img/> tag.
<img/> can show the image in base64 string.
Alternatively you can save the image and use the path in the <img/>.
I have a flash app which sends raw data for a jpg image to a particular url Send.aspx . In Send.aspx I am using request.binaryread() to get the total request length and then read in the data to a byte array.
Then I am writing the data as jpg file to the server. The code is given below:
FileStream f = File.Create(Server.MapPath("~") + "/plugins/handwrite/uploads/" + filename);
byte[] data = Request.BinaryRead(Request.TotalBytes);
f.Write(data, 0, data.Length);
f.Close();
The file is getting created but there is no image in it. It always shows up as empty in any graphic viewer. What part am I missing. Am I supposed to use jpg encoding first before writing it to file? Thanks in advance
Well, you should use a using statement for your file stream, but other than that it looks okay to me.
A few suggestions for how to proceed...
Is it possible that the client isn't providing the data properly? Perhaps it's providing it as base64-encoded data?
Have you already read some data from the request body? (That could mess things up.)
I suggest you look closely at what you end up saving vs the original file:
Are they the same length? If not, which is longer?
If they're the same length, do their MD5 sums match?
If you look at both within a binary file editor, do they match at all? Any obvious differences?
I'm developing a MVC application and I need to show an image in the browser, but I haven't the file physically on disk.
I only have a byte[] array in my model, with content of the image. Is there any "easy" trick to show the image in the view, without writing it to the disk?
The first approach that comes to my mind is writing a temp file, but:
What file name should I choose?
When should I delete it? I'm afraid that we will leak those files.
So I don't want to write the contents to a file. Is there any other approach?
Thanks in advanced.
EDIT: The result page is not only the image, I need to show some text, and below, the image, for example:
<%= Response.Write("Some text here") %>
<%= /* Here my image */ %>
I'd create a controller action that returns the image from a byte array. In your view, you can use the normal <img> tag, setting the src attribute to your controller action that renders the image.
It would be something like this:
[HttpGet]
public ActionResult Render(...)
{
byte[] imageBytes = ...;
MemoryStream imageStream = new MemoryStream();
imageStream.Write(imageBytes, 0, imageBytes.Length);
return new FileStreamResult(imageStream, "image/png"); // might be a different mime type depending on your image type
}
From your View you can then do:
<p>Some text here</p>
<img src="<%= Url.Action("Render", "MyController", new { params as needed }) %>" alt="Image" />
Several options:
Write a HTTP handler that will return the byte array and point the image URL to it
Write a custom image controller and point the image URL to it
Use the data URI scheme outputting the image data directly
If you just want the image and are not serving up HTML, just stream it out with the correct headers
You can have a page that will serve image like that:
var context = System.Web.HttpContext.Current;
context.Response.Clear();
context.Response.OutputStream.Write(buffer, 0, buffer.Length);
context.Response.End();
You should also set context.Response.ContentType to something meaningful. If you use ImageEncoder to generate array of bytes, you can use its mimeType property, if not - figure the way to provide a correct content-type (like "image/PNG")
I tried several ways to URL rewrite. The first way the image mime was clobbered and was consider an octet stream which didnt allow me to view the image in a browser (unless it was using img src). The 2nd way i wasnt convince it worked. Firefox displayed the img but said the length was 0 (i think it only worked bc it was in my cache).
How do i properly rewrite the image /abc/id/title.png to the internal location /static/user/name/id.png
In ASP.NET I might do something like this:
Response.Clear();
Response.ContentType = profile.AvatarMimeType;
Response.BinaryWrite(profile.Avatar.ToArray());
Where profile.AvatarMimeType is an appropriate mime type for a gif, jpeg, or png.
And where profile.Avatar.ToArray() is a binary content from the db sent out as an array of data!