When developing Android apps, images are often uploaded to the server, as is the case in a project that our company currently maintains. The project is through the private APN and the server to interact with the good, but the speed of the move is too slow, the customer in the process of using the software, because the uploaded information may contain more than one picture, will often appear to upload the picture failure problem, in order to solve this problem, we decided to compress the photos below 100k, and ensure that the picture is not true (at present the picture after compression, about 300k or so). So I re-examined the image compression technology of Android.
The Android-side directory structure looks like this:
Use the third-party library jar package as shown in:
Where Ksoap2-android-xxx.jar is used by Android to call WebService, Gson-xx.jar is to turn JavaBean into JSON data format.
This blog mainly explains the image compression, the core code is as follows:
[Java]View Plaincopy
- Calculate the zoom value of a picture
- Public static int calculateinsamplesize (bitmapfactory.options Options,int reqwidth, int reqheight) {
- final int height = options.outheight;
- final int width = options.outwidth;
- int insamplesize = 1;
- if (height > Reqheight | | width > reqwidth) {
- final int heightratio = Math.Round ((float) height/(float) reqheight);
- final int widthRatio = Math.Round ((float) width/(float) reqwidth);
- Insamplesize = HeightRatio < WidthRatio? Heightratio:widthratio;
- }
- return insamplesize;
- }
[Java]View Plaincopy
- Get the picture and compress it according to the path, return bitmap for display
- Public static Bitmap Getsmallbitmap (String filePath) {
- final Bitmapfactory.options Options = new Bitmapfactory.options ();
- Options.injustdecodebounds = true;
- Bitmapfactory.decodefile (FilePath, Options);
- //Calculate insamplesize
- Options.insamplesize = calculateinsamplesize (options, 480, 800);
- //Decode bitmap with Insamplesize set
- Options.injustdecodebounds = false;
- return Bitmapfactory.decodefile (FilePath, Options);
- }
[Java]View Plaincopy
- Convert Bitmap to String
- Public static String bitmaptostring (String filePath) {
- Bitmap BM = Getsmallbitmap (FilePath);
- Bytearrayoutputstream BAOs = new Bytearrayoutputstream ();
- Bm.compress (Bitmap.CompressFormat.JPEG, BAOs);
- byte[] B = Baos.tobytearray ();
- return base64.encodetostring (b, Base64.default);
- }
To view all source code, please visit:
Https://github.com/feicien/StudyDemo/tree/master/FileUploadDemo
Compression principle explained: Compress a picture. We need to know the original size of this image and then compress it according to the compression ratio we set.
So there are 3 things we need to do:
1. Get the length and width of the original image
[Java]View Plaincopy
- Bitmapfactory.options Options = new Bitmapfactory.options ();
- Options.injustdecodebounds = true;
- Bitmapfactory.decodefile (FilePath, Options);
- int height = options.outheight;
- int width = options.outwidth;
The above code is to decode the image, Injustdecodebounds set to True, you can not read the picture into memory, but still can calculate the size of the picture, which just can meet the needs of our first step.
2. Calculate the compression ratio
[Java]View Plaincopy
- int height = options.outheight;
- int width = options.outwidth;
- int insamplesize = 1;
- int reqheight=800;
- int reqwidth=480;
- if (height > Reqheight | | width > reqwidth) {
- final int heightratio = Math.Round ((float) height/(float) reqheight);
- final int widthRatio = Math.Round ((float) width/(float) reqwidth);
- Insamplesize = HeightRatio < WidthRatio? Heightratio:widthratio;
- }
The resolution of the general phone is 480*800, so we compress the image expected broadband is set to 480, the height is set to 800, these 2 values are only the desired width and height, in fact, the actual width of compression will be higher than expected. If the original height of the image or bandwidth is about the bandwidth and height we expect, we need to calculate the scale value. Otherwise, it is not scaled. HeightRatio is a multiple of the original height of the image and the height after compression, WidthRatio is a multiple of the original width of the picture and the compressed width. Insamplesize is the smallest of heightratio and WidthRatio, and insamplesize is the scale value. A insamplesize of 1 means that the width and height are not scaled, and 2 means the compressed width and height are the original 1/2
3. Zoom and compress the picture
[Java]View Plaincopy
- Creates a bitmap object in memory that is created by scaling small
- Options.insamplesize = calculateinsamplesize (options, 480, 800);
- Options.injustdecodebounds = false;
- Bitmap bitmap= bitmapfactory.decodefile (FilePath, Options);
- Bytearrayoutputstream BAOs = new Bytearrayoutputstream ();
- Bm.compress (Bitmap.CompressFormat.JPEG, BAOs);
- byte[] B = Baos.tobytearray ();
The first 3 lines of code have actually got a scaled bitmap object, and if you display the picture in the app, you can use the bitmap object. Due to the problem of network traffic. We need to sacrifice the quality of the picture in exchange for a portion of space, here call Bm.compress () method to compress, the second parameter of this method, if it is 100, is not compressed, I set here is 60, you can also more you need to set, in the course of the experiment I set to 30, Pictures are not distorted.
Compression Effect: This demo can compress about 1.5M picture to about 100K, and no distortion.
As follows:
Update:
[Java]View Plaincopy
- /*
- Compress pictures, handle some mobile phone camera angle rotation problem
- */
- Public static String compressimage (Context context,string filepath,string fileName,int q) throws FileNotFoundException {
- Bitmap BM = Getsmallbitmap (FilePath);
- int degree = Readpicturedegree (FilePath);
- if (degree!=0) {//rotate photo angle
- Bm=rotatebitmap (Bm,degree);
- }
- File Imagedir = sdcardutils.getimagedir (context);
- File outputfile=new file (Imagedir,filename);
- FileOutputStream out = new FileOutputStream (OutputFile);
- Bm.compress (Bitmap.CompressFormat.JPEG, q, Out);
- return Outputfile.getpath ();
- }
Judging the photo angle
[Java]View Plaincopy
- Public static int readpicturedegree (String path) {
- int degree = 0;
- try {
- Exifinterface exifinterface = new Exifinterface (path);
- int orientation = Exifinterface.getattributeint (
- Exifinterface.tag_orientation,
- Exifinterface.orientation_normal);
- switch (orientation) {
- Case exifinterface.orientation_rotate_90:
- degree = 90;
- Break ;
- Case exifinterface.orientation_rotate_180:
- degree = 180;
- Break ;
- Case exifinterface.orientation_rotate_270:
- degree = 270;
- Break ;
- }
- } catch (IOException e) {
- E.printstacktrace ();
- }
- return degree;
- }
Rotate photos
[Java]View Plaincopy
- Public static Bitmap Rotatebitmap (Bitmap Bitmap,int degress) {
- if (bitmap! = null) {
- Matrix M = new Matrix ();
- M.postrotate (degress);
- Bitmap = Bitmap.createbitmap (bitmap, 0, 0, Bitmap.getwidth (),
- Bitmap.getheight (), M, true);
- return bitmap;
- }
- return bitmap;
- }
An efficient way for Android to compress images below 100K and remain undistorted