C# MVC4将图像调整为最大高度或最大宽度

C# MVC4将图像调整为最大高度或最大宽度,c#,asp.net-mvc-4,razor,C#,Asp.net Mvc 4,Razor,我正在创建MVC4网站,希望显示数据库中所有允许的图片。问题是图片的大小不同,有些是纵向的,有些是横向的。首先,所有图像都需要保持纵横比。每个图像都显示在div命名卡中,并且应该具有标准大小(在控件中设置的大小)。所以我需要调整图像的大小,使其高度和宽度都不能超过控件的维度高度和宽度。例如,如果某些图像具有纵向方向,则高度不得超过控件的高度,因此,如果图像具有横向方向,则应按此方式调整其大小,宽度不得超过控件的宽度。 我以这种方式显示图片: 控制器 如何调整图像大小以满足要求?唯一的方法是裁剪肖

我正在创建MVC4网站,希望显示数据库中所有允许的图片。问题是图片的大小不同,有些是纵向的,有些是横向的。首先,所有图像都需要保持纵横比。每个图像都显示在div命名卡中,并且应该具有标准大小(在
控件中设置的大小)。所以我需要调整图像的大小,使其高度和宽度都不能超过
控件的维度高度和宽度。例如,如果某些图像具有纵向方向,则高度不得超过
控件的高度,因此,如果图像具有横向方向,则应按此方式调整其大小,宽度不得超过
控件的宽度。 我以这种方式显示图片:

控制器


如何调整图像大小以满足要求?

唯一的方法是裁剪肖像照片以适应图像。我有一个VB函数,完全按照你说的做,从顶部裁剪25%的额外高度像素,其余的从底部裁剪。大多数照片都是这样的。我在一个旅游网站上用这个

