如何根据原始图像比例调整图像大小?

时间:2013-01-15 12:20:16

标签: vb.net image image-processing

使用VB.net重新调整图像大小后的白色背景,如下所示。我试图改变一些值,但失败了。

Dim FileToResize As String = Server.MapPath("~/images/" & filename & FileUpload1.FileName)
Using originalBitmap As Bitmap = Bitmap.FromFile(FileToResize, True), newbmp As Bitmap = New Bitmap(200, 200)
    Dim WidthVsHeightRatio = CDec(originalBitmap.Width) / CDec(originalBitmap.Height)

    Using newg As Graphics = Graphics.FromImage(newbmp)
        newg.SmoothingMode = Drawing2D.SmoothingMode.HighQuality
        newg.Clear(Color.White)

        If WidthVsHeightRatio = 1D Then
            newg.DrawImage(originalBitmap, 0, 0, 200, 200)
            newg.Save()


        ElseIf WidthVsHeightRatio < 1D Then 'Image is taller than wider

            newg.DrawImage(originalBitmap, New RectangleF(New PointF((100 - (200 * WidthVsHeightRatio) / 2), 0), New SizeF(200 * WidthVsHeightRatio, 200.0F)))
            newg.Save()

        Else 'Image is wider than taller

            Dim inverse As Double = Math.Pow(WidthVsHeightRatio, -1)
            newg.DrawImage(originalBitmap, New RectangleF(New PointF(0, 100 - ((200 * inverse) / 2)), New SizeF(200.0F, 200 * inverse)))
            newg.Save()
        End If
    End Using

    newbmp.Save(Server.MapPath("~/images/" & "_th_" & filename & FileUpload1.FileName), System.Drawing.Imaging.ImageFormat.Jpeg)
    NewsItem.ImageLink = filename & FileUpload1.FileName
    NewsItem.smallimage = "_th_" & filename & FileUpload1.FileName
End Using

1 个答案:

答案 0 :(得分:0)

我最近做了一些研究,为电子商务网站动态生成图像缩略图。我开始自己生成一个位图,然后调整大小等等。在光盘上的图像大小问题和质量问题后,我查看了http://imageresizing.net/,我从此没有回头。它可以通过一行代码快速生成来自byte(),流和物理文件的图像:

ImageBuilder.Current.Build(New MemoryStream(bImage), sImageLocation + sFullFileName, New      ResizeSettings("maxwidth=214&maxheight=238"))

我肯定会推荐这个组件,而不是试图重新发明轮子......