I have the following code in my IHttpHandler:
Dim MemoryStream1 As New System.IO.MemoryStream
MemoryStream1.Write(SqlDataReader1("cover"), 0, SqlDataReader1("cover").Length - 1)
Dim 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 * Width1 / Width1
Dim Bitmap2 As System.Drawing.Bitmap = New System.Drawing.Bitmap(Width2, Height2)
Dim Graphics1 As System.Drawing.Graphics = System.Drawing.Graphics.FromImage(Bitmap2)
Graphics1.DrawImage(Bitmap1, 0, 0, Width2, Height2)
Dim MemoryStream2 As New System.IO.MemoryStream
Bitmap2.Save(MemoryStream2, System.Drawing.Imaging.ImageFormat.Png)
context.Response.BinaryWrite(MemoryStream2.ToArray)
It works but I’m not sure that it is the right way to resize an image. How to simplify that code?
Thanks in advance!
Basically the code is correct, but there are some problems with it:
Writecall should be the length, not the length minus one.Height2is incorrect. The expressionHeight1 * Width1 / Width1will always evaluate to the value ofHeight1. You should useHeight1 * Width2 / Width1instead.Usingblocks 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: