简体   繁体   中英

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

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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