在本文中,将探讨如何使用VB.NET进行图片的异步下载和格式转换。这涉及到创建一个用户界面,使用背景工作者进行异步操作,以及处理图片的下载、格式转换和尺寸调整。虽然这个过程不需要复杂的编程知识,但了解异步编程的概念将对理解本文内容大有裨益。
让开始吧!在项目中,需要以下组件:
由于使用背景工作者,需要一个类(GetFiles),这是宝贵的“货物”!
首先,填写所有信息:将从URL获取图片(在示例中,仅支持HTTP服务器,可能可以添加FTP传输),保存文件的文件夹,文件名,图片格式,如果设置复选框为真(选中),另外两个文本框将允许输入结果图片的宽度/高度。
注意:如果将宽度/高度设置为0,结果图片将保持原始大小(宽度/高度)。
当点击“Proceed”时:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Me.BackgroundWorker1.RunWorkerAsync()
Me.Button1.Enabled = False
End Sub
现在可以跳到类:
Private MyURLex As String ' 图片的URL
Private MyPATHex As String ' 保存结果图片的路径
Private MyWidthEx As Int32 = 0 ' 图片的新宽度
Private MyHeightEx As Int32 = 0 ' 图片的新高度
Private MyFormatEx As Imaging.ImageFormat ' 图片的新格式
如所见,在BackgroundWorker1_DoWork子程序中,有一个类的构造函数,它帮助设置所有私有属性。这让想到了封装的概念。
Sub New(ByVal MyPath As String, ByVal MyURL As String, ByVal Height As Int32, ByVal Width As Int32, ByVal MyFormat As Imaging.ImageFormat)
MyURLex = MyURL
MyPATHex = MyPath
MyHeightEx = Height
MyWidthEx = Width
MyFormatEx = MyFormat
End Sub
设置属性后,将调用MyPictureConverter子程序!它是什么?
Friend Sub MyPictureConverter()
Dim MyTarget As New Uri(MyURLex)
Dim MyMemStream As New MemoryStream
Dim MyDownData As Integer = 0
Dim FileSize As Int64
Dim MyWebRequest As HttpWebRequest = WebRequest.Create(MyTarget)
MyWebRequest.Timeout = 5000
Dim MyWebResponse As WebResponse = MyWebRequest.GetResponse
FileSize = MyWebResponse.ContentLength
Dim MyStream As Stream = MyWebResponse.GetResponseStream
Dim MyCache(1024) As Byte
Dim MyCount As Integer = MyStream.Read(MyCache, 0, MyCache.Length)
MyDownData = MyCount
While MyCount > 0
MyMemStream.Write(MyCache, 0, MyCount)
MyCount = MyStream.Read(MyCache, 0, MyCache.Length)
MyDownData += MyCount
Wend
MyMemStream.Flush()
MyMemStream.Seek(0, SeekOrigin.Begin)
MyStream.Close()
MyWebResponse.Close()
If FileSize = MyDownData Then
MyConverter(MyMemStream)
Else
MsgBox("An error occurred when downloading the file")
MyWebResponse.Close()
End If
End Sub
让看看这个子程序来自哪里...
Private Sub MyConverter(ByVal MemStream As MemoryStream)
Dim MyOriginalPic As New Bitmap(MemStream)
Dim MyFinalPic As Bitmap
If MyWidthEx = 0 Then MyWidthEx = MyOriginalPic.Width End If
If MyHeightEx = 0 Then MyHeightEx = MyOriginalPic.Height End If
Try
MyFinalPic = New Bitmap(MyOriginalPic, MyWidthEx, MyHeightEx)
MyFinalPic.Save(MyPATHex, MyFormatEx)
Catch ex As Exception
MsgBox(ex.Message & "/" & Err.Number & "/" & Err.Description)
End Try
End Sub
现在一切都完成了,启用[Proceed]命令按钮!可以再次尝试下载。注意到这段代码只支持HTTP/文件传输...稍后会添加一个支持其他类型传输的例程,如FTP!