How to Upload, Cache, Save and Share image in an Android App?

What if I ask you to guess the icon image for WhatsApp or Instagram? Even before your mind processes my question, decides an image and reverts, your tongue would have already answered to me. Images play that important role in making an app or so to specify, an android app. Here, forehead a sample, I will Upload an image from Android SD Card using App42 Upload Service. Thereafter, I will perform Caching, Sharing and Saving operations on the image.

  • Upload an image on the server from Android SD Card
  • Make a more swift App in case of image caching
  • Increase user engagement by pushing  user to share these images
  • Save these images in SD card


Image Uploading
Firstly, upload an image from Android SD Card to Server so as to get a Web URL to perform operations on the image like sharing. Here, we are using App42′s service to upload an image on the server.

Image Caching 
When you build a mobile or a web application,  you have to make sure it runs as fast as possible. For this, the most important function is caching. If you are using a certain resource in your application, you should know that it isn’t as easy to retrieve. I used LruCache Algorithm to implement this mechanism.

LRUCache
LRU stands for Least Recently Used. The term itself clarifies the way cache would work. LUCaches have a fixed cache size and work like a queue.  If a new object is added to the cache, it is being placed at the beginning of the queue. Later, when the app asks to get an object from the cache, it is placed at the starting of a queue. This way the LRU objects are left at the initial point of the queue.
lru cache How to Upload, Cache, Save and Share image in an Android App?

Image Sampling 
While loading an image from the web, its resolution can be larger than the device. Sampling can provide a better way of loading and optimizing memory.

Image Sharing
Using images in the App from Gallery and sharing it within your contacts will increase user engagement in android.

Image Saving
After loading an image from the web, if you need to save it, you can do so in SD Card for further usage.

About Sample Application

  1. Register with App42 Platform.
  2. Create an app once you are on the Quick-start page after the registration
  3. If you are already registered, login to AppHQ console and create an app from App Manager -> App Create link
  4. Download the project from here and import it in eclispe
  5. Open MainActivity.java file and pass the required information in onCreate method as shown below (application keys for AppHq console)
  6. 1
    
    App42API.initialize(this,"App42 API key","App42 secret Key");
  7. Change the application name with your application name in res/strings (useful to save image in SD card)
  8. Build and run the application


get started How to Upload, Cache, Save and Share image in an Android App?

Design Details

