Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

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

DZone's Guide to

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

Encouraging app users to share images increases user engagement. Learn to upload, cache, save, and share images in an Android app.

· Mobile Zone ·
Free Resource

What if I ask you to guess the icon image for WhatsApp or Instagram? Even before your mind processes my question, decides on an image and responds, your mouth would have already answered me. Images play that important role in making an app, or to specify, an Android app. Here, for example, I will upload an image from an Android SD Card using the 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 for image caching.
  • Increase user engagement by pushing users to share these images.
  • Save these images to an SD card.

Image Uploading

First, upload an image from an Android SD Card to the 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 to 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 easy to retrieve. I used the LRUCache Algorithm to implement this mechanism.

LRUCache

LRU stands for Least Recently Used. The term itself clarifies the way cache works. LRUCaches have a fixed cache size and work like a queue.  If a new object is added to the cache, it is placed at the beginning of the queue. Later, when the app asks to get an object from the cache, it is placed at the start of a queue. This way the LRU objects are left at the initial point of the queue

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 the 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 on an SD Card for further usage.

Sample Application

  1. Register with the 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 into Eclipse.
  5. Open MainActivity.java file and pass the required information in onCreate method as shown below (application keys for AppHQ console).
App42API.initialize(this,"App42 API key","App42 secret Key");

Change the application name with your application name in res/strings (useful to save image in SD card), then build and run the application 

Design Details

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

     /*
     * 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);
        }
    }

If you want to upload an image on the server from Android SD Card gallery, you can follow the code written in the MainActivity.java file.

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);
                    }
                });
    }

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

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"));

ImageCacher.java file contains all types of code 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:

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:

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:

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:

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:

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.

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 uploading, caching, saving, and sharing of images in an Android application.

Topics:
caching ,mobile ,mobile app development ,android ,images

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}