The process of compressing an image in Android for uploading to a server
I want to write my own code for a compressed image before uploading it to the server.
I’ve seen a lot of similar on SO this There are many other posts in the post, but there are only code samples everywhere. It is not actually explained anywhere. I can’t understand from the given code.
I
just want to know the whole way to compress pictures so I can start writing code myself.
I’m not looking for code, just looking for the steps one needs to follow to compress an image. (It’s like writing an algorithm, i.e. pseudocode, before writing a program).
Solution
I think Chetan Joshi’s answer is by far the closest. But to explain further,
A “compressed” image and a “scaled” (resized) image are different. Since you just want to reduce the network bandwidth (KB/MB) when uploading to the server, you are most likely talking about “scaling” because this will have the biggest impact on the size of the image.
Note that as with other Android answers, you need to use Bitmaps API calls to perform the action you want.
Starting point:
If you allow your app to take photos using the camera or pick photos from the gallery, you’ll get a Uri that allows you to open an InputStream: like this
InputStream is = getContext().getContentResolver().openInputStream(photoUri);
This is the first step. The next part is the pseudocode you want like this:
- Gets the
InputStream
of the photo/selected image. This is simply a byte stream that represents the image. - Use
BitmapFactory.decodeStream (InputStream src) to decode
the stream intoa bitmap
- Use
Bitmap.createScaledBitmap(src, dstWidth, dstHeight, filter);
Scale (resize) the bitmap. You have to decide the target width and target height yourself. See the next set of pseudocode. - CompressFormat(), 100, output) compresses the bitmap using
imageFormat.getBitmapCompressFormat(), where output
is an instance ofByteArrayOutputStream
- You can now call
output.toByteArray();
to get bytes. - Bytes are what you want to send to the server.
Notes on how to choose the target width and height to scale to:
- Determine the maximum height and width, for example, 240 x 240. You’ll compare it to the actual height and actual width of the bitmap.
- If it is too tall (actual height > maximum height), calculate the scale factor of maximum height/actual height
- If it is too wide (actual width > maximum width), a scale factor is calculated, which is maximum width/actual width
- Your actual scale factor is the smallest of the two scale factors
- and the actual width * scale factor
Returns the actual height * scale factor
Overall, the high-level process looks like this:
- Open the image byte stream
- Converts bytes to bitmaps
- Scale the bitmap
- Compress bitmaps
- Converts the bitmap back to bytes