Here is a fun tutorial on how to compress images picked by users from the gallery using Jetpack Compose and Kotlin.
- First things first, you gotta add a dependency called coil to your project's build.gradle file. This coil will take the magic juice (URI) of the image selected by the user and display it.
- Next, you gotta create a function that converts a URI, which is kind of an address to the image, to a drawable. You gotta remember, drawables are the pictures that show up on your fancy app.
- Since converting things is always fun, let's create another function that resizes an image. This function takes a drawable as input and returns another drawable. But watch out, it might return null if the drawable is null itself. If the drawable isn't null, we gotta create a byte array output stream. You can think of this output stream as a magic pipe where you put in your image and it squishes it out smaller!
- Now, let's compress the image! We gotta create a Bitmap, which is like a special image format for Android. To compress this Bitmap, we gotta call the compress function. This function takes a bunch of arguments, including the quality of the image (like how much you wanna squish it), and the output stream we created earlier.
- Finally, let's set up the user interface. We'll use a launcher to pick an image from the gallery. Once the user picks an image, we'll display it on the screen. Below the image, we'll add a button that says "Compress the image". When the user clicks this button, we'll call the compress function we created earlier and then display the compressed image.
And that's it! With a little bit of code, you can compress images and save users some storage space. Just be careful not to compress the images too much, otherwise they might look like they went through a meat grinder!