一种简单的图像缩放方法






4.44/5 (27投票s)
本文将向您展示如何调整图像大小,同时保持最佳的图形质量。
简介
在任何 Web/Windows 应用程序中添加图像/签名是最常见的操作。本文将向您展示如何调整图像大小,同时保持最佳的图形质量。
背景
大多数时候,开发人员在运行时调整图像大小时会遇到各种问题。 在本文中,我尝试在运行时调整图像大小,同时保持最佳的图形质量。
使用代码
这里我编写了一个用于调整图像大小的函数(即“ImageResize
”),该函数具有四个输入参数,分别是
strImageSrcPath
:一个string
,包含图像源文件路径strImageDesPath
:一个string
,包含目标文件路径intWidth
:一个integer
值,用于新的图像宽度intHeight
:一个integer
值,用于新的图像高度
成功调用该函数并提供有效输入值后,它将调整图像大小并将其存储到您提供的目标路径中,并返回完整路径以显示新的调整大小后的图像。 这里我使用 .NET Framework 3.5 (System.Drawing,IO
) 命名空间。
Public Function ImageResize(ByVal strImageSrcPath As String _
, ByVal strImageDesPath As String _
, Optional ByVal intWidth As Integer = 0 _
, Optional ByVal intHeight As Integer = 0) As String
If System.IO.File.Exists(strImageSrcPath) = False Then Exit Function
Dim objImage As System.Drawing.Image = System.Drawing.Image.FromFile(strImageSrcPath)
If intWidth > objImage.Width Then intWidth = objImage.Width
If intHeight > objImage.Height Then intHeight = objImage.Height
If intWidth = 0 And intHeight = 0 Then
intWidth = objImage.Width
intHeight = objImage.Height
ElseIf intHeight = 0 And intWidth <> 0 Then
intHeight = Fix(objImage.Height * intWidth / objImage.Width)
ElseIf intWidth = 0 And intHeight <> 0 Then
intWidth = Fix(objImage.Width * intHeight / objImage.Height)
End If
Dim imgOutput As New Bitmap(objImage, intWidth, intHeight)
Dim imgFormat = objImage.RawFormat
objImage.Dispose()
objImage = Nothing
If strImageSrcPath = strImageDesPath Then System.IO.File.Delete(strImageSrcPath)
' send the resized image to the viewer
imgOutput.Save(strImageDesPath, imgFormat)
imgOutput.Dispose()
Return strImageDesPath
End Function
现在我们将讨论上述函数的工作原理。 在这里,您将找到各种用于执行文件操作的方法,所有这些方法都很常见。 我想重点介绍用于图像调整大小的主要属性、方法和类。
属性
RawFormat
:获取此图像的文件格式
方法
FromFile
:从指定文件创建图像Fix
:以整数形式返回分数值
Bitmap 类
封装了一个 GDI+ 位图,该位图包含图形图像的像素数据及其属性。 Bitmap
是用于处理由像素数据定义的图像的对象。
概念非常简单,首先我们需要创建 System.Drawing.Image.FromFile
的一个实例,并设置图像的新宽度和高度。 之后,我们使用 Bitmap 对象
来填充新图像,并使用 RawFormat
属性设置实际格式,最后将新图像存储到目标路径中。
结论
这是一种非常简单易于使用的方法。 希望对您有所帮助! 祝您愉快!