调整大小在VB.NET的图像 [英] Resizing an image in VB.NET
本文介绍了调整大小在VB.NET的图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下的code在我的IHttpHandler:
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)
它的工作原理,但我不知道它是要调整图像的正确途径。如何简化了code?
It works but I'm not sure that it is the right way to resize an image. How to simplify that code?
在此先感谢!
推荐答案
基本上,code是正确的,但也有一些问题是:
Basically the code is correct, but there are some problems with it:
- 您是当你写到第一内存流跳过最后一个字节。在
写
调用应该是长度,不长减一。 最后一个属性 - 您
身高2
的计算是不正确。这位前pressionHeight1 *宽度1 /宽度1
将总是为Height1
的价值。您应该使用Height1 *宽2 /宽度1
代替。 - 您没有处置你的内存流,位图或图形对象。使用
使用
块,以确保该对象被设置。
- You are skipping the last byte when you write into the first memory stream. The last property in the
Write
call should be the length, not the length minus one. - Your calculation of
Height2
is incorrect. The expressionHeight1 * Width1 / Width1
will always evaluate to the value ofHeight1
. You should useHeight1 * Width2 / Width1
instead. - You are not disposing your memory streams, bitmaps or graphics objects. Use
Using
blocks to make sure that the objects are disposed.
您可以通过创建从字节数组的第一个内存流,而不是数组写入流有所简化code:
You can simplify the code somewhat by creating the first memory stream from the byte array instead of writing the array to the stream:
Using MemoryStream1 As New System.IO.MemoryStream(SqlDataReader1("cover"))
Using 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 * Width2 / Width1
Using Bitmap2 As System.Drawing.Bitmap = New System.Drawing.Bitmap(Width2, Height2)
Using Graphics1 As System.Drawing.Graphics = System.Drawing.Graphics.FromImage(Bitmap2)
Graphics1.DrawImage(Bitmap1, 0, 0, Width2, Height2)
End Using
Using MemoryStream2 As New System.IO.MemoryStream
Bitmap2.Save(MemoryStream2, System.Drawing.Imaging.ImageFormat.Png)
context.Response.BinaryWrite(MemoryStream2.ToArray)
End Using
End Using
End Using
End Using
这篇关于调整大小在VB.NET的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文