调整图像到字节数组并将其压缩而不保存新图像

时间:2014-07-15 11:18:40

标签: vb.net

图像首先调整大小,压缩然后保存在磁盘上,如#34; Preview.jpg"然后打开它以转换为字节数组。代码工作正常但我无法弄清楚如何在不将图像保存到磁盘上的情况下完成。

以下是代码:

Public Function GetThumb_Preview(ByVal sourceImg As String) As Byte()

    Dim jgpEncoder As ImageCodecInfo = GetEncoder(ImageFormat.Jpeg)
    Dim myEncoder As System.Drawing.Imaging.Encoder = System.Drawing.Imaging.Encoder.Quality
    Dim myEncoderParameters As New EncoderParameters(1)
    Dim myEncoderParameter As New EncoderParameter(myEncoder, 50&)
    myEncoderParameters.Param(0) = myEncoderParameter

    Dim myBitmap As New Bitmap(sourceImg)

    Dim oWidth As Integer = myBitmap.Width
    Dim oHeight As Integer = myBitmap.Height

    Dim aspectRatio As Double = oHeight / oWidth

    Dim thumbWidthDouble As Double = 200
    Dim thumbHeightDouble As Double = Math.Round(thumbWidthDouble * aspectRatio)

    Dim thumbWidth As Integer = CInt(thumbWidthDouble)
    Dim thumbHeight As Integer = CInt(thumbHeightDouble)

    Dim myThumb As New Bitmap(myBitmap, thumbWidth, thumbHeight)

    Dim targetPreviewPath As String = "E:\Preview.jpg"

    myThumb.Save(targetPreviewPath, jgpEncoder, myEncoderParameters)

    Dim myImage As Image = Image.FromFile(targetPreviewPath)

    Dim imgByteArray As Byte() = Nothing

    'Image to byte[]      
    Dim imgMemoryStream As MemoryStream = New MemoryStream()
    myImage.Save(imgMemoryStream, System.Drawing.Imaging.ImageFormat.Jpeg)
    imgByteArray = imgMemoryStream.GetBuffer()

    Return imgByteArray

End Function

2 个答案:

答案 0 :(得分:1)

您可以将其保存到流中并从那里加载

    Using Str As New MemoryStream
        myThumb.Save(Str, jgpEncoder, myEncoderParameters)
        myImage = Image.FromStream(Str)
    End Using

答案 1 :(得分:1)

这是很多变量。您还有许多物品未被处置。只有当结果字节数据小于缓冲区大小时,它才会返回有效的字节数组。它在这种情况下 ,因为你正在调整大小到200倍并降低质量。

我没有测试是否正确折叠了所有这些变量,但应该非常接近。更重要的是处理您创建的内容,并获取返回的所有字节:

Dim jgpEncoder As ImageCodecInfo = GetEncoder(ImageFormat.Jpeg)
Dim myEncoder As System.Drawing.Imaging.Encoder = 
          System.Drawing.Imaging.Encoder.Quality
Dim myEncoderParameters As New EncoderParameters(1)
Dim myEncoderParameter As New EncoderParameter(myEncoder, 50&)
myEncoderParameters.Param(0) = myEncoderParameter

Dim imgByteArray As Byte()

Using myBitmap As New Bitmap(sourceImg)    ' i guess this is from file

    Dim aspectRatio As Double = myBitmap.Height / myBitmap.Width

    ' USING for disposable objects
    Using myThumb As New Bitmap(myBitmap, 200, 
                                CInt(Math.Round(200 * aspectRatio))),
        ms As New MemoryStream

        ' encode image to memstream
        myThumb.Save(ms, jgpEncoder, myEncoderParameters)

        ' rewind and get ALL bytes for the new image
        ms.Position = 0
        imgByteArray = ms.ToArray

    End Using
End Using           ' dispose

Return imgByteArray