Mastering Visuals on Android: A Seamless App Image Guide

Imagine I asked you to guess the icon image for WhatsApp or Instagram. Even before your mind processes the question, decides on an image, and responds, your mouth would have already answered me. Visuals play a vital role in creating an app, specifically an Android app. Here, for instance,

Picture this: I ask you to conjure up the icon image for WhatsApp or Instagram. Even before your mind has a chance to process the question, formulate an answer, and respond, your instincts would have already supplied the image. Visuals play a pivotal role in crafting an app, particularly an Android app. Here, for instance, I will demonstrate how to upload an image from an Android SD card using the

App42 upload service

. Subsequently, I will delve into caching, sharing, and saving operations on the image.

  • Transfer an image to the server from an Android SD card.
  • Develop a more agile app for image caching.
  • Foster user engagement by encouraging users to share these images.
  • Store these images to an SD card.


Mastering Image Uploading

First, upload an image from an Android SD card to the server to obtain a web URL, enabling operations on the image, such as sharing. Here, we are leveraging App42’s service to upload an image to the server.


Optimizing Image Caching

When building a mobile or web application, it’s crucial to ensure it runs as swiftly as possible. For this, caching is a vital function. If you’re using a certain resource in your application, you should be aware that it isn’t easy to retrieve. I employed the LRUCache algorithm to implement this mechanism.


Understanding LRUCache


LRU

stands for Least Recently Used. The term itself elucidates how the cache works. LRUCaches have a fixed cache size and function 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 requests to retrieve an object from the cache, it is placed at the start of the queue. This way, the LRU objects are left at the initial point of the queue


Image Downsampling

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


Seamless Image Sharing

Using images in the app from the gallery and sharing them within your contacts will increase user engagement in Android.

Source: https://carsnewstoday.com/programming/data-engineering/unlock-android-app-image-mastery-expert-guide-to-uploading-caching-saving-and-sharing-visuals-seamlessly/


Safeguarding Visual Content

After retrieving an image from the internet, you can archive it on an SD card for later use.

Example Implementation

  1. Register with the

    App42 platform

    .
  2. Create a new application on the quick-start page following registration.
  3. If you’re already registered, log in to the

    AppHQ

    console and create an application via the App Manager Create App link.
  4. Download the project from

    here

    and import it into Eclipse.
  5. Open the MainActivity.java file and provide the necessary details in the

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

To transfer an image from your Android device's SD card gallery to a remote server, simply adhere to the code outlined 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 wish to disseminate an image to your friends using multiple apps installed on your device, follow the code 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" + "\" + imageUrl);intent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Check my image");startActivity(Intent.createChooser(intent, "Share"));

The ImageCacher.java file encompasses all the necessary code to disseminate an image from the web or cache accordingly.

To load an image without downsampling in your Android activity class file, utilize the following code:

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

If you wish to load an image with downsampling in your Android activity class, please adhere to the code below:

ImageView imgLogo = (ImageView) findViewById(R.id.my_image);ImageCacher imageCacher = new ImageCacher(this, samplingImageSize);imageCacher.loadImage(imageUrl, imgLogo);

To retrieve an image from the web or cache, follow the code snippet below:

public Bitmap fetchBitmap(String url) {    String filename = String.valueOf(url.hashCode());    File file = new File(cacheDir, filename);    // from SD cache    Bitmap bitmap;    if (isSamplingReq) {        bitmap = decodeWithoutResampling(file);    } else {        bitmap = decodeWithResampling(file);    }    if (bitmap != null)        return bitmap;    // from web    try {        Bitmap image = null;        InputStream inputStream = new URL(url).openStream();        OutputStream outputStream = new FileOutputStream(file);        Utility.copyStream(inputStream, outputStream);        outputStream.close();        if (isSamplingReq) {            image = decodeWithoutResampling(file);        } else {            image = decodeWithResampling(file);        }        return image;    } catch (Throwable ex) {        ex.printStackTrace();        if (ex instanceof OutOfMemoryError)            clearCache();        return null;    }}


Code for Image Resampling:

private bitmap decodeWithResampling(File file) {        try {            // Retrieve image dimensions            BitmapFactory.Options options = new BitmapFactory.Options();            options.inJustDecodeBounds = true;            BitmapFactory.decodeStream(new FileInputStream(file), null, options);            int widthTemp = options.outWidth, heightTemp = options.outHeight;            int scalingFactor = 1;            while (true) {                if (widthTemp / 2  requiredSize                        || heightTemp / 2  requiredSize)                    break;                widthTemp /= 2;                heightTemp /= 2;                scalingFactor *= 2;            }            BitmapFactory.Options options2 = new BitmapFactory.Options();            options2.inSampleSize = scalingFactor;            return BitmapFactory.decodeStream(new FileInputStream(file), null, options2);        } catch (FileNotFoundException e) {        }        return null;    }


Code without Downsampling:

private bitmap decodeWithoutDownsampling(File file) {        try {            return BitmapFactory.decodeStream(new FileInputStream(file));        } catch (Exception e) {        }        return null;    }


Store Image in SD Card Gallery:

If you desire to store an image in the Android SD card gallery,

you can follow the code outlined in the 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;    }

Within this blog, I embark on an in-depth exploration of the complexities involved in managing visual media within an Android application, covering the entire spectrum of uploading, storing, caching, and distributing images.


Isabella Clark

13 Blog posts

Comments