How do i URL rewrite an image properly? C# ASP.NET - c#

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!

Related

How to set ContentType for unknown image extensions?

I have a service returning an image stream to be displayed in UI. How do I set the ContentType value for this as I do not know what the image type will be? It can be image/jpeg, image/png etc.
fileContent.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("inline")
{
FileName = fileName
};
fileContent.Content.Headers.ContentType = new MediaTypeHeaderValue(??);
One way to solve this is by restricting users the type of files they can upload.
If you don't want to do that just add file type to image/ and send it as mime-type.
example,
png : image/png
gif : image/gif
You will also have to check whether the image is in compatible format for browser while sending. check this wiki page.
If it is not, then user is using some other application to process the image. So, you will have to use application/ and the file type. I strongly discouage use of this, because there could be only few selected type of images.
refer this for complete MIME-types. (Link)
Please Note: for jpg format, it should be jpeg.
Also, as mentioned by haim770, you can make use of System.Web.MimeMapping.GetMimeMapping which would return required mime-type, for all type of files, not just images.

Serve Image with IHttpHandler

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.

generic error in gdi+ decoding a valid jpeg

I have a valid jpeg frame that is taken from a camera:
http://www.developerinabox.com/test.jpg
I'm loading this with the below (example) code:
using System.Net;
using System.Drawing;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
WebRequest req = WebRequest.Create("http://www.developerinabox.com/test.jpg");
req.Timeout = 5000;
WebResponse resp = null;
resp = req.GetResponse();
if (resp != null)
{
var s = resp.GetResponseStream();
if (s != null)
{
Image img = Image.FromStream(s); //<-- Error thrown here
}
}
}
}
}
In windows XP/Vista/7 this works fine.
In windows 8 it's failing with "generic error in gdi+" I've tried loading it via WPF with the same result.
I can display the image on my windows 8 PC in google chrome but not in IE. It will display in both on windows XP/Vista/7.
I can open it on my Windows 8 box in Fireworks but trying to open it in paint gives me:
"This is not a valid bitmap file, or its format is not currently supported."
Any ideas?
Actually, it is an invalid JPEG image but, as you can see, many applications can decode this image seamlessly. This JPEG image has a bogus SOS marker (sorry for the technical information), this Scan header (SOS) says that this image has 1 color component but the Frame header (SOF, which appears before the SOS in the JPEG file structure) claims that it's a 3 components image.
So the Scan header has less information than required but the missing information can be replaced with default values and the JPEG image should be decoded with no issues, which is exactly what is happening. The missing information are the Huffman table indices and default sets of these indices can be assumed based on the JPEG coding type (sequential, progressive or lossless).
Well, it seems that Win8 is stricter when it comes to JPEG decoding. If you are curious you can take a look to this code I uploaded for another JPEG related issue (it's coded in VB.NET) and you can debug it to know where the problem is (you should check JPEG specifications as well).
EDIT: It was a valid JPEG image after all
This JPEG is a baseline multi-scan sequential image (similar to a planar image), not to be confused with a progressive image (which is similar to an interlaced image). So this JPEG has a smaller Scan header because the image is decoded one component at a time. Thus, this file has 3 non-contiguous Scan headers (SOS for 1st component, compressed data, SOS for 2nd component, compressed data,...), and each scan header has information for a single component.
Finally, if the problem was an incomplete or bogus scan header there would be a workaround (you could fix a bogus SOS header) but this is not the case. So you could make a request to the MS guys asking for support for multi-scan sequential JPEG images on Win8 ;-) or use some third-party JPEG decoding library.

Place Image from DLL onto a web page

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

HttpHandler to render a png from an array of bytes

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)

Categories