B4A Library Library PictureDownloadUrl

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:
B4X:
Dim file_share asString = "example.jpg"
File.Copy(File.DirAssets, file_share, File.DirRootExternal, "save.jpg")
same thing to copy from web:
B4X:
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:

B4X:
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("https://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
 

Attachments

  • PictureDownloadUrl-example.zip
    7.6 KB · Views: 277
  • PictureDownloadUrl-Library.zip
    8.2 KB · Views: 303
Last edited:

rboeck

Well-Known Member
Licensed User
Longtime User
Hi,

whats the reason to restrict it to pictures? Would it be more complicated to copy any files?
Thanks,
Reinhard
 

MarcoRome

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

B4X:
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:

DonManfred

Expert
Licensed User
Longtime User
Does not look like async! The code is running in the mainthread.
 

DonManfred

Expert
Licensed User
Longtime User

Erel

B4X founder
Staff member
Licensed User
Longtime 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

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

B4X:
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("https://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
 

DonManfred

Expert
Licensed User
Longtime User
Top