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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…