开发者

Display image using C#

I'm using mvc2 and I would like to use action in controller, for example ShowSmallImage) and when I type www.url.com/ShowSmallImage that in browser the output is an image.

I tried something like this:

public Bitmap CreateThumbnail()
        {
            Image img1 = Image.FromFile(@"C:...\Uploads\Photos\178.jpg");

            int newWidth = 100;
            int newHeight = 100;
            double ratio = 0;

            if (img1.Width > img1.Height)
            {
                ratio = img1.Width / (double)img1.Height;
                newHeight = (int)(newHeight / ratio);
            }
            else
            {
                ratio = img1.Height / (double)img1.Width;
                newWidth = (int)(newWidth / ratio);
            }

            //a holder for the result 
            Bitmap result = new Bitmap(newWidth, newHeight);

            //use a graphics object to draw the resized image into the bitmap 
            using (Graphics graphics = Graphics.FromImage(result))
            {
                //set the resize quality modes to high quality 
                graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode开发者_如何学编程.HighQualityBicubic;
                graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                //draw the image into the target bitmap 
                graphics.DrawImage(img1, 0, 0, result.Width, result.Height);
            }

            return result;
        }

As a result I get only System.Drawing.Bitmap in browser. I suppose I need to set response/content type of the page but have no idea how to do it...

Thanks,

Ile


Create a fileresult and return the stream to the bitmap & set the content type:

    private FileResult RenderImage()
    {   
        MemoryStream stream = new MemoryStream();
        var bitmap = CreateThumbnail();
        bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);
        Byte[] bytes = stream.ToArray();
        return File(bytes, "image/png");

    }


In a controller, say ResourceController you could have an Action that returns a FileResult. Like so

    public FileResult Thumbnail()
    {
        var bitmap = // Your method call which returns a Bitmap

        var ms = new MemoryStream();
        bitmap.Save(ms, ImageFormat.Png);
        return new FileStreamResult(ms, "image/png");
    }

Then you can call http://www.mysite.com/Resource/Thumbnail.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