Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
269 views
in Technique[技术] by (71.8m points)

Is there a recommended way to return an image using ASP.NET Web API

What is the best way to return an image with 2 parameters (x and y for resize).

For example

~/api/image12345/200/200

Will return a 200 by 200 jpg/png/or gif

Should I return a System.Drawing.Image object or manually define the HTTPReponseMessage.Content?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You shouldn't return a System.Drawing.Image, unless you also add a formatter which knows how to convert that into the appropriate bytes doesn't serialize itself as the image bytes as you'd expect.

One possible solution is to return an HttpResponseMessage with the image stored in its content (as shown below). Remember that if you want the URL you showed in the question, you'd need a route that maps the {imageName}, {width} and {height} parameters.

public HttpResponseMessage Get(string imageName, int width, int height)
{
    Image img = GetImage(imageName, width, height);
    using(MemoryStream ms = new MemoryStream())
    {
        img.Save(ms, System.Drawing.Imaging.ImageFormat.Png);

        HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
        result.Content = new ByteArrayContent(ms.ToArray());
        result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png");

        return result;
    }
}

But again, if you are doing this in many places, going the formatter route may be the "recommended" way. As almost everything in programming, the answer will depend on your scenario.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...