B4A Library Library PictureDownloadUrl

Discussion in 'Additional libraries, classes and official updates' started by MarcoRome, Jun 28, 2015.

  1. MarcoRome

    MarcoRome Expert Licensed User

    THIS LIBRARY DONT WORK FINE I SUGGEST UNIVERSALIMAGELOADER BY DONMANFRED OR YOU CAN USE Job.GetBitmap
    Thank you


    ********************
    This library copy an image from the web and copy to device ( you can save the same in jpeg or png )
    Example you use this feature to copy:
    Code:
    Dim file_share asString = "example.jpg"
    File.Copy(File.DirAssets, file_share, File.DirRootExternal, "save.jpg")
    same thing to copy from web:
    Code:
    Dim FileUrl As PictureDownloadUrl
    Dim file_share as String = "example.png"
    FileUrl.Copy(
    "http://devil-app.eu/example/",file_share, File.DirRootExternal,"tattoo_pro","jpeg")
    Yes i know exist also another way ... but this you have in two lines code

    PictureDownloadUrl
    Version:1.10



    PictureDownloadUrl
    Author:
    DevilApp
    Version: 1.1
    • PictureDownloadUrl
      Methods:
      • Copy (pathSourceUrl As String, imgSource As String, pathDestiny As String, imgDestiny As String, format As String)
        Copy Image from URL to Destiny ;) - Joke NJDude
        pathSourceUrl = URL where is original Image
        imgSource = Name Image original
        pathDestiny = Path where you want put new Image
        imgDestiny = Name Image new
        format = "png" or "jpeg"
        Example:<code>
        Dim FileUrl As PictureDownloadUrl
        FileUrl.Copy("http://devil-app.eu/immagini_mie/","test.jpg", File.DirRootExternal,"vedi","jpeg")</code>
      Permissions:
      • android.permission.INTERNET

    Code Example:

    Code:
    Sub Globals
        
    'These global variables will be redeclared each time the activity is created.
        'These variables can only be accessed from this module.
    Dim FileUrl As PictureDownloadUrl
    End Sub

    Sub Activity_Create(FirstTime As Boolean)
        
    'Do not forget to load the layout file created with the visual designer. For example:
        'Activity.LoadLayout("Layout1")


        
    Dim FileUrl As PictureDownloadUrl
        
    Dim file_share As String = "63206.jpg"
        FileUrl.Copy(
    "http://www.b4x.com/android/forum/data/avatars/m/63/",file_share, File.DirRootExternal,"save","jpeg")
        
    ToastMessageShow("Done, look in File.DirRootExternal you have save.jpeg"True)

    End Sub
     

    Attached Files:

    Last edited: Jul 31, 2015
  2. Reids

    Reids Member Licensed User

    what about the progress % of download?
     
  3. NJDude

    NJDude Expert Licensed User

    LOL.
     
    MarcoRome likes this.
  4. rboeck

    rboeck Well-Known Member Licensed User

    Hi,

    whats the reason to restrict it to pictures? Would it be more complicated to copy any files?
    Thanks,
    Reinhard
     
    MarcoRome likes this.
  5. MarcoRome

    MarcoRome Expert Licensed User

    Right... i will work on it.
     
  6. MarcoRome

    MarcoRome Expert Licensed User

    Doesn't exist...when finish download save file. Maybe in future i can add event downloadcomplete or similar
     
  7. Erel

    Erel Administrator Staff Member Licensed User

    Is the code blocking until download completes?
     
  8. MarcoRome

    MarcoRome Expert Licensed User

    Hi Erel. The code blocking until download completes ( Right DonManfred )
    Anyway this is code, anyone can improve it :) ;):)

    Code:
    package com.devil.app;

    import java.io.IOException;
    import android.app.Activity;
    import android.graphics.Bitmap;
    import android.graphics.BitmapFactory;
    import android.os.Bundle;
    import android.os.Environment;
    import java.io.*;

    import android.app.Activity;
    import android.graphics.Bitmap;
    import android.graphics.Bitmap.CompressFormat;
    import android.graphics.BitmapFactory;
    import android.os.Bundle;
    import android.util.Log;
    import android.widget.ImageView;
    import android.view.View.OnClickListener;
    import android.widget.EditText;
    import android.widget.Toast;
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import android.os.Environment;
    import android.provider.MediaStore;


    import java.io.InputStream;
    import java.io.OutputStream;
    import java.lang.ref.WeakReference;
    import java.lang.reflect.Method;
    import java.util.ArrayList;

    import android.content.ContentProviderOperation;
    import android.content.ContentResolver;
    import android.content.Context;
    import android.content.Intent;
    import android.content.pm.PackageInfo;
    import android.content.pm.PackageManager;
    import android.database.Cursor;
    import android.net.Uri;
    import android.provider.ContactsContract;
    import android.util.Log;
    import android.widget.Toast;
    import android.net.Uri;
    import android.app.Activity;
    import java.net.*;
    import android.app.Activity;
    import android.app.ProgressDialog;
    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.os.StrictMode;



    import anywheresoftware.b4a.BA;
    import anywheresoftware.b4a.BA.Permissions;
    import anywheresoftware.b4a.BA.ShortName;
    import anywheresoftware.b4a.BA.*;
    import anywheresoftware.b4a.*;



    @Version(
    1.1f)
    @ShortName(
    "PictureDownloadUrl")
    @Author(
    "DevilApp")
    //@DependsOn(values={
    "XXX"})
    @Permissions(values={"android.permission.INTERNET"})



    public class PictureDownloadUrl {
        private BA ba;
        private final static boolean DEBUG = false;
        String fullUrl=null;
        String formato=null;
        String dir=null;
        String tutto=null;

    /*
      * Normally do not hardcode "/sdcard/";
      * use Environment.getExternalStorageDirectory().getPath() instead
      */


    /**
    * Resize and Copy Image from URL to Destiny ;) - Joke NJDude
    * pathSourceUrl = URL where is original Image
    * imgSource = Name Image original
    * pathDestiny = Path where you want put new Image
    * imgDestiny = Name Image new
    * format = "png" or "jpeg"
    *Example:<code>
    *Dim FileUrl As PictureDownloadUrl
    *FileUrl.Copy("http://devil-app.eu/immagini_mie/","test.jpg", File.DirRootExternal,"vedi","jpeg")</code>
    */ 
      
        public void Copy(BA ba, String pathSourceUrl, String imgSource, String pathDestiny, String imgDestiny, String format){
                
        
        try {
        
            tutto = pathSourceUrl
             + imgSource;
            BA.Log("lib:Path " + tutto);        
            URL url = new URL(tutto);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
             try {
            connection.setDoInput(true);
            }catch(Exception e){
                if(DEBUG) Log.e("Exception", e.toString());
                BA.Log("lib:Connection 0: " + e.toString());

                int duration = Toast.LENGTH_LONG;
                Toast toast = Toast.makeText(ba.context, "Lib:Connection 0: " + e.toString(), duration);
                toast.show();
            
            }
             try {
            // *** Aggiungo per evitare eccezione al di sopra targeSDKVersion 9
            StrictMode.ThreadPolicy policy = new
            StrictMode.ThreadPolicy.Builder()
            .permitAll().build();
            StrictMode.setThreadPolicy(policy);
            // *** Fine
            connection.connect();
            }catch(Exception e){
                if(DEBUG) Log.e("Exception", e.toString());
                BA.Log("lib:Connection: " + e.toString());
                int duration = Toast.LENGTH_LONG;
                Toast toast = Toast.makeText(ba.context, "Lib:Connection: " + e.toString(), duration);
                toast.show();
            
            }
            InputStream input = connection.getInputStream();
            dir = pathDestiny;
            Bitmap bitmap_Source = BitmapFactory.decodeStream(input);
            int originalWidth = bitmap_Source.getWidth();
            int originalHeight = bitmap_Source.getHeight();

            Bitmap bm = Bitmap.createScaledBitmap(bitmap_Source, originalWidth, originalHeight, false);
            BA.Log("lib:OK.. " + tutto);
            File file = new File(dir, imgDestiny +"."+ format);
            FileOutputStream fOut;
                try {
                    fOut = new FileOutputStream(file);
                    if (format == "png")
                    { bm.compress(Bitmap.CompressFormat.PNG, 100, fOut); }
                    else
                    { bm.compress(Bitmap.CompressFormat.JPEG, 100, fOut); }
                
                    fOut.flush();
                    fOut.close();
                
                } catch (Exception e) { // TODO
                if(DEBUG) Log.e("Exception", e.toString());
                BA.Log("lib:Error 1.. " + tutto);
                int duration = Toast.LENGTH_LONG;
                Toast toast = Toast.makeText(ba.context, "Error 1: " + e.toString(), duration);
                toast.show();
                }
       
           }catch(Exception e){
            
                if(DEBUG) Log.e("Exception", e.toString());
                BA.Log("lib:Error 2.. " + e.toString());
                int duration = Toast.LENGTH_LONG;
                Toast toast = Toast.makeText(ba.context, "Error 2: " + e.toString(), duration);
                toast.show();
            
            
            }
       
         //Salvo File
     

        }


               
    }
     
    Last edited: Jun 29, 2015
  9. DonManfred

    DonManfred Expert Licensed User

    Does not look like async! The code is running in the mainthread.
     
    MarcoRome likes this.
  10. DonManfred

    DonManfred Expert Licensed User

    Does not look async too... Looks more like an Synced call....
     
  11. MarcoRome

    MarcoRome Expert Licensed User

    You are right DonMandred ;):)
     
  12. Erel

    Erel Administrator Staff Member Licensed User

    I don't recommend you to use such code. A http request can easily take 30 seconds or more to complete (successfully or unsuccessfully). This means that your app will be freezed for 30 or more seconds.

    Android doesn't allow such freezes so it will kill your app after 5 seconds if the user touches the screen.

    Downloading files is very simple with HttpUtils2. If you want to work with images only then you should check ImageDownloader: ImageDownloader - The simple way to download images
     
    MarcoRome and Informatix like this.
  13. MarcoRome

    MarcoRome Expert Licensed User

    Mmmhhh... Never happen ( maybe lucky ) but if Master Erel say so, is so:

    Code:
    Activity module
    Sub Process_Globals
    End Sub

    Sub Globals

    End Sub

    Sub Activity_Create(FirstTime As Boolean)
        
    Dim job1 As HttpJob

        job1.Initialize(
    "Job1", Me)
        job1.Download(
    "http://www.b4x.com/android/forum/data/avatars/m/63/63206.jpg")
    End Sub



    Sub JobDone (Job As HttpJob)
        
    Log("JobName = " & Job.JobName & ", Success = " & Job.Success)
        
    If Job.Success = True Then
            
    Select Job.JobName
                
    Case "Job1"
                    
    'show the downloaded image
                    Activity.SetBackgroundImage(Job.GetBitmap)
                    
    Dim out As OutputStream
                    out = 
    File.OpenOutput(File.DirRootExternal,"test.jpg",False)
                    
    File.Copy2(Job.GetInputStream, out)
                    out.close
            
    End Select
        
    Else
            
    Log("Error: " & Job.ErrorMessage)
            
    ToastMessageShow("Error: " & Job.ErrorMessage, True)
        
    End If
        Job.Release
    End Sub

    Sub Activity_Resume

    End Sub

    Sub Activity_Pause (UserClosed As Boolean)

    End Sub
     
  14. Informatix

    Informatix Expert Licensed User

    Last edited: Jun 30, 2015
  15. DonManfred

    DonManfred Expert Licensed User

  16. Informatix

    Informatix Expert Licensed User

    MarcoRome likes this.
  17. DonManfred

    DonManfred Expert Licensed User

    i will try the links later with my UIL Library too :)
     
  18. MarcoRome

    MarcoRome Expert Licensed User

  19. MarcoRome

    MarcoRome Expert Licensed User

    DonManfred work with out problem ;)
     
    DonManfred likes this.
Loading...