Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

vb.net - Resize and Compress image to byte array without saving the new image

The image is first resized, compressed and then saved on disk as "Preview.jpg" and then it is opened to convert into byte array. The code works fine but I cannot figure out how to do it without saving the image on disk.

Here is the code:

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You could save it to a stream and load it from there

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...