我花了很长时间在谷歌上搜索并阅读了各种文章,但我似乎一直在兜圈子,现在很困惑,似乎没有成功!
我正在尝试获取 4 个不同大小的图像版本,为了实现这一点,我有一个大小数组,并且正在循环下面的函数。
这行得通,并且完成了预期的一切,除了较小的图像非常块状,我无法获得平滑以达到我期望的效果。
对于老式的 ASP Classic,我使用了 Persits ASPUpload/jpeg 插件,它可以很好地平滑调整大小。使用 .NET,我正在苦苦挣扎。
Public Shared Sub ResizeImages(FileName, NewFileName, maxWidth, maxHeight, uploadDir, qualityPercent)
Dim originalImg As System.Drawing.Image = System.Drawing.Image.FromFile(uploadDir & FileName)
Dim aspectRatio As Double
Dim newHeight As Integer
Dim newWidth As Integer
'*** Calculate Size ***'
If originalImg.Width > maxWidth Or originalImg.Height > maxHeight Then
If originalImg.Width >= originalImg.Height Then ' image is wider than tall
newWidth = maxWidth
aspectRatio = originalImg.Width / maxWidth
newHeight = originalImg.Height / aspectRatio
Else ' image is taller than wide
newHeight = maxHeight
aspectRatio = originalImg.Height / maxHeight
newWidth = originalImg.Width / aspectRatio
End If
Else ' if image is not larger than max then keep original size
newWidth = originalImg.Width
newHeight = originalImg.Height
End If
Dim newImg As New Bitmap(originalImg, CInt(newWidth), CInt(newHeight)) '' blank canvas
Dim canvas As Graphics = Graphics.FromImage(newImg) 'graphics element
'*** compress ***'
Dim myEncoderParameters As EncoderParameters
myEncoderParameters = New EncoderParameters(1)
' set quality level based on "resolution" variable
Dim myEncoderParameter = New EncoderParameter(System.Drawing.Imaging.Encoder.Quality, CType(qualityPercent, Int32))
myEncoderParameters.Param(0) = myEncoderParameter
'*** Save As ***'
canvas.SmoothingMode = Drawing.Drawing2D.SmoothingMode.AntiAlias
canvas.DrawImage(newImg, New Point(0, 0))
newImg.Save(uploadDir & NewFileName, getCodec("image/jpeg"), myEncoderParameters)
'*** Close ***'
originalImg.Dispose()
newImg.Dispose()
'*** Nothing ***'
newImg = Nothing
originalImg = Nothing
End Sub
Public Shared Function getCodec(getThis) As Drawing.Imaging.ImageCodecInfo
Dim output As Drawing.Imaging.ImageCodecInfo
Dim codecs As Imaging.ImageCodecInfo() = Imaging.ImageCodecInfo.GetImageEncoders
For Each codec As Imaging.ImageCodecInfo In codecs
If codec.MimeType = getThis Then
output = codec
End If
Next codec
Return output
End Function
我觉得我可能在这里混淆了类型?
在执行上述函数的过程中,我有 a System.Drawing.Image
、 aBitMap
和一个Graphic
对象,并且觉得我可能试图将平滑应用于错误的元素,或者在编码的错误阶段?
该System.Drawing.Image
对象加载保存在服务器上的文件,然后我计算所需的纵横比和新大小,创建一个BitMap
此大小的新文件并将其保存到Graphics
对象中。
它是否正确?
我需要修改什么来实现更平滑的调整大小?
像往常一样,非常感谢任何帮助。