简体   繁体   English

如何在MVC3剃刀视图中显示存储在变量内的图像

[英]how do I display an image stored inside a variable in an MVC3 Razor View

I have a project in which I need to display thumbnails of image stored locally on the server. 我有一个项目,需要在其中显示本地存储在服务器上的图像的缩略图。 At first I tried using a jquery library to just "thumbify" the original images for my view. 最初,我尝试使用jquery库只是为我的视图“缩略图化”原始图像。 However, later I realized serving potentially thousands of images this way will really take up the bandwidth. 但是,后来我意识到以这种方式提供潜在的成千上万张图像确实会占用带宽。 So below is a method that extracts windows thumbnails instead (and only one full time image will be served on demand). 因此,下面是一种提取Windows缩略图的方法(仅按需提供一个全时图像)。

The problem is though, the thumbnail is now inside a variable in a model. 问题是,缩略图现在位于模型的变量内。 I don't know how actually display the image inside a Razor View. 我不知道如何在“剃刀视图”中实际显示图像。 So how do I display a System.Drawing.Icon item in a view? 那么,如何在视图中显示System.Drawing.Icon项目?

public static System.Drawing.Icon GetThumbnailImages(string imageFilePath) 
        {
            ShellFile shellFile = ShellFile.FromFilePath(imageFilePath);
            Bitmap shellThumb = shellFile.Thumbnail.ExtraLargeBitmap;
            System.Drawing.Icon shellThumb2 = shellFile.Thumbnail.Icon;
            //var shellThumb3 = shellFile.Thumbnail.MediumIcon;
            return shellThumb2;

        }

I would count the images and generate the tag in a loop which has an action as its source 我会计算图像并在以动作为源的循环中生成标签

for(int i= 0; i< MyModel.ImageCount(); i++){

     <img src="@Url.Action("GetImage", "Home")" />


}

Your action will need to send a file back. 您的操作将需要发送回文件。 See this as an example Overflow 以此为例溢出

This will load in the image 这将加载到图像中

i suggest you to create a new file with the new dimensions and then show it by url. 我建议您使用新尺寸创建一个新文件,然后按url显示。 you could use something like: 您可以使用类似:

public static string GenerateThumbnail(string filename, string target, int width)
{
    var img = Image.FromFile(filename);

    if (img.Width > width)
    {
        var bitmap = new Bitmap(width, GetTargetHeight(img.Width, width, img.Height));
        var g = Graphics.FromImage(bitmap);

        g.InterpolationMode = InterpolationMode.HighQualityBicubic;
        g.DrawImage(img, 0, 0, width, GetTargetHeight(img.Width, width, img.Height));
        g.Dispose();

        using (Stream file = File.OpenWrite(target))
        {
            CopyStream(bitmap.ToStream(ImageFormat.Jpeg), target);
        }

        return target;
    }

    return filename;
}

private static int GetTargetHeight(int originalWidth, int targetWidth, int originalHeight)
{
    return Convert.ToInt32(decimal.Round((decimal)targetWidth / originalWidth * originalHeight, 0));
}

and then use 然后使用

<img src="@GenerateThumbnail("path", "targetFile", 100)" />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM