4,818
社区成员
发帖
与我相关
我的任务
分享

Imports System.IO
Public Function ResizeImage(ByVal sImage As Byte(), ByVal ImageSize As Integer) As Byte()
Dim ow, oh, nw, nh, nx, ny As Integer
Dim img As Image = Nothing
Dim newimg As Image = Nothing
Dim imgstream As MemoryStream = Nothing
Dim newimgstream As MemoryStream = Nothing
Try
If IsDBNull(sImage) Then
Return Nothing
End If
imgstream = New MemoryStream(sImage)
'获取原图片宽高
img = Image.FromStream(imgstream)
imgstream.Dispose()
ow = img.Width
oh = img.Height
'按比例设置新宽高
If ow > oh Then
nw = ImageSize
nh = CType(nw * oh / ow, Integer)
nx = 0
ny = CType((ImageSize - nh) / 2, Integer)
Else
nh = ImageSize
nw = CType(nh * ow / oh, Integer)
ny = 0
nx = CType((ImageSize - nw) / 2, Integer)
End If
'建立新图片
newimg = New Bitmap(ImageSize, ImageSize)
'建立新画板
Dim g As Graphics = Graphics.FromImage(newimg)
'高质量插入
g.InterpolationMode = Drawing2D.InterpolationMode.HighQualityBicubic
'清空画布并以白色背景色填充
g.Clear(Drawing.Color.White)
'按新宽高比在新图片居中位置绘画原图片内容
g.DrawImage(img, nx, ny, nw, nh)
'将新图片转换成数据流
newimgstream = New MemoryStream
newimg.Save(newimgstream, System.Drawing.Imaging.ImageFormat.Jpeg)
img.Dispose()
newimg.Dispose()
g.Dispose()
'以字符串形式返回图片值
Return newimgstream.ToArray
Catch ex As Exception
img.Dispose()
newimg.Dispose()
imgstream.Dispose()
newimgstream.Dispose()
Return sImage
End Try
End Function