Share My Creation Example: Download image from URL link

This basic example shows how to download an image from a URL link and display it in an ImageView.
You can either enter the URL manually or grab the link from the clipboard.

As an example, copy this link to the clipboard, then click the [From Clipboard] button to view the image. The image should download thereafter.
http://media.treehugger.com/assets/images/2011/10/aptera-01.jpg


Note that large images will take some time to appear (and a progress indicator will appear indicating that the download is in progress).


ImageURL1_zps33066beb.png



B4X:
#Region Project Attributes
    #MainFormWidth: 560
    #MainFormHeight: 480
#End Region

Sub Process_Globals
    Public MainUrL As String
    Private fx As JFX
    Private MainForm As Form
    Private btn_Go As Button
    Private btn_Clipboard As Button
    Private img_View As ImageView
    Private edit_URL As TextField
    Private pi_Progress As ProgressIndicator
End Sub

Sub AppStart (Form1 As Form, Args() As String)
    MainForm = Form1
    MainForm.Title="Image URL downloader"
    MainForm.RootPane.LoadLayout("1") 'Load the layout file.
    pi_Progress.Visible=False
    img_View.SetImage(fx.LoadImage(File.DirAssets,"blank.png"))
    MainForm.Show
End Sub

Sub JobDone(Job As HttpJob)
    If Job.Success Then
        Dim i As Image = Job.GetBitmap
        If i.IsInitialized=False Then
            Log("Invalid image")
            pi_Progress.Visible=False
            Job.Release
            Return
        End If
        img_View.SetImage(i)
        img_View.Width=i.Width
        img_View.Height=i.Height
        pi_Progress.Visible=False
    Else
        Log("Job Error: " & Job.ErrorMessage)
    End If
    Job.Release
End Sub

Sub btn_Go_Action
    Dim job As HttpJob
    job.Initialize("Main page", Me)
    MainUrL=ConvertURL(edit_URL.Text)
    pi_Progress.Visible=True
    job.Download(MainUrL)
End Sub

Sub btn_Clipboard_Action
    If fx.Clipboard.HasString Then
        Dim job As HttpJob
        job.Initialize("Main page", Me)
        edit_URL.Text=fx.Clipboard.GetString
        MainUrL=ConvertURL(edit_URL.Text)
        pi_Progress.Visible=True
        job.Download(MainUrL)
    Else
        Log("no clipboard")
    End If
End Sub

Sub ConvertURL(urlString As String) As String
    urlString=urlString.Replace("\","/")
    Return urlString
End Sub

Sub MainForm_Resize (Width As Double, Height As Double)
End Sub
 

Attachments

  • ImageRULDownloader 2.zip
    50.9 KB · Views: 471
Last edited:
Top