5,693,936 members and growing! (17,092 online)
Email Password   helpLost your password?
Multimedia » GDI+ » General     Intermediate License: The Code Project Open License (CPOL)

How to convert pictures on the fly (downloading & converting)

By HADBI Moussa Benameur {Mozads}

Explain how to make a picture converter & downloader (Only http is supported)
VB (VB 7.x, VB), .NET (.NET, .NET 1.0, .NET 1.1, .NET 2.0, .NET 3.0), Dev

Posted: 9 Mar 2008
Updated: 11 Mar 2008
Views: 10,854
Bookmarked: 18 times
Announcements
Loading...



Search    
Advanced Search
Sitemap
7 votes for this Article.
Popularity: 3.42 Rating: 4.05 out of 5
0 votes, 0.0%
1
0 votes, 0.0%
2
1 vote, 14.3%
3
4 votes, 57.1%
4
2 votes, 28.6%
5
Note: This is an unedited contribution. If this article is inappropriate, needs attention or copies someone else's work without reference then please Report This Article

Introduction

Hay,...this code does download pictures on background (shadow) and convert or resize them to a specific format/size. May be some guys will find how to use the background worker in this article also useful, but we dont lost focus its not our goal in this article.

Background

This code doesnt really need hard stuff to know about, may be you will need some information about asynchronous programming since im using a background worker (after all i will explain dont worry...).

Using the code

Lets 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 : contain the different supported picture format (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 backgound worker, we will need a class (GetFiles), and its our precious "cargot" !

HOW IT WORKS

*) First the we start by filling all information: the url from where we will grabb our picture (in my example only http server are supported, may be you can add FTP transfer), folder that will hold the file, the file name, the format of the picture, and if the 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 wich 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 remind me 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 being 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 this 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 transfered    
        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 transfered
            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) 'What the hell this routine does come from !!!!
            MyMemStream.Close()
        Else
            MsgBox("An error occured when downloading the file")
            MyWebResponse.Close()
        End If

Lets see what 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 notice that this code does support only HTTP/file transfer...later i will add a routine that support other kind of transfer such FTP !

Points of Interest

I guess its 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

On 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)

About the Author

HADBI Moussa Benameur {Mozads}


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 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.
( i told u i have it under my skin or may be in my bones...)
Occupation: Software Developer
Company: GENCOX
Location: Algeria Algeria

Other popular GDI+ articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 8 of 8 (Total in Forum: 8) (Refresh)FirstPrevNext
Generalalternativememberkoo915:44 17 Jun '08  
GeneralBTW,mvptoxcct1:10 11 Mar '08  
General[Message Deleted]memberMozads1:54 11 Mar '08  
GeneralRe: BTW,mvptoxcct1:57 11 Mar '08  
GeneralRe: BTW,memberMozads1:57 11 Mar '08  
GeneralRe: BTW,mvptoxcct1:57 11 Mar '08  
GeneralGot Errormember~V~23:08 10 Mar '08  
AnswerRe: Got ErrormemberMozads0:41 11 Mar '08  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 11 Mar 2008
Editor:
Copyright 2008 by HADBI Moussa Benameur {Mozads}
Everything else Copyright © CodeProject, 1999-2008
Web09 | Advertise on the Code Project