Get Image from Android SD Card Gallery: Get an image for your app from Android SD Card with the code written in MainActivity.java file.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
     /*
     * Call when user clicks on browse photo
     */
    private void browsePhoto(String imageName) {
        if (this.imageName != null && !this.imageName.equals(""))
            this.imageName = imageName;
        Intent i = new Intent(Intent.ACTION_PICK,
                android.provider.MediaStore.Images.Media.EXTERN
AL_CONTENT_URI);
        startActivityForResult(i, RESULT_LOAD_IMAGE);
    }
 
    /*
     * Callback when user select image from gallery for upload
     * get a callback
     * @see android.app.Activity#onActivityResult(int, int,
     * android.content.Intent)
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK
                && null != data) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };
            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            cursor.close();
            progressDialog.setMessage("uploading image");
            progressDialog.show();
            uploadImage(picturePath);
        }
    }

Upload Image Using App42 Uplaod Service: If you want to upload an image on the server from Android Sd Card gallery, you can follow the code written in MainActivity.java file.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
private void uploadImage(String imagePath) {
        App42API.buildUploadService().uploadFile(imageName, imagePath,
                UploadFileType.IMAGE, Description, new App42CallBack() {
 
                    public void onSuccess(Object uploadObj) {
                        // TODO Auto-generated method stub
                        onUploadResult(uploadObj);
                    }
                    public void onException(Exception ex) {
                        // TODO Auto-generated method stub
                        System.out.println(ex);
                        onUploadError(ex);
                    }
                });
    }

Share Image to friends: If you want to share an image with your friends using several apps installed in your device, you can follow the code written in MainActivity.java file.

1
2
3
4
5
6
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, "Hey friends checkout this image"+"\n\n"+imageUrl);
intent.putExtra(android.content.Intent.EXTRA_SUBJECT,
"Check My Image ");
startActivity(Intent.createChooser(intent, "Share"));

Loading and Caching of Image: ImageCacher.java file contains all types of coding, which is required to share an image from the web or cache accordingly.

If you want to load an image without sampling that you should use in our Android Activity class file, here is the code:

1
2
3
ImageView imgLogo = (ImageView) findViewById(R.id.my_image);
ImageCacher imageCacher=new ImageCacher(this, -1);
imageCacher.loadImage(imageUrl, imgLogo);

If you want to load an image with sampling that can be used in your Android Activity class, please follow the code below:

1
2
3
ImageView imgLogo = (ImageView) findViewById(R.id.my_image);
ImageCacher imageCacher=new ImageCacher(this, SamplingImageSize);
imageCacher.loadImage(imageUrl, imgLogo);

If you want to load an image from the web or cache, you should follow the code below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
public Bitmap getBitmap(String url) {
        String filename = String.valueOf(url.hashCode());
        File f = new File(cacheDir, filename);
        // from SD cache
        Bitmap b;
        if (isSamplingReq) {
            b = decodeWithoutSampling(f);
        } else {
            b = decodewithSampleing(f);
        }
        if (b != null)
            return b;
        // from web
        try {
            Bitmap bitmap = null;
            InputStream is = new URL(url).openStream();
            OutputStream os = new FileOutputStream(f);
            Utility.CopyStream(is, os);
            os.close();
            if (isSamplingReq) {
                bitmap = decodeWithoutSampling(f);
            } else {
                bitmap = decodewithSampleing(f);
            }
            return bitmap;
        } catch (Throwable ex) {
            ex.printStackTrace();
            if (ex instanceof OutOfMemoryError)
                clearCache();
            return null;
        }
    }

Code for Image Sampling:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
private Bitmap decodewithSampleing(File f) {
        try {
            // decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(new FileInputStream(f), null, o);
            int width_tmp = o.outWidth, height_tmp = o.outHeight;
            int scale = 1;
            while (true) {
                if (width_tmp / 2 < requiredSize
                        || height_tmp / 2 < requiredSize)
                    break;
                width_tmp /= 2;
                height_tmp /= 2;
                scale *= 2;
            }
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize = scale;
            return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
        } catch (FileNotFoundException e) {
        }
        return null;
    }

Code Without Sampling:

1
2
3
4
5
6
7
8
private Bitmap decodeWithoutSampling(File f) {
        try {
            return BitmapFactory.decodeStream(new FileInputStream(f));
 
        } catch (Exception e) {
        }
        return null;
    }

Save Image in SD Card Gallery: If you want to save an Image in Android SD Card Gallery,
you can follow the code written in MainActivity.java file.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
void saveMyImage() {
        Bitmap bmImg = imageCacher.getBitmap(imageUrl);
        File filename;
        try {
            String path1 = android.os.Environment.getExternalStorageDirectory()
                    .toString();
            Log.i("in save()", "after mkdir");
            File file = new File(path1 + "/" + appName);
            if (!file.exists())
                file.mkdirs();
            filename = new File(file.getAbsolutePath() + "/" + imageName
                    + ".jpg");
            Log.i("in save()", "after file");
            FileOutputStream out = new FileOutputStream(filename);
            Log.i("in save()", "after outputstream");
            bmImg.compress(Bitmap.CompressFormat.JPEG, 90, out);
            out.flush();
            out.close();
            Log.i("in save()", "after outputstream closed");
            //File parent = filename.getParentFile();
            ContentValues image = getImageContent(filename);
            Uri result = getContentResolver().insert(
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI, image);
            Toast.makeText(getApplicationContext(),
                    "File is Saved in  " + filename, Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            e.printStackTrace();
        }
 
    }
    public ContentValues getImageContent(File parent) {
        ContentValues image = new ContentValues();
        image.put(Images.Media.TITLE, appName);
        image.put(Images.Media.DISPLAY_NAME, imageName);
        image.put(Images.Media.DESCRIPTION, "App Image");
        image.put(Images.Media.DATE_ADDED, System.currentTimeMillis());
        image.put(Images.Media.MIME_TYPE, "image/jpg");
        image.put(Images.Media.ORIENTATION, 0);
        image.put(Images.ImageColumns.BUCKET_ID, parent.toString()
                .toLowerCase().hashCode());
        image.put(Images.ImageColumns.BUCKET_DISPLAY_NAME, parent.getName()
                .toLowerCase());
        image.put(Images.Media.SIZE, parent.length());
        image.put(Images.Media.DATA, parent.getAbsolutePath());
        return image;
    }

In this blog, I have explained you about uploading, caching, saving and sharing of images in Android application.

If you have any queries or need further assistance, please feel free to reach us at support@shephertz.com

twitter How to Upload, Cache, Save and Share image in an Android App?facebook How to Upload, Cache, Save and Share image in an Android App?google How to Upload, Cache, Save and Share image in an Android App?linkedin How to Upload, Cache, Save and Share image in an Android App?pinterest How to Upload, Cache, Save and Share image in an Android App?reddit How to Upload, Cache, Save and Share image in an Android App?stumbleupon How to Upload, Cache, Save and Share image in an Android App?tumblr How to Upload, Cache, Save and Share image in an Android App?