65.9K
CodeProject 正在变化。 阅读更多。
Home

如何即时转换图片(下载和转换)

2008年3月9日

CPOL

2分钟阅读

viewsIcon

54341

downloadIcon

592

解释如何制作图片转换器和下载器(仅支持 HTTP)。

引言

此代码在后台(影子)下载图片并将其转换为特定格式/大小。 也许有些人也会觉得这篇文章中如何使用后台工作程序很有用,但我们不要跑题。 这不是我们这篇文章的目标。

背景

这段代码实际上不需要了解很多复杂的东西,也许你需要一些关于异步编程的信息,因为我正在使用后台工作程序(毕竟,我会解释,别担心......)。

Using the Code

让我们开始!

在我们的项目中,我们需要

主窗体,它将包括

  • 7 个标签:{URL, 保存到, 文件名, 格式, ???, 高度, 宽度}
  • 1 个组合框:包含不同的受支持图片格式(BMP, ICO, PNG, WMF, JPG, TIFF, GIF 和 EMF)
  • 2 个命令按钮:[文件夹] 用于选择文件夹,[执行] 用于下载和转换我们的图片 
  • 1 个复选框,也许你需要调整你的图片大小...谁知道呢!!!!
  • 2 个组件:后台工作程序,以及 FolderBrowserDialog

好吧,由于我们正在使用后台工作程序,我们需要一个类(GetFiles),它是我们珍贵的“货运”!

工作原理

首先,我们从填写所有信息开始:我们将从中获取图片的 URL(在我的示例中,仅支持 HTTP 服务器,也许你可以添加 FTP 传输),将保存文件的文件夹,文件名,图片的格式,以及如果我们将复选框设置为 true(选中),则另外两个文本框将允许我们输入结果图片的宽度/高度。
注意:如果将宽度/高度设置为 0,则生成的图片将保持原始大小(宽度/高度)。

当我们点击执行时

            ' Start the background worker, and disable the proceed button ! 
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 Sub BackgroundWorker1_DoWork(ByVal sender As Object, _
	ByVal e As System.ComponentModel.DoWorkEventArgs) _
	Handles BackgroundWorker1.DoWork
         '     
        Dim MyGetFiles As Getfiles
        If CheckBox1.Checked Then
            ' being true, means that we will need to resize the picture        
            MyGetFiles = New Getfiles(Label4.Text, TextBox1.Text, _
			TextBox4.Text, TextBox5.Text, MyNewFormat)
        Else
            'being false, the picture will stay as it is, 
            'but we change only the format
                MyGetFiles = New Getfiles(Label4.Text, _
				TextBox1.Text, 0, 0, MyNewFormat)
        End If
        MyGetFiles.MyPictureConverter()
        MyGetFiles = Nothing
    End Sub

现在我们可以跳转到我们的类

'Properties

Private MyURLex As String 'URL of our picture
Private MyPATHex As String 'Path on which the resulting picture will be saved
Private MyWidthEx As Int32 = 0 'The new width of picture
Private MyHeightEx As Int32 = 0 ' The new height of picture
Private MyFormatEx As Imaging.ImageFormat ' The new format of the picture

正如你在 BackgroundWorker1_DoWork 子程序中看到的那样,有一个类[new]的构造函数,它帮助我们设置所有 private 属性。这让我想起了封装的概念。

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  'The "picture" 
					' will be first saved to memory
          'To verify that our file is intact I added these two variables        
        Dim MyDownData As Integer = 0 
        Dim FileSize As Int64
          'Start the request...     
        Dim MyWebRequest As HttpWebRequest = WebRequest.Create(MyTarget)
        'Set the response time to 5 seconds
        MyWebRequest.Timeout = 5000
        Dim MyWebResponse As WebResponse = MyWebRequest.GetResponse
        'Get the size of the picture
        FileSize = MyWebResponse.ContentLength
          'Download the picture NOW !!!!
        Dim MyStream As Stream = MyWebResponse.GetResponseStream
        Dim MyCache(1024) As Byte
        Dim MyCount As Integer = MyStream.Read(MyCache, 0, MyCache.Length)
          'Store the number of bytes transferred    
        MyDownData = MyCount
        While MyCount > 0
            'Write downloaded data to memory stream
            MyMemStream.Write(MyCache, 0, MyCount)
            MyCount = MyStream.Read(MyCache, 0, MyCache.Length)
            'Store the number of bytes transferred
            MyDownData += MyCount
        End While
        MyMemStream.Flush()          
        MyMemStream.Seek(0, SeekOrigin.Begin)
        MyStream.Close()
        MyWebResponse.Close()
        'Check if all data was well downloaded
        If FileSize = MyDownData Then
            'Call pictures converter
            MyConverter(MyMemStream) 'Where the hell this routine does come from !!!!
            MyMemStream.Close()
        Else
            MsgBox("An error occurred when downloading the file")
            MyWebResponse.Close()
        End If

让我们看看她到底来自哪里... MyConverter(MyMemStream)

Private Sub MyConverter(ByVal MemStream As MemoryStream)
        Dim MyOriginalPic As New Bitmap(MemStream) 'This will help us 
		'to create our picture from the resulting stream (memory stream)
        Dim MyFinalPic As Bitmap
        'Set the width/height of the picture
        If MyWidthEx = 0 Then
            MyWidthEx = MyOriginalPic.Width
        End If
        If MyHeightEx = 0 Then
            MyHeightEx = MyOriginalPic.Height
        End If
        'Convert...
        Try
            ' Now create the new bitmap, and set the width/height 
            MyFinalPic = New Bitmap(MyOriginalPic, MyWidthEx, MyHeightEx)
              ' Save the resulting new picture to the path, and new format    
            MyFinalPic.Save(MyPATHex, MyFormatEx)
            ' *.tiff, *.ico, *.bmp, *.jpg, *.png,
        Catch ex As Exception
            MsgBox(ex.Message & "/" & Err.Number & "/" & Err.Description)
        End Try
    End Sub

现在一切都完成了,我们启用了 [执行] 命令按钮!我们可以尝试再次下载。我注意到这段代码只支持 HTTP/文件传输...稍后我将添加一个支持其他类型传输(如 FTP)的例程!

关注点

我想最好这样做,因为现在我们的计算机配备了非常大的物理内存(在我的示例中为 1024 MB),所以我们可以让硬盘安息一段时间...

历史

在下一个版本中,我将尝试添加一些有用的图形优化/修改。

© . All rights reserved.