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 ou
That is a lot of variables to do so little. You also have a number of objects not being disposed. It will also return a valid Byte array only when the resulting byte data is less than the buffer size. It works in this case because you are resizing to 200x and reducing quality.
I didnt test if I collapsed all those variables correctly, but should be very close. More important is disposing things you create, and getting the all the Bytes for the return:
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
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