Android image compression example code

The core idea is to scale the picture through bitmapfactory.options, mainly using its insamplesize parameter (sampling rate)

When insamplesize is 1, the size of the sampled image is the original size of the image;

When insamplesize is 2, the width and height of the sampled image are 1 / 2 of the original, that is, its pixels are 1 / 4 of the original, and the memory occupied is naturally 1 / 4 of the original. and so on.

When insamplesize is less than 1, the effect is the same as when insamplesize is equal to 1.

The compression process is as follows:

1. The injustdecodebounds parameter of bitmapfactory.options is set to true (at this time, bitmapfactory only parses the original width and height of the picture and does not load the picture).

2. Take out the original width and height, outwidth and outheight of the picture from bitmapfactory.options.

3. Set the appropriate sampling rate according to your own needs.

4. Set the injustdecodebounds parameter of bitmapfactory.options to false, and then you can load the picture.

Let's look at the code below:

In this way, the compression of a picture is completed. In addition, bitmapfactory has other decode methods, and we can follow the above.

Next, a small demo is combined to implement a complete process

First encapsulate the image compression class

Then you can use it:

activity_ main2.xml

Main2Activity.Java

Finally, remember to obtain network permissions

Results of operation:

Comparison of bitmap size before and after compression

Comparison of bitmap size before and after compression

The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support programming tips.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>