Click here to Skip to main content
Click here to Skip to main content

How To Convert Pictures on the Fly (Downloading & Converting)

, 11 Mar 2008 CPOL
Rate this:
Please Sign up or sign in to vote.
Explain how to make a picture converter & downloader (Only HTTP is supported)

Introduction

This code does download pictures on background (shadow) and convert or resize them to a specific format/size. May be some guys will also find how to use the background worker in this article useful, but we don't lose focus. It's not our goal in this article.

Background

This code doesn't really need hard stuff to know about, may be you will need some information about asynchronous programming since I'm using a background worker (after all, I will explain, don't worry...).

Using the Code

Let's start !

In our project, we will need:

The main form that will include:

  • 7 Labels: {Url, Save to, Filename, Format, ???, Height, Width}
  • 1 Combo Box: contains the different supported picture formats (BMP, ICO, PNG, WMF, JPG, TIFF, GIF and EMF)
  • 2 command buttons: [Folder] to select a folder, and [Proceed] to download and convert our picture 
  • 1 check box, may be you will need to resize your picture... who knows !!!!!!
  • 2 components : Background worker, and FolderBrowserDialog

Well since we are using a background worker, we will need a class (GetFiles), and it's our precious "cargot" !

How It Works

First we start by filling all information: the URL from where we will grab our picture (in my example, only HTTP server is supported, may be you can add FTP transfer), folder that will hold the file, the file name, the format of the picture, and if we set the checkbox to true (checked), the two other textboxes will permit us to enter the width/height of our resulting picture.
Note: If you set the width/height to 0, the resulting picture will hold the original size (width/height).

When we click on proceed:

            ' 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

Now we can jump to our class :

'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

As you did see in the BackgroundWorker1_DoWork sub, there is a constructor of class [new] that helps us to set all our private properties. This reminds me of the encapsulation concept.

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

After our properties are set, the MypictureConverter subroutine will be invoked! What about it ?

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

Let's see where the hell she comes from... 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

And now that all is finished, we enable the [Proceed] command button! And we can try to download again. I noticed that this code does support only HTTP/file transfer...later I will add a routine that supports other kinds of transfer such as FTP !

Points of Interest

I guess it's better to act like this, since now our computer comes up with a very big physical memory (in my example 1024 MB) so we can let the Hard disk Rest In Peace...for a while...

History

In the next version, I will try to add some useful graphical optimisation / modification.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

HADBI Moussa Benameur {Mozads}
Software Developer GENCOX
Algeria Algeria
Hello everybody...so i started programming since 10 years,...PASCAL(Borland) then after that, i moved to Visual Basic 5.0 and 6.0, i developped many application : A(rtificial)Intelligence {that was hard stuff} also...for now im migrating from VB 6.0 to VB .Net...i have an Algerian diplom on computer science BAC+3 (Applied engineering Soft/Hard).
 
I need to develop my skills on programmation : .Net technology (Vb or C#), Java, Javascript, Ajax & PHP and of course SGBD (SQL Server & MySQL, Interbase & FireBird, Oracle).
 

I Have two expert rating certificate, and you can of course check my result sheet at this adress :
 
Computer Skills (http://www.expertrating.com/transcript.asp?transcriptid=1158363)
 
Windows Xp Test (http://www.expertrating.com/transcript.asp?transcriptid=1158862)
 
I love also astronomy,...jumpin from my computer to my telescop...of course since now im not married...
 
Well this is me...u can contact me if u want !i 'll be honored...
 
thanks !
Msgbox ("See Ya Around")
 
End Sub.

Comments and Discussions

 
GeneralMy vote of 5 PinmemberMember 86141177-May-12 15:18 
Generalalternative Pinmemberkoo917-Jun-08 15:44 
GeneralRe: alternative Pinmemberthund3rstruck13-Nov-09 18:31 
GeneralBTW, Pinmvptoxcct11-Mar-08 1:10 
General[Message Deleted] PinmemberMozads11-Mar-08 1:54 
GeneralRe: BTW, Pinmvptoxcct11-Mar-08 1:57 
GeneralRe: BTW, PinmemberMozads11-Mar-08 1:57 
GeneralRe: BTW, Pinmvptoxcct11-Mar-08 1:57 
GeneralGot Error Pinmember~V~10-Mar-08 23:08 
AnswerRe: Got Error PinmemberMozads11-Mar-08 0:41 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.141220.1 | Last Updated 11 Mar 2008
Article Copyright 2008 by HADBI Moussa Benameur {Mozads}
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid