Skip to main content
 首页 » 编程设计

c#之使用 C# 显示图像

2024年02月23日16mq0036

我正在使用 mvc2,我想在 Controller 中使用操作,例如 ShowSmallImage),当我在浏览器中键入 www.url.com/ShowSmallImage 时,输出是一个图像。

我试过这样的:

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; 
        } 

结果我在浏览器中只得到 System.Drawing.Bitmap。我想我需要设置页面的响应/内容类型,但不知道该怎么做...

谢谢,
艾尔

请您参考如下方法:

创建一个文件结果并将流返回到位图并设置内容类型:

    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"); 
 
    }