In this Image Compression in Android tutorial, I will explain how to pick an image from Gallery or Camera and compress it before uploading it.
I am sharing this code because the maximum android app has a user account. If a user creates his account, the profile picture needs to be added compulsory. We need to pick a picture from Gallery or Camera. Some applications depend on media like Facebook or Instagram to source the image. My article will increase your understanding on how to compress images in Android.
1. Create a basic android project
Go to Android Studio | File | New | New Project
2. Our app needs two permissions in our AndroidManifest.xml file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
3. Now we need a simple layout file with above mention design i.e. 2 Image view and 3 Buttons. Create new layout file i.e.layout/activity_main
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.mb.imagescalling.MainActivity"> <LinearLayout android:id="@+id/activity_main_ll_lable" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_marginTop="10dp" android:orientation="horizontal"> <TextView android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:gravity="center" android:text="@string/normal_image" /> <TextView android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:gravity="center" android:text="@string/compress_image" /> </LinearLayout> <LinearLayout android:id="@+id/activity_main_ll_image" android:layout_width="match_parent" android:layout_height="300dp" android:layout_below="@+id/activity_main_ll_lable" android:layout_marginTop="10dp" android:orientation="horizontal"> <ImageView android:id="@+id/activity_main_img" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" app:srcCompat="@mipmap/ic_launcher" /> <ImageView android:id="@+id/activity_main_img_compress" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" app:srcCompat="@mipmap/ic_launcher" /> </LinearLayout> <Button android:id="@+id/activity_main_btn_load_from_gallery" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/activity_main_ll_image" android:layout_centerHorizontal="true" android:layout_marginTop="20dp" android:text="@string/load_from_gallery" /> <Button android:id="@+id/activity_main_btn_load_from_camera" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/activity_main_btn_load_from_gallery" android:layout_centerHorizontal="true" android:layout_marginTop="10dp" android:text="@string/load_from_camera" /> <Button android:id="@+id/activity_main_btn_compress" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignEnd="@+id/activity_main_btn_load_from_camera" android:layout_alignLeft="@+id/activity_main_btn_load_from_gallery" android:layout_alignRight="@+id/activity_main_btn_load_from_camera" android:layout_alignStart="@+id/activity_main_btn_load_from_gallery" android:layout_below="@+id/activity_main_btn_load_from_camera" android:layout_marginTop="10dp" android:text="@string/compress" /> </RelativeLayout>
We also need some labels for Button and Imageview in values/strings.xml
<string name="load_from_gallery">Load From Gallery</string> <string name="load_from_camera">Load From Camera</string> <string name="compress">Compress</string> <string name="normal_image">Normal Image</string> <string name="compress_image">Compress Image</string>
4. Android code for picking the image from Gallery or Camera. “Load From Gallery”
Intent intentGalley = new Intent(Intent.ACTION_PICK); intentGalley.setType("image/*"); startActivityForResult(intentGalley, PICK_GALLERY_IMAGE);
“Load From Camera”
destFile = new File(file, "img_"+ dateFormatter.format(new Date()).toString() + ".png"); imageCaptureUri = Uri.fromFile(destFile); Intent intentCamera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); intentCamera.putExtra(MediaStore.EXTRA_OUTPUT, imageCaptureUri); startActivityForResult(intentCamera, PICK_CAMERA_IMAGE);
When user selects image from Gallery or Camera, method onActivityResult() will be called in your main activity. Once you get the data in onActivityResult() , we need to handle it.
We are doing two operations on selected image.
protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == Activity.RESULT_OK) { switch (requestCode) { case PICK_GALLERY_IMAGE: Uri uriPhoto = data.getData(); Log.d(TAG + ".PICK_GALLERY_IMAGE", "Selected image uri path :" + uriPhoto.toString()); img.setImageURI(uriPhoto); sourceFile = new File(getPathFromGooglePhotosUri(uriPhoto)); destFile = new File(file, "img_"+ dateFormatter.format(new Date()).toString() + ".png"); Log.d(TAG, "Source File Path :" + sourceFile); try { copyFile(sourceFile, destFile); } catch (IOException e) { e.printStackTrace(); } break; case PICK_CAMERA_IMAGE: Log.d(TAG + ".PICK_CAMERA_IMAGE", "Selected image uri path :" + imageCaptureUri); img.setImageURI(imageCaptureUri); break; } } }
5. Copy image from selected folder to application folder. If we want to copy an image from one folder to another folder, we need file path i.e. Source file and Destination file.
private void copyFile(File sourceFile, File destFile) throws IOException { if (!sourceFile.exists()) { return; } FileChannel source = null; FileChannel destination = null; source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); if (destination != null && source != null) { destination.transferFrom(source, 0, source.size()); } if (source != null) { source.close(); } if (destination != null) { destination.close(); } } } }
When we pick an image from gallery we got the image data from Uri format but we need a file to copy one folder to another. So now we are using one method getPathFromGooglePhotosUri() for getting string path from Uri.
public String getPathFromGooglePhotosUri(Uri uriPhoto) { if (uriPhoto == null) return null; FileInputStream input = null; FileOutputStream output = null; try { ParcelFileDescriptor pfd = getContentResolver().openFileDescriptor(uriPhoto, "r"); FileDescriptor fd = pfd.getFileDescriptor(); input = new FileInputStream(fd); String tempFilename = getTempFilename(this); output = new FileOutputStream(tempFilename); int read; byte[] bytes = new byte[4096]; while ((read = input.read(bytes)) != -1) { output.write(bytes, 0, read); } return tempFilename; } catch (IOException ignored) { // Nothing we can do } finally { closeSilently(input); closeSilently(output); } return null; } public static void closeSilently(Closeable c) { if (c == null) return; try { c.close(); } catch (Throwable t) { // Do nothing } } private static String getTempFilename(Context context) throws IOException { File outputDir = context.getCacheDir(); File outputFile = File.createTempFile("image", "tmp", outputDir); return outputFile.getAbsolutePath(); }
6. Once you get the selected image in onActivityResult(), we will compress it and set it to another Imageview.
private Bitmap decodeFile(File f) { Bitmap b = null; //Decode image size BitmapFactory.Options o = new BitmapFactory.Options(); o.inJustDecodeBounds = true; FileInputStream fis = null; try { fis = new FileInputStream(f); BitmapFactory.decodeStream(fis, null, o); fis.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } int IMAGE_MAX_SIZE = 1024; int scale = 1; if (o.outHeight > IMAGE_MAX_SIZE || o.outWidth > IMAGE_MAX_SIZE) { scale = (int) Math.pow(2, (int) Math.ceil(Math.log(IMAGE_MAX_SIZE / (double) Math.max(o.outHeight, o.outWidth)) / Math.log(0.5))); } //Decode with inSampleSize BitmapFactory.Options o2 = new BitmapFactory.Options(); o2.inSampleSize = scale; try { fis = new FileInputStream(f); b = BitmapFactory.decodeStream(fis, null, o2); fis.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } Log.d(TAG, "Width :" + b.getWidth() + " Height :" + b.getHeight()); destFile = new File(file, "img_" + dateFormatter.format(new Date()).toString() + ".png"); try { FileOutputStream out = new FileOutputStream(destFile); b.compress(Bitmap.CompressFormat.PNG, 100, out); out.flush(); out.close(); } catch (Exception e) { e.printStackTrace(); } return b; }
Get the compressed image in bitmap format and set to image view after clicking on compress button.
Bitmap bmp = decodeFile(destFile); imgCompress.setImageBitmap(bmp);
public class MainActivity extends AppCompatActivity implements View.OnClickListener { private final String TAG = getClass().getSimpleName(); private static final int PICK_CAMERA_IMAGE = 2; private static final int PICK_GALLERY_IMAGE = 1; public static final String DATE_FORMAT = "yyyyMMdd_HHmmss"; public static final String IMAGE_DIRECTORY = "ImageScalling"; private static final String SCHEME_FILE = "file"; private static final String SCHEME_CONTENT = "content"; private Button btnGallery; private Button btnCamera; private Button btnCompress; private ImageView img; private ImageView imgCompress; private Uri imageCaptureUri; private File file; private File sourceFile; private File destFile; private SimpleDateFormat dateFormatter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); file = new File(Environment.getExternalStorageDirectory() + "/" + IMAGE_DIRECTORY); if (!file.exists()) { file.mkdirs(); } dateFormatter = new SimpleDateFormat( DATE_FORMAT, Locale.US); initView(); } public void initView() { btnGallery = (Button) findViewById(R.id.activity_main_btn_load_from_gallery); btnCamera = (Button) findViewById(R.id.activity_main_btn_load_from_camera); btnCompress = (Button) findViewById(R.id.activity_main_btn_compress); img = (ImageView) findViewById(R.id.activity_main_img); imgCompress = (ImageView) findViewById(R.id.activity_main_img_compress); btnGallery.setOnClickListener(this); btnCamera.setOnClickListener(this); btnCompress.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.activity_main_btn_load_from_gallery: Intent intentGalley = new Intent(Intent.ACTION_PICK); intentGalley.setType("image/*"); startActivityForResult(intentGalley, PICK_GALLERY_IMAGE); break; case R.id.activity_main_btn_load_from_camera: destFile = new File(file, "img_" + dateFormatter.format(new Date()).toString() + ".png"); imageCaptureUri = Uri.fromFile(destFile); Intent intentCamera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); intentCamera.putExtra(MediaStore.EXTRA_OUTPUT, imageCaptureUri); startActivityForResult(intentCamera, PICK_CAMERA_IMAGE); break; case R.id.activity_main_btn_compress: Bitmap bmp = decodeFile(destFile); imgCompress.setImageBitmap(bmp); break; } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == Activity.RESULT_OK) { switch (requestCode) { case PICK_GALLERY_IMAGE: Uri uriPhoto = data.getData(); Log.d(TAG + ".PICK_GALLERY_IMAGE", "Selected image uri path :" + uriPhoto.toString()); img.setImageURI(uriPhoto); sourceFile = new File(getPathFromGooglePhotosUri(uriPhoto)); destFile = new File(file, "img_" + dateFormatter.format(new Date()).toString() + ".png"); Log.d(TAG, "Source File Path :" + sourceFile); try { copyFile(sourceFile, destFile); } catch (IOException e) { e.printStackTrace(); } break; case PICK_CAMERA_IMAGE: Log.d(TAG + ".PICK_CAMERA_IMAGE", "Selected image uri path :" + imageCaptureUri); img.setImageURI(imageCaptureUri); break; } } } private Bitmap decodeFile(File f) { Bitmap b = null; //Decode image size BitmapFactory.Options o = new BitmapFactory.Options(); o.inJustDecodeBounds = true; FileInputStream fis = null; try { fis = new FileInputStream(f); BitmapFactory.decodeStream(fis, null, o); fis.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } int IMAGE_MAX_SIZE = 1024; int scale = 1; if (o.outHeight > IMAGE_MAX_SIZE || o.outWidth > IMAGE_MAX_SIZE) { scale = (int) Math.pow(2, (int) Math.ceil(Math.log(IMAGE_MAX_SIZE / (double) Math.max(o.outHeight, o.outWidth)) / Math.log(0.5))); } //Decode with inSampleSize BitmapFactory.Options o2 = new BitmapFactory.Options(); o2.inSampleSize = scale; try { fis = new FileInputStream(f); b = BitmapFactory.decodeStream(fis, null, o2); fis.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } Log.d(TAG, "Width :" + b.getWidth() + " Height :" + b.getHeight()); destFile = new File(file, "img_" + dateFormatter.format(new Date()).toString() + ".png"); try { FileOutputStream out = new FileOutputStream(destFile); b.compress(Bitmap.CompressFormat.PNG, 100, out); out.flush(); out.close(); } catch (Exception e) { e.printStackTrace(); } return b; } /** * This is useful when an image is available in sdcard physically. * * @param uriPhoto * @return */ public String getPathFromUri(Uri uriPhoto) { if (uriPhoto == null) return null; if (SCHEME_FILE.equals(uriPhoto.getScheme())) { return uriPhoto.getPath(); } else if (SCHEME_CONTENT.equals(uriPhoto.getScheme())) { final String[] filePathColumn = {MediaStore.MediaColumns.DATA, MediaStore.MediaColumns.DISPLAY_NAME}; Cursor cursor = null; try { cursor = getContentResolver().query(uriPhoto, filePathColumn, null, null, null); if (cursor != null && cursor.moveToFirst()) { final int columnIndex = (uriPhoto.toString() .startsWith("content://com.google.android.gallery3d")) ? cursor .getColumnIndex(MediaStore.MediaColumns.DISPLAY_NAME) : cursor.getColumnIndex(MediaStore.MediaColumns.DATA); // Picasa images on API 13+ if (columnIndex != -1) { String filePath = cursor.getString(columnIndex); if (!TextUtils.isEmpty(filePath)) { return filePath; } } } } catch (IllegalArgumentException e) { // Nothing we can do Log.d(TAG, "IllegalArgumentException"); e.printStackTrace(); } catch (SecurityException ignored) { Log.d(TAG, "SecurityException"); // Nothing we can do ignored.printStackTrace(); } finally { if (cursor != null) cursor.close(); } } return null; } /** * This is useful when an image is not available in sdcard physically but it displays into photos application via google drive(Google Photos) and also for if image is available in sdcard physically. * * @param uriPhoto * @return */
public String getPathFromGooglePhotosUri(Uri uriPhoto) { if (uriPhoto == null) return null; FileInputStream input = null; FileOutputStream output = null; try { ParcelFileDescriptor pfd = getContentResolver().openFileDescriptor(uriPhoto, "r"); FileDescriptor fd = pfd.getFileDescriptor(); input = new FileInputStream(fd); String tempFilename = getTempFilename(this); output = new FileOutputStream(tempFilename); int read; byte[] bytes = new byte[4096]; while ((read = input.read(bytes)) != -1) { output.write(bytes, 0, read); } return tempFilename; } catch (IOException ignored) { // Nothing we can do } finally { closeSilently(input); closeSilently(output); } return null; } public static void closeSilently(Closeable c) { if (c == null) return; try { c.close(); } catch (Throwable t) { // Do nothing } } private static String getTempFilename(Context context) throws IOException { File outputDir = context.getCacheDir(); File outputFile = File.createTempFile("image", "tmp", outputDir); return outputFile.getAbsolutePath(); } private void copyFile(File sourceFile, File destFile) throws IOException { if (!sourceFile.exists()) { return; } FileChannel source = null; FileChannel destination = null; source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); if (destination != null && source != null) { destination.transferFrom(source, 0, source.size()); } if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
Hope this Image Compression in Android tutorial will help you to eliminate the crashing and also avoid huge load time. Now you can easily compress image size in android programmatically. Get in touch with us If you want to hire dedicated android developer.
How to Effectively Hire and Manage a Remote Team of Developers.
Download NowThe team at Mindbowser was highly professional, patient, and collaborative throughout our engagement. They struck the right balance between offering guidance and taking direction, which made the development process smooth. Although our project wasn’t related to healthcare, we clearly benefited...
Founder, Texas Ranch Security
Mindbowser played a crucial role in helping us bring everything together into a unified, cohesive product. Their commitment to industry-standard coding practices made an enormous difference, allowing developers to seamlessly transition in and out of the project without any confusion....
CEO, MarketsAI
I'm thrilled to be partnering with Mindbowser on our journey with TravelRite. The collaboration has been exceptional, and I’m truly grateful for the dedication and expertise the team has brought to the development process. Their commitment to our mission is...
Founder & CEO, TravelRite
The Mindbowser team's professionalism consistently impressed me. Their commitment to quality shone through in every aspect of the project. They truly went the extra mile, ensuring they understood our needs perfectly and were always willing to invest the time to...
CTO, New Day Therapeutics
I collaborated with Mindbowser for several years on a complex SaaS platform project. They took over a partially completed project and successfully transformed it into a fully functional and robust platform. Throughout the entire process, the quality of their work...
President, E.B. Carlson
Mindbowser and team are professional, talented and very responsive. They got us through a challenging situation with our IOT product successfully. They will be our go to dev team going forward.
Founder, Cascada
Amazing team to work with. Very responsive and very skilled in both front and backend engineering. Looking forward to our next project together.
Co-Founder, Emerge
The team is great to work with. Very professional, on task, and efficient.
Founder, PeriopMD
I can not express enough how pleased we are with the whole team. From the first call and meeting, they took our vision and ran with it. Communication was easy and everyone was flexible to our schedule. I’m excited to...
Founder, Seeke
We had very close go live timeline and Mindbowser team got us live a month before.
CEO, BuyNow WorldWide
If you want a team of great developers, I recommend them for the next project.
Founder, Teach Reach
Mindbowser built both iOS and Android apps for Mindworks, that have stood the test of time. 5 years later they still function quite beautifully. Their team always met their objectives and I'm very happy with the end result. Thank you!
Founder, Mindworks
Mindbowser has delivered a much better quality product than our previous tech vendors. Our product is stable and passed Well Architected Framework Review from AWS.
CEO, PurpleAnt
I am happy to share that we got USD 10k in cloud credits courtesy of our friends at Mindbowser. Thank you Pravin and Ayush, this means a lot to us.
CTO, Shortlist
Mindbowser is one of the reasons that our app is successful. These guys have been a great team.
Founder & CEO, MangoMirror
Kudos for all your hard work and diligence on the Telehealth platform project. You made it possible.
CEO, ThriveHealth
Mindbowser helped us build an awesome iOS app to bring balance to people’s lives.
CEO, SMILINGMIND
They were a very responsive team! Extremely easy to communicate and work with!
Founder & CEO, TotTech
We’ve had very little-to-no hiccups at all—it’s been a really pleasurable experience.
Co-Founder, TEAM8s
Mindbowser was very helpful with explaining the development process and started quickly on the project.
Executive Director of Product Development, Innovation Lab
The greatest benefit we got from Mindbowser is the expertise. Their team has developed apps in all different industries with all types of social proofs.
Co-Founder, Vesica
Mindbowser is professional, efficient and thorough.
Consultant, XPRIZE
Very committed, they create beautiful apps and are very benevolent. They have brilliant Ideas.
Founder, S.T.A.R.S of Wellness
Mindbowser was great; they listened to us a lot and helped us hone in on the actual idea of the app. They had put together fantastic wireframes for us.
Co-Founder, Flat Earth
Ayush was responsive and paired me with the best team member possible, to complete my complex vision and project. Could not be happier.
Founder, Child Life On Call
The team from Mindbowser stayed on task, asked the right questions, and completed the required tasks in a timely fashion! Strong work team!
CEO, SDOH2Health LLC
Mindbowser was easy to work with and hit the ground running, immediately feeling like part of our team.
CEO, Stealth Startup
Mindbowser was an excellent partner in developing my fitness app. They were patient, attentive, & understood my business needs. The end product exceeded my expectations. Thrilled to share it globally.
Owner, Phalanx
Mindbowser's expertise in tech, process & mobile development made them our choice for our app. The team was dedicated to the process & delivered high-quality features on time. They also gave valuable industry advice. Highly recommend them for app development...
Co-Founder, Fox&Fork