vb.net写的一个图片按等比例缩放,剪辑图像的函数。

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()

 

 

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值