vb.net写的一个图片按等比例缩放,剪辑图像的函数。我们在作网站的时候,经常遇到用户上传一些图片大小不对的,或上传很大的图片,这个类就是将客户的图片进行剪辑处理一下,然后再给存起来。
''' <summary>
''' 图片剪切成为指定大小
''' </summary>
Function ImgSize(ByVal ImgPath As String, Optional ByVal MaxHeight As Integer = 0, Optional ByVal MaxWidth As Integer = 0) As Drawing.Bitmap
Dim SImg As Drawing.Image = Drawing.Image.FromFile(ImgPath), Bmp As Drawing.Bitmap, scale As Long
scale = SImg.Height / SImg.Width
If MaxHeight = 0 Then MaxHeight = SImg.Height Else MaxWidth = CInt(MaxHeight / scale)
If MaxWidth = 0 Then MaxWidth = SImg.Width Else MaxHeight = CInt(MaxWidth * scale)
Bmp = New Drawing.Bitmap(MaxWidth, MaxHeight)
Dim g As Drawing.Graphics = Drawing.Graphics.FromImage(Bmp) : g.Clear(Drawing.Color.White)
If SImg.Width <= MaxWidth AndAlso SImg.Height <= MaxHeight Then '小源图或一样大
g.DrawImage(SImg, New Drawing.RectangleF(0, 0, MaxWidth, MaxHeight))
Else
Dim NW As Integer = SImg.Width, NH As Integer = SImg.Height
If SImg.Width / SImg.Height >= MaxWidth / MaxHeight Then
If SImg.Width > MaxWidth Then NW = SImg.Width / (SImg.Height / MaxHeight) : NH = MaxHeight
Else
If SImg.Height > MaxHeight Then NW = MaxWidth : NH = SImg.Height / (SImg.Width / MaxWidth)
End If
g.DrawImage(SImg, New Drawing.RectangleF((MaxWidth - NW) / 2, (MaxHeight - NH) / 2, NW, NH))
End If
SImg.Dispose()
Return Bmp
End Function
注意:这个MaxHeight,MaxWidth参数是图片大值,可以自行修改成为固定大小图片。
以下是调用方法例子
Dim Bmp As Drawing.Bitmap = ImgSize("C:\www\cqwsc\UpFile\Temp\190911_166089a7.jpg", 0, 500)
Bmp.Save(AppPath & "\UpFile\123.jpg", Drawing.Imaging.ImageFormat.Jpeg)
Bmp.Dispose()