Resizing an image in VB.NET

夙愿已清 提交于 2019-12-08 03:11:27

Basically the code is correct, but there are some problems with it:

  • You are skipping the last byte when you write into the first memory stream. The last property in the Write call should be the length, not the length minus one.
  • Your calculation of Height2 is incorrect. The expression Height1 * Width1 / Width1 will always evaluate to the value of Height1. You should use Height1 * Width2 / Width1 instead.
  • You are not disposing your memory streams, bitmaps or graphics objects. Use Using blocks to make sure that the objects are disposed.

You can simplify the code somewhat by creating the first memory stream from the byte array instead of writing the array to the stream:

Using MemoryStream1 As New System.IO.MemoryStream(SqlDataReader1("cover"))

  Using Bitmap1 As System.Drawing.Bitmap = System.Drawing.Bitmap.FromStream(MemoryStream1)

    Dim Width1 As Integer = Bitmap1.Width
    Dim Height1 As Integer = Bitmap1.Height

    Dim Width2 As Integer = 90
    Dim Height2 As Integer = Height1 * Width2 / Width1

    Using Bitmap2 As System.Drawing.Bitmap = New System.Drawing.Bitmap(Width2, Height2)

      Using Graphics1 As System.Drawing.Graphics = System.Drawing.Graphics.FromImage(Bitmap2)

        Graphics1.DrawImage(Bitmap1, 0, 0, Width2, Height2)

      End Using

      Using MemoryStream2 As New System.IO.MemoryStream

        Bitmap2.Save(MemoryStream2, System.Drawing.Imaging.ImageFormat.Png)

        context.Response.BinaryWrite(MemoryStream2.ToArray)

      End Using

    End Using

  End Using

End Using
Public Function ResizeImage(imgToResize As Image, size As Size) As Byte()
        Dim sourceWidth As Integer = imgToResize.Width
        Dim sourceHeight As Integer = imgToResize.Height

        Dim nPercent As Single = 0
        Dim nPercentW As Single = 0
        Dim nPercentH As Single = 0

        nPercentW = (CSng(size.Width) / CSng(sourceWidth))
        nPercentH = (CSng(size.Height) / CSng(sourceHeight))

        If nPercentH < nPercentW Then
            nPercent = nPercentH
        Else
            nPercent = nPercentW
        End If

        Dim destWidth As Integer = CInt(Math.Truncate(sourceWidth * nPercent))
        Dim destHeight As Integer = CInt(Math.Truncate(sourceHeight * nPercent))

        Dim b As New Bitmap(destWidth, destHeight)
        Dim g As Graphics = Graphics.FromImage(DirectCast(b, Image))
        g.InterpolationMode = InterpolationMode.HighQualityBicubic

        g.DrawImage(imgToResize, 0, 0, destWidth, destHeight)
        g.Dispose()

        Return b.ToByteArray()
    End Function

This function will resize an image to a specified size keeping its proporstion. It was in C# and I put it through an online converter so may not be 100% correct

ToByteArray() is an extension method I wrote to store the image in a DB i can give you that also if you like.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!