1 / 9

A comprehensive tutorial to upload, cache, save and share image in Android apps

A tutorial addressing common Android Dev issues related to images and icons, using App42 Upload service and performing Caching, Sharing and Saving operations on the image along with relevant definitions and code snippets.

shephertz
Télécharger la présentation

A comprehensive tutorial to upload, cache, save and share image in Android apps

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 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 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 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. Uploading Caching

  2. Image 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 Using images in the App from Gallery and sharing it within your contacts will increase user engagement in android. Image 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 Sampling Sharing Saving 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) App42API.initialize(this,"App42 API key","App42 secret Key"); 1.Change the application name with your application name in res/strings (useful to save image in SD card) 2.Build and run the application 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. /*

  3. * 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();

  4. 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. 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. Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("text/plain");

  5. 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: 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

  6. 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;

  7. 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() {

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

  9. } 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

More Related