@foreach (var item in Model)
{
    <div class="photo-index-card">
        <div style="float:left; padding: 2px 2px 2px 2px; margin: 0px 0px 10px 0px; height: 20px;">
            <div>@item.Title</div>
        </div>

        <div style="float:left;">
            @if (item.PhotoFile != null)
            {
                <a href="@Url.Action("Display", "Photo", new { id = item.PhotoID })">
                    <img class="photo-index-card-img" src="@Url.Action("GetImage", "Photo", new { id = item.PhotoID })" />
                </a>
            }
        </div>                
    </div>
}
公共共享函数saveAshumbnaild裁剪为字符串(ByVal path为字符串,ByVal archivo为字符串,ByVal NewWidth为整数,ByVal NewHeight为整数)
'声明两个名为
'调整图像宽度和调整图像高度。
Dim adjustedImageWidth,adjustedImageHeight为整数
'声明一个名为Image类型的Image的变量。
将图像变暗为图像
Dim ThumbFileName,扩展名为字符串,convertToGIF为布尔值=False
如果InStrRev(archivo,“.”)大于0,则
扩展=中间(archivo,InStrRev(archivo,“.”)。ToString.ToLower
ThumbFileName=Mid(archivo,1,InStrRev(archivo,“.”)-1)+“_tb”+修剪(新宽度)+“x”+修剪(新高度)+扩展名
其他的
扩展名=“desconocida”
ThumbFileName=archivo+“_tb”+修剪(新宽度)+“x”+修剪(新高度)
如果结束
如果不是My.Computer.FileSystem.FileExists(路径+“\”+拇指文件名)和My.Computer.FileSystem.FileExists(路径+“\”+archivo),则
'从图像文件中获取图像对象;
'将图像对象指定给theImage变量。
theImage=System.Drawing.Image.FromFile(路径+“\”+archivo)
如果图像高度>新高度或图像宽度>新宽度,则
如果图像高度*新宽度/图像宽度>新高度,则
“tengo que Reducer el alto”
adjustedImageHeight=新高度
"保持率",
adjustedImageWidth=图像宽度*(adjustedImageHeight/TheImageHeight)
其他的
adjustedImageWidth=NewWidth
"保持率",
adjustedImageHeight=图像高度*(adjustedImageWidth/TheImageWidth)
如果结束
其他的
“不,我不知道你在想什么
返回阿奇沃
如果结束
将cropRect设置为矩形
如果adjustedImageHeightNewWidth,则
“我们的时代是一个充满活力的时代
adjustedImageHeight=新高度
adjustedImageWidth=图像宽度*(adjustedImageHeight/TheImageHeight)
尺寸宽度范围=调整图像宽度-新宽度
cropRect=新矩形(宽度范围/2,0,新宽度,新高度)
否则,如果adjustedImageHeight>NewHeight或adjustedImageWidth@foreach (var item in Model)
{
    <div class="photo-index-card">
        <div style="float:left; padding: 2px 2px 2px 2px; margin: 0px 0px 10px 0px; height: 20px;">
            <div>@item.Title</div>
        </div>

        <div style="float:left;">
            @if (item.PhotoFile != null)
            {
                <a href="@Url.Action("Display", "Photo", new { id = item.PhotoID })">
                    <img class="photo-index-card-img" src="@Url.Action("GetImage", "Photo", new { id = item.PhotoID })" />
                </a>
            }
        </div>                
    </div>
}
public FileContentResult GetImage(int id)
    {
        Photo photo = context.FindPhotoById(id);
        if (photo.PhotoFile != null)
        {
            return File(photo.PhotoFile, photo.ImageMimeType);
        }
        else
        {
            return null;
        }
    }
Public Shared Function SaveAsThumbnailCropped(ByVal path As String, ByVal archivo As String, ByVal NewWidth As Integer, ByVal NewHeight As Integer) As String

    ' Declare two variables of type Integer named
    '    adjustedImageWidth and adjustedImageHeight.
    Dim adjustedImageWidth, adjustedImageHeight As Integer

    ' Declare a variable named theImage of type Image.
    Dim theImage As Image
    Dim ThumbFileName, extension As String, convertToGIF As Boolean = False
    If InStrRev(archivo, ".") > 0 Then
        extension = Mid(archivo, InStrRev(archivo, ".")).ToString.ToLower
        ThumbFileName = Mid(archivo, 1, InStrRev(archivo, ".") - 1) + "_tb" + Trim(NewWidth) + "x" + Trim(NewHeight) + extension
    Else
        extension = "" 'desconocida
        ThumbFileName = archivo + "_tb" + Trim(NewWidth) + "x" + Trim(NewHeight)
    End If


    If Not My.Computer.FileSystem.FileExists(path + "\" + ThumbFileName) And My.Computer.FileSystem.FileExists(path + "\" + archivo) Then
        ' Get an image object from the image file;
        '    assign the image object to the theImage variable.
        theImage = System.Drawing.Image.FromFile(path + "\" + archivo)

        If theImage.Height > NewHeight Or theImage.Width > NewWidth Then
            If theImage.Height * NewWidth / theImage.Width > NewHeight Then
                ' tengo que reducir el alto
                adjustedImageHeight = NewHeight
                'keep ratio
                adjustedImageWidth = theImage.Width * (adjustedImageHeight / theImage.Height)
            Else
                adjustedImageWidth = NewWidth
                'keep ratio
                adjustedImageHeight = theImage.Height * (adjustedImageWidth / theImage.Width)
            End If
        Else
            'no hago nada porque la imagen es muy chica
            Return archivo
        End If

        Dim cropRect As Rectangle
        If adjustedImageHeight < NewHeight Or adjustedImageWidth > NewWidth Then
            'era muy apaisada tengo que croppear el centro
            adjustedImageHeight = NewHeight
            adjustedImageWidth = theImage.Width * (adjustedImageHeight / theImage.Height)
            Dim WidthSobrante = adjustedImageWidth - NewWidth
            cropRect = New Rectangle(WidthSobrante / 2, 0, NewWidth, NewHeight)
        ElseIf adjustedImageHeight > NewHeight Or adjustedImageWidth < NewWidth Then
            adjustedImageWidth = NewWidth
            adjustedImageHeight = theImage.Height * (adjustedImageWidth / theImage.Width)
            'quedo muy larga. Le cropeo el 25% de arriba del sobrante
            Dim HeightSobrante = adjustedImageHeight - NewHeight
            cropRect = New Rectangle(0, HeightSobrante / 4, NewWidth, NewHeight)
        Else
            cropRect = New Rectangle(0, 0, Math.Min(NewWidth, theImage.Width), Math.Min(NewHeight, theImage.Height))
        End If

        Dim Image As System.Drawing.Image = theImage
        Dim thumbnail As System.Drawing.Image = New Bitmap(adjustedImageWidth, adjustedImageHeight)
        Dim graphic As System.Drawing.Graphics = System.Drawing.Graphics.FromImage(thumbnail)

        graphic.InterpolationMode = InterpolationMode.HighQualityBicubic
        graphic.SmoothingMode = SmoothingMode.HighQuality
        graphic.PixelOffsetMode = PixelOffsetMode.HighQuality
        graphic.CompositingQuality = CompositingQuality.HighQuality

        graphic.DrawImage(Image, 0, 0, adjustedImageWidth, adjustedImageHeight)

        Dim croppedThumbnail = cropImage(thumbnail, cropRect)


        If extension.Equals(".gif") Then
            Dim quantizer As ImageQuantization.OctreeQuantizer = New ImageQuantization.OctreeQuantizer(255, 8)
            Dim quantized As Bitmap = quantizer.Quantize(croppedThumbnail)
            quantized.Save(path + "\" + ThumbFileName, System.Drawing.Imaging.ImageFormat.Gif)

        ElseIf extension.Equals(".jpg") Or extension.Equals(".jpeg") Then
            'Create quality parameter
            Dim encoderParams As New EncoderParameters(1)

            Dim jpgCodec As ImageCodecInfo
            jpgCodec = GetImageCodec("image/jpeg")

            If Not jpgCodec Is Nothing Then
                'Create quality parameter
                Dim qParam As New EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L)
                encoderParams.Param(0) = qParam
                croppedThumbnail.Save(path + "\" + ThumbFileName, jpgCodec, encoderParams)
            End If
        Else
            croppedThumbnail.Save(path + "\" + ThumbFileName)
        End If

        croppedThumbnail.Dispose()
        thumbnail.Dispose()
        Image.Dispose()
        graphic.Dispose()

    End If

    Return ThumbFileName


End Function

Private Shared Function cropImage(img As Image, cropArea As Rectangle) As Image
    Dim bmpImage = New Bitmap(img)
    Dim bmpCrop = bmpImage.Clone(cropArea, bmpImage.PixelFormat)
    Return CType(bmpCrop, Image)
End Function



Private Shared Function GetImageCodec(ByVal mimeType As String) As ImageCodecInfo
    Dim codecs() As ImageCodecInfo = ImageCodecInfo.GetImageEncoders()
    For Each codec As ImageCodecInfo In codecs
        If codec.MimeType.Equals(mimeType, StringComparison.OrdinalIgnoreCase) Then
            Return codec
        End If
    Next

    Return Nothing
End Function
public FileContentResult GetImage(int id, int w, int h)
    {
        Photo photo = context.FindPhotoById(id);
        MemoryStream ms;
        if (photo.PhotoFile != null)
        {
            if (w != 0 && h != 0)
            {
                ms = new MemoryStream(photo.PhotoFile);
                Image img = Image.FromStream(ms);
                var ratio = (double)img.Width / (double)img.Height;
                var ratioImg = (double)w / (double)h;
                var newHeight = 0;
                var newWidth = 0;

                if (img.Height > img.Width)
                {
                    newHeight = h;
                    newWidth = (int)(ratio * newHeight);
                }
                else
                {
                    newWidth = w;
                    newHeight = (int)(newWidth / ratio);
                }

                var newImage = new Bitmap(newWidth, newHeight);
                var destRect = new Rectangle(0, 0, newWidth, newHeight);

                using (var graphics = Graphics.FromImage(newImage))
                {
                    graphics.CompositingMode = CompositingMode.SourceCopy;
                    graphics.CompositingQuality = CompositingQuality.HighQuality;
                    graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                    graphics.SmoothingMode = SmoothingMode.HighQuality;
                    graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;

                    using (var wrapMode = new ImageAttributes())
                    {
                        wrapMode.SetWrapMode(WrapMode.TileFlipXY);
                        graphics.DrawImage(img, destRect, 0, 0, img.Width, img.Height, GraphicsUnit.Pixel, wrapMode);
                    }
                }

                Bitmap bmp = new Bitmap(newImage);
                ImageConverter icnv = new ImageConverter();

                var imgByte = (byte[])icnv.ConvertTo(bmp, typeof(byte[]));

                return File(imgByte, photo.ImageMimeType);
            }
            else
            {
                return File(photo.PhotoFile, photo.ImageMimeType);
            }                
        }
        else
        {
            return null;
        }
    }