Android Picture Compression (Quality Compression and Size Compression) &Bitmap Converts to String Upload

Keywords: Android Java Mobile encoding

Android Picture Compression (Quality Compression and Size Compression) & Bitmap Converted to String Upload

2015-03-12 22:38 53 665 people read comment(34) Collection Report
This article has been included in:
Classification:
Android Image Processing (30) Android Development (1100)
After investigating the methods of image compression on the Internet and implementing them, it can be generally considered that there are two kinds of compression: quality compression (without changing the size of the picture) and size compression (equivalent to the compression on on the pixel); quality compression can generally be used for the processing before uploading the big picture, so as to save a certain amount of traffic, after all, the current mobile phone photos can reach about 3M, size compression. Generally, it can be used to generate thumbnails.
Both methods are actually installed in my project, but it turns out that in the quality compression module, the original 1.9M image compression has turned into more than 3M, which is very strange. Further investigation has been done and the reason is finally known. The following blog is more clear:

Summary of android Picture Compression

To sum up, there are three forms of picture: file on hard disk, stream on network, stream in memory or bitmap. The so-called quality compression can only affect file. You can convert a file into a bitmap and then into a file, or directly convert a bitmap into a file. The final file is compressed, but the bitmap in the middle does not exist. There is compression (or almost no compression, I'm not sure), because the size of bigmap in memory is calculated by pixels, that is, width. * height, for quality compression, does not change the pixels of the image, so even if the quality is compressed, bitmap's share of memory is still not reduced, but when you make a file, it does become smaller.

Dimension compression reduces the pixels of the image, so it directly affects the bitmap, of course, the final file is relatively smaller.

Finally, post the tool classes summarized by yourself:
  1. import java.io.ByteArrayInputStream;  
  2. import java.io.ByteArrayOutputStream;  
  3. import java.io.File;  
  4. import java.io.FileNotFoundException;  
  5. import java.io.FileOutputStream;  
  6. import java.io.IOException;  
  7.   
  8. import android.graphics.Bitmap;  
  9. import android.graphics.Bitmap.Config;  
  10. import android.graphics.BitmapFactory;  
  11.   
  12. /** 
  13.  * Image compress factory class 
  14.  *  
  15.  * @author  
  16.  * 
  17.  */  
  18. public class ImageFactory {  
  19.   
  20.     /** 
  21.      * Get bitmap from specified image path 
  22.      *  
  23.      * @param imgPath 
  24.      * @return 
  25.      */  
  26.     public Bitmap getBitmap(String imgPath) {  
  27.         // Get bitmap through image path  
  28.         BitmapFactory.Options newOpts = new BitmapFactory.Options();  
  29.         newOpts.inJustDecodeBounds = false;  
  30.         newOpts.inPurgeable = true;  
  31.         newOpts.inInputShareable = true;  
  32.         // Do not compress  
  33.         newOpts.inSampleSize = 1;  
  34.         newOpts.inPreferredConfig = Config.RGB_565;  
  35.         return BitmapFactory.decodeFile(imgPath, newOpts);  
  36.     }  
  37.       
  38.     /** 
  39.      * Store bitmap into specified image path 
  40.      *  
  41.      * @param bitmap 
  42.      * @param outPath 
  43.      * @throws FileNotFoundException  
  44.      */  
  45.     public void storeImage(Bitmap bitmap, String outPath) throws FileNotFoundException {  
  46.         FileOutputStream os = new FileOutputStream(outPath);  
  47.         bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);  
  48.     }  
  49.       
  50.     /** 
  51.      * Compress image by pixel, this will modify image width/height.  
  52.      * Used to get thumbnail 
  53.      *  
  54.      * @param imgPath image path 
  55.      * @param pixelW target pixel of width 
  56.      * @param pixelH target pixel of height 
  57.      * @return 
  58.      */  
  59.     public Bitmap ratio(String imgPath, float pixelW, float pixelH) {  
  60.         BitmapFactory.Options newOpts = new BitmapFactory.Options();    
  61. // Start reading in the picture, then set options.inJustDecodeBounds back to true, that is, read-only without reading the content. ___________
  62.         newOpts.inJustDecodeBounds = true;  
  63.         newOpts.inPreferredConfig = Config.RGB_565;  
  64.         // Get bitmap info, but notice that bitmap is null now    
  65.         Bitmap bitmap = BitmapFactory.decodeFile(imgPath,newOpts);  
  66.             
  67.         newOpts.inJustDecodeBounds = false;    
  68.         int w = newOpts.outWidth;    
  69.         int h = newOpts.outHeight;    
  70. // Target size you want to zoom in
  71. float hh = pixelH; / / / Setting the height to 240f, you can clearly see that the image is reduced.
  72. float ww = pixelW; / / / Set the width to 120f, and you can see that the picture is reduced significantly.
  73. // Scale-up ratio. Because it is a fixed scale, only one of the high or wide data can be used to calculate.
  74. int be = 1; / be = 1 means no zooming.
  75. if (w > h & & W > W w) {// if the width is large, scale according to the width.
  76.             be = (int) (newOpts.outWidth / ww);    
  77. } Otherwise (w < H & H > H h) {// Scale according to width if height is high.
  78.             be = (int) (newOpts.outHeight / hh);    
  79.         }    
  80.         if (be <= 0) be = 1;    
  81. newOpts.inSampleSize = be; // Set zoom ratio.
  82. // Start compressing the image. Note that options.inJustDecodeBounds has been set back to false at this time.
  83.         bitmap = BitmapFactory.decodeFile(imgPath, newOpts);  
  84. // After compressing the scale, the mass compression is carried out.
  85. // return compress(bitmap, maxSize); // There is little significance of quality compression here, but it consumes resources and deletes.
  86.         return bitmap;  
  87.     }  
  88.       
  89.     /** 
  90.      * Compress image by size, this will modify image width/height.  
  91.      * Used to get thumbnail 
  92.      *  
  93.      * @param image 
  94.      * @param pixelW target pixel of width 
  95.      * @param pixelH target pixel of height 
  96.      * @return 
  97.      */  
  98.     public Bitmap ratio(Bitmap image, float pixelW, float pixelH) {  
  99.         ByteArrayOutputStream os = new ByteArrayOutputStream();  
  100.         image.compress(Bitmap.CompressFormat.JPEG, 100, os);  
  101. If (os.toByteArray().length / 1024 > 1024) {// Judge if the picture is larger than 1M, compress to avoid overflow when generating the picture (BitmapFactory.decodeStream)
  102. os.reset(); // Reset baos is to empty baos.
  103. image.compress(Bitmap.CompressFormat.JPEG, 50, os); //Here compress 50%, store the compressed data in baos.
  104.         }    
  105.         ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray());    
  106.         BitmapFactory.Options newOpts = new BitmapFactory.Options();    
  107. // Start reading in the picture and set options.inJustDecodeBounds back to true.
  108.         newOpts.inJustDecodeBounds = true;  
  109.         newOpts.inPreferredConfig = Config.RGB_565;  
  110.         Bitmap bitmap = BitmapFactory.decodeStream(is, null, newOpts);    
  111.         newOpts.inJustDecodeBounds = false;    
  112.         int w = newOpts.outWidth;    
  113.         int h = newOpts.outHeight;    
  114. float hh = pixelH; / / / Setting the height to 240f, you can clearly see that the image is reduced.
  115. float ww = pixelW; / / / Set the width to 120f, and you can see that the picture is reduced significantly.
  116. // Scale-up ratio. Because it is a fixed scale, only one of the high or wide data can be used to calculate.
  117. int be = 1; / be = 1 means no zooming.
  118. if (w > h & & W > W w) {// if the width is large, scale according to the width.
  119.             be = (int) (newOpts.outWidth / ww);    
  120. } Otherwise (w < H & H > H h) {// Scale according to width if height is high.
  121.             be = (int) (newOpts.outHeight / hh);    
  122.         }    
  123.         if (be <= 0) be = 1;    
  124. newOpts.inSampleSize = be; // Set Scale Ratio
  125. // Reread the picture and note that options.inJustDecodeBounds has been set back to false at this time.
  126.         is = new ByteArrayInputStream(os.toByteArray());    
  127.         bitmap = BitmapFactory.decodeStream(is, null, newOpts);  
  128. // After compressing the scale, the mass compression is carried out.
  129. // return compress(bitmap, maxSize); // There is little significance of quality compression here, but it consumes resources and deletes.
  130.         return bitmap;  
  131.     }  
  132.       
  133.     /** 
  134.      * Compress by quality,  and generate image to the path specified 
  135.      *  
  136.      * @param image 
  137.      * @param outPath 
  138.      * @param maxSize target will be compressed to be smaller than this size.(kb) 
  139.      * @throws IOException  
  140.      */  
  141.     public void compressAndGenImage(Bitmap image, String outPath, int maxSize) throws IOException {  
  142.         ByteArrayOutputStream os = new ByteArrayOutputStream();  
  143.         // scale  
  144.         int options = 100;  
  145.         // Store the bitmap into output stream(no compress)  
  146.         image.compress(Bitmap.CompressFormat.JPEG, options, os);    
  147.         // Compress by loop  
  148.         while ( os.toByteArray().length / 1024 > maxSize) {  
  149.             // Clean up os  
  150.             os.reset();  
  151.             // interval 10  
  152.             options -= 10;  
  153.             image.compress(Bitmap.CompressFormat.JPEG, options, os);  
  154.         }  
  155.           
  156.         // Generate compressed image file  
  157.         FileOutputStream fos = new FileOutputStream(outPath);    
  158.         fos.write(os.toByteArray());    
  159.         fos.flush();    
  160.         fos.close();    
  161.     }  
  162.       
  163.     /** 
  164.      * Compress by quality,  and generate image to the path specified 
  165.      *  
  166.      * @param imgPath 
  167.      * @param outPath 
  168.      * @param maxSize target will be compressed to be smaller than this size.(kb) 
  169.      * @param needsDelete Whether delete original file after compress 
  170.      * @throws IOException  
  171.      */  
  172.     public void compressAndGenImage(String imgPath, String outPath, int maxSize, boolean needsDelete) throws IOException {  
  173.         compressAndGenImage(getBitmap(imgPath), outPath, maxSize);  
  174.           
  175.         // Delete original file  
  176.         if (needsDelete) {  
  177.             File file = new File (imgPath);  
  178.             if (file.exists()) {  
  179.                 file.delete();  
  180.             }  
  181.         }  
  182.     }  
  183.       
  184.     /** 
  185.      * Ratio and generate thumb to the path specified 
  186.      *  
  187.      * @param image 
  188.      * @param outPath 
  189.      * @param pixelW target pixel of width 
  190.      * @param pixelH target pixel of height 
  191.      * @throws FileNotFoundException 
  192.      */  
  193.     public void ratioAndGenThumb(Bitmap image, String outPath, float pixelW, float pixelH) throws FileNotFoundException {  
  194.         Bitmap bitmap = ratio(image, pixelW, pixelH);  
  195.         storeImage( bitmap, outPath);  
  196.     }  
  197.       
  198.     /** 
  199.      * Ratio and generate thumb to the path specified 
  200.      *  
  201.      * @param image 
  202.      * @param outPath 
  203.      * @param pixelW target pixel of width 
  204.      * @param pixelH target pixel of height 
  205.      * @param needsDelete Whether delete original file after compress 
  206.      * @throws FileNotFoundException 
  207.      */  
  208.     public void ratioAndGenThumb(String imgPath, String outPath, float pixelW, float pixelH, boolean needsDelete) throws FileNotFoundException {  
  209.         Bitmap bitmap = ratio(imgPath, pixelW, pixelH);  
  210.         storeImage( bitmap, outPath);  
  211.           
  212.         // Delete original file  
  213.                 if (needsDelete) {  
  214.                     File file = new File (imgPath);  
  215.                     if (file.exists()) {  
  216.                         file.delete();  
  217.                     }  
  218.                 }  
  219.     }  
  220.       
  221. }  
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;

/**
 * Image compress factory class
 * 
 * @author 
 *
 */
public class ImageFactory {

	/**
	 * Get bitmap from specified image path
	 * 
	 * @param imgPath
	 * @return
	 */
	public Bitmap getBitmap(String imgPath) {
		// Get bitmap through image path
		BitmapFactory.Options newOpts = new BitmapFactory.Options();
		newOpts.inJustDecodeBounds = false;
		newOpts.inPurgeable = true;
		newOpts.inInputShareable = true;
		// Do not compress
		newOpts.inSampleSize = 1;
		newOpts.inPreferredConfig = Config.RGB_565;
		return BitmapFactory.decodeFile(imgPath, newOpts);
	}
	
	/**
	 * Store bitmap into specified image path
	 * 
	 * @param bitmap
	 * @param outPath
	 * @throws FileNotFoundException 
	 */
	public void storeImage(Bitmap bitmap, String outPath) throws FileNotFoundException {
		FileOutputStream os = new FileOutputStream(outPath);
		bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);
	}
	
	/**
	 * Compress image by pixel, this will modify image width/height. 
	 * Used to get thumbnail
	 * 
	 * @param imgPath image path
	 * @param pixelW target pixel of width
	 * @param pixelH target pixel of height
	 * @return
	 */
	public Bitmap ratio(String imgPath, float pixelW, float pixelH) {
		BitmapFactory.Options newOpts = new BitmapFactory.Options();  
        // Start reading in the picture, and set options.inJustDecodeBounds back to true, that is, read-only without reading content.
        newOpts.inJustDecodeBounds = true;
        newOpts.inPreferredConfig = Config.RGB_565;
        // Get bitmap info, but notice that bitmap is null now  
        Bitmap bitmap = BitmapFactory.decodeFile(imgPath,newOpts);
          
        newOpts.inJustDecodeBounds = false;  
        int w = newOpts.outWidth;  
        int h = newOpts.outHeight;  
        // Target size to be scaled
        float hh = pixelH;// When you set the height to 240f, you can clearly see that the image has been reduced.
	    float ww = pixelW;// Set the width to 120f, and you can see that the picture is reduced.
        // Zoom ratio. Because of the fixed scale, only one of the high or wide data can be used to calculate.  
        int be = 1;//be=1 means no zooming  
        if (w > h && w > ww) {//If the width is large, the size is fixed according to the width.  
            be = (int) (newOpts.outWidth / ww);  
        } else if (w < h && h > hh) {//If the height is high, the size is fixed according to the width.  
            be = (int) (newOpts.outHeight / hh);  
        }  
        if (be <= 0) be = 1;  
        newOpts.inSampleSize = be;//Set zoom ratio
        // Start compressing the image. Note that options.inJustDecodeBounds has been set back to false at this time.
        bitmap = BitmapFactory.decodeFile(imgPath, newOpts);
        // Compression of the scale before mass compression
//        return compress(bitmap, maxSize); // There is little point in compressing quality again here, but it consumes resources and deletes them.
        return bitmap;
	}
	
	/**
	 * Compress image by size, this will modify image width/height. 
	 * Used to get thumbnail
	 * 
	 * @param image
	 * @param pixelW target pixel of width
	 * @param pixelH target pixel of height
	 * @return
	 */
	public Bitmap ratio(Bitmap image, float pixelW, float pixelH) {
		ByteArrayOutputStream os = new ByteArrayOutputStream();
	    image.compress(Bitmap.CompressFormat.JPEG, 100, os);
	    if( os.toByteArray().length / 1024>1024) {//Judge that if the image is larger than 1M, compress to avoid overflow when generating the image (BitmapFactory.decodeStream)    
	        os.reset();//Resetting baos means emptying baos  
	        image.compress(Bitmap.CompressFormat.JPEG, 50, os);//Here, compress 50% and store the compressed data in baos  
	    }  
	    ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray());  
	    BitmapFactory.Options newOpts = new BitmapFactory.Options();  
	    //Start reading in the picture, and set options.inJustDecodeBounds back to true  
	    newOpts.inJustDecodeBounds = true;
	    newOpts.inPreferredConfig = Config.RGB_565;
	    Bitmap bitmap = BitmapFactory.decodeStream(is, null, newOpts);  
	    newOpts.inJustDecodeBounds = false;  
	    int w = newOpts.outWidth;  
	    int h = newOpts.outHeight;  
	    float hh = pixelH;// When you set the height to 240f, you can clearly see that the image has been reduced.
	    float ww = pixelW;// Set the width to 120f, and you can see that the picture is reduced.
	    //Zoom ratio. Because of the fixed scale, only one of the high or wide data can be used to calculate.  
	    int be = 1;//be=1 means no zooming  
	    if (w > h && w > ww) {//If the width is large, the size is fixed according to the width.  
	        be = (int) (newOpts.outWidth / ww);  
	    } else if (w < h && h > hh) {//If the height is high, the size is fixed according to the width.  
	        be = (int) (newOpts.outHeight / hh);  
	    }  
	    if (be <= 0) be = 1;  
	    newOpts.inSampleSize = be;//Set zoom ratio  
	    //Reread the picture and notice that options.inJustDecodeBounds has been set back to false at this time.  
	    is = new ByteArrayInputStream(os.toByteArray());  
	    bitmap = BitmapFactory.decodeStream(is, null, newOpts);
	    //Compression of the scale before mass compression
//	    return compress(bitmap, maxSize); // There is little point in compressing quality again here, but it consumes resources and deletes them.
	    return bitmap;
	}
	
	/**
	 * Compress by quality,  and generate image to the path specified
	 * 
	 * @param image
	 * @param outPath
	 * @param maxSize target will be compressed to be smaller than this size.(kb)
	 * @throws IOException 
	 */
	public void compressAndGenImage(Bitmap image, String outPath, int maxSize) throws IOException {
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		// scale
		int options = 100;
		// Store the bitmap into output stream(no compress)
        image.compress(Bitmap.CompressFormat.JPEG, options, os);  
        // Compress by loop
        while ( os.toByteArray().length / 1024 > maxSize) {
            // Clean up os
        	os.reset();
        	// interval 10
            options -= 10;
            image.compress(Bitmap.CompressFormat.JPEG, options, os);
        }
        
        // Generate compressed image file
        FileOutputStream fos = new FileOutputStream(outPath);  
        fos.write(os.toByteArray());  
        fos.flush();  
        fos.close();  
	}
	
	/**
	 * Compress by quality,  and generate image to the path specified
	 * 
	 * @param imgPath
	 * @param outPath
	 * @param maxSize target will be compressed to be smaller than this size.(kb)
	 * @param needsDelete Whether delete original file after compress
	 * @throws IOException 
	 */
	public void compressAndGenImage(String imgPath, String outPath, int maxSize, boolean needsDelete) throws IOException {
		compressAndGenImage(getBitmap(imgPath), outPath, maxSize);
		
		// Delete original file
		if (needsDelete) {
			File file = new File (imgPath);
			if (file.exists()) {
				file.delete();
			}
		}
	}
	
	/**
	 * Ratio and generate thumb to the path specified
	 * 
	 * @param image
	 * @param outPath
	 * @param pixelW target pixel of width
	 * @param pixelH target pixel of height
	 * @throws FileNotFoundException
	 */
	public void ratioAndGenThumb(Bitmap image, String outPath, float pixelW, float pixelH) throws FileNotFoundException {
		Bitmap bitmap = ratio(image, pixelW, pixelH);
		storeImage( bitmap, outPath);
	}
	
	/**
	 * Ratio and generate thumb to the path specified
	 * 
	 * @param image
	 * @param outPath
	 * @param pixelW target pixel of width
	 * @param pixelH target pixel of height
	 * @param needsDelete Whether delete original file after compress
	 * @throws FileNotFoundException
	 */
	public void ratioAndGenThumb(String imgPath, String outPath, float pixelW, float pixelH, boolean needsDelete) throws FileNotFoundException {
		Bitmap bitmap = ratio(imgPath, pixelW, pixelH);
		storeImage( bitmap, outPath);
		
		// Delete original file
				if (needsDelete) {
					File file = new File (imgPath);
					if (file.exists()) {
						file.delete();
					}
				}
	}
	
}


If the above tool class does not satisfy you, look at the following methods.

I. Picture Quality Compression
  1. /** 
  2. * Quality Compression Method
  3.  * 
  4.  * @param image 
  5.  * @return 
  6.  */  
  7. public static Bitmap compressImage(Bitmap image) {  
  8.   
  9.     ByteArrayOutputStream baos = new ByteArrayOutputStream();  
  10. image.compress(Bitmap.CompressFormat.JPEG, 100, baos); // quality compression method, where 100 means uncompressed, storing compressed data in baos
  11.     int options = 90;  
  12.   
  13. while (baos. toByteArray (). len gt h / 1024 > 100) {// Cycle judges if the compressed image is greater than 100kb, greater than the continued compression.
  14. baos.reset(); // Reset baos to clear baos
  15. image.compress(Bitmap.CompressFormat.JPEG, options, baos); // Here compress options, and store the compressed data in baos.
  16. options - = 10; // Decrease by 10 each time.
  17.     }  
  18. ByteArray InputStream isBm = new ByteArray InputStream (baos. to ByteArray ()); // Store the compressed data baos in ByteArray InputStream.
  19. Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null); // Generate pictures from ByteArray InputStream data
  20.     return bitmap;  
  21. }  
    /**
     * Mass Compression Method
     *
     * @param image
     * @return
     */
    public static Bitmap compressImage(Bitmap image) {

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);// The quality compression method, where 100 means uncompressed, stores the compressed data in baos
        int options = 90;

        while (baos.toByteArray().length / 1024 > 100) { // Cyclic judgment if the compressed image is greater than 100kb, greater than the continued compression
            baos.reset(); // Resetting baos means emptying baos
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);// Here compress options and store compressed data in baos
            options -= 10;// Decrease by 10 per time
        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// Store the compressed data baos in ByteArray Input Stream
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);// Generate pictures from ByteArray Input Stream data
        return bitmap;
    }

2. Compression by Scale (Path Acquisition Pictures)

  1. /** 
  2. * Picture Scale Compression Method
  3.  * 
  4. *@ param srcPath
  5.  * @return 
  6.  */  
  7. public static Bitmap getimage(String srcPath) {  
  8.   
  9.     BitmapFactory.Options newOpts = new BitmapFactory.Options();  
  10. // Start reading in the picture and set options.inJustDecodeBounds back to true.
  11.     newOpts.inJustDecodeBounds = true;  
  12. Bitmap bitmap = BitmapFactory.decodeFile(srcPath, new Opts); // At this time, the return bm is empty.
  13.   
  14.     newOpts.inJustDecodeBounds = false;  
  15.     int w = newOpts.outWidth;  
  16.     int h = newOpts.outHeight;  
  17. // At present, most of the mainstream mobile phones have 800*480 resolution, so we set the height and width as follows:
  18. float hh = 800f; // Set height to 800f here
  19. float ww = 480f; // Set the width here to 480f
  20. // Scale-up ratio. Because it is a fixed scale, only one of the data with high or wide can be calculated.
  21. int be=1; // be=1 means no zooming.
  22. if (w > h & & W > W w) {// if the width is large, scale according to the width.
  23.         be = (int) (newOpts.outWidth / ww);  
  24. } if (w < H & & H > H h) {// if the height is high, scale according to the width.
  25.         be = (int) (newOpts.outHeight / hh);  
  26.     }  
  27.     if (be <= 0)  
  28.         be = 1;  
  29. newOpts.inSampleSize = be; // Set zoom ratio.
  30. // Re-read the picture and note that options.inJustDecodeBounds has been set back to false at this time.
  31.     bitmap = BitmapFactory.decodeFile(srcPath, newOpts);  
  32. return compress Image (bitmap); // Compress the scale before compressing the quality.
  33. }  
    /**
     * Picture Scale Compression Method
     *
     * @param srcPath (Get pictures from paths and compress them)
     * @return
     */
    public static Bitmap getimage(String srcPath) {

        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        // Start reading in the picture, and set options.inJustDecodeBounds back to true
        newOpts.inJustDecodeBounds = true;
        Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOpts);// At this point the return bm is empty

        newOpts.inJustDecodeBounds = false;
        int w = newOpts.outWidth;
        int h = newOpts.outHeight;
        // At present, most of the mainstream mobile phones have 800*480 resolution, so we set the width and height to be 800*480 resolution.
        float hh = 800f;// Set the height here to 800f
        float ww = 480f;// The width is set to 480f.
        // Zoom ratio. Because of the fixed scale, only one of the high or wide data can be used to calculate.
        int be = 1;// be=1 means no zooming
        if (w > h && w > ww) {// If the width is large, the size is fixed according to the width.
            be = (int) (newOpts.outWidth / ww);
        } else if (w < h && h > hh) {// If the height is high, the size is fixed according to the width.
            be = (int) (newOpts.outHeight / hh);
        }
        if (be <= 0)
            be = 1;
        newOpts.inSampleSize = be;// Set zoom ratio
        // Reread the picture and notice that options.inJustDecodeBounds has been set back to false at this time.
        bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
        return compressImage(bitmap);// Compression of the scale before mass compression
    }
3. Bitmap

  1. /** 
  2. * Picture Scale Compression Method
  3.  * 
  4. *@ param image (compressed according to Bitmap picture)
  5.  * @return 
  6.  */  
  7. public static Bitmap compressScale(Bitmap image) {  
  8.   
  9.     ByteArrayOutputStream baos = new ByteArrayOutputStream();  
  10.     image.compress(Bitmap.CompressFormat.JPEG, 100, baos);  
  11.   
  12. // Judge that if the image is larger than 1M, compress to avoid overflow when generating the image (BitmapFactory.decodeStream)
  13.     if (baos.toByteArray().length / 1024 > 1024) {  
  14. baos.reset(); // Reset baos to empty baos
  15. image.compress(Bitmap.CompressFormat.JPEG, 80, baos); // Here compress 50%, store the compressed data in baos.
  16.     }  
  17.     ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());  
  18.     BitmapFactory.Options newOpts = new BitmapFactory.Options();  
  19. // Start reading in the picture and set options.inJustDecodeBounds back to true.
  20.     newOpts.inJustDecodeBounds = true;  
  21.     Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);  
  22.     newOpts.inJustDecodeBounds = false;  
  23.     int w = newOpts.outWidth;  
  24.     int h = newOpts.outHeight;  
  25.     Log.i(TAG, w + "---------------" + h);  
  26. // At present, most of the mainstream mobile phones have 800*480 resolution, so we set the height and width as follows:
  27. // float hh = 800f; // Set height to 800f here
  28. // float ww = 480f; // Set the width here to 480f
  29.     float hh = 512f;  
  30.     float ww = 512f;  
  31. // Scale-up ratio. Because it is a fixed scale, only one of the data with high or wide can be calculated.
  32. int be=1; // be=1 means no zooming.
  33. if (w > h & & W > W w) {// if the width is large, scale according to the width.
  34.         be = (int) (newOpts.outWidth / ww);  
  35. } if (w < H & H > H h) {// / if the height is high, scale according to the height.
  36.         be = (int) (newOpts.outHeight / hh);  
  37.     }  
  38.     if (be <= 0)  
  39.         be = 1;  
  40. newOpts.inSampleSize = be; // Set zoom ratio
  41. // NewOpts.in Preferred Config = Config.RGB_565; // Reduce images from ARGB888 to RGB565
  42.   
  43. // Re-read the picture and note that options.inJustDecodeBounds has been set back to false at this time.
  44.     isBm = new ByteArrayInputStream(baos.toByteArray());  
  45.     bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);  
  46.   
  47. return compress Image (bitmap); // Compress the scale before compressing the quality.
  48.   
  49.     //return bitmap;  
  50. }  
    /**
     * Picture Scale Compression Method
     *
     * @param image (Compression according to Bitmap pictures)
     * @return
     */
    public static Bitmap compressScale(Bitmap image) {

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);

        // Judge that if the image is larger than 1M, compress to avoid overflow when generating the image (BitmapFactory.decodeStream)
        if (baos.toByteArray().length / 1024 > 1024) {
            baos.reset();// Resetting baos means emptying baos
            image.compress(Bitmap.CompressFormat.JPEG, 80, baos);// Here, compress 50% and store the compressed data in baos
        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        // Start reading in the picture, and set options.inJustDecodeBounds back to true
        newOpts.inJustDecodeBounds = true;
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
        newOpts.inJustDecodeBounds = false;
        int w = newOpts.outWidth;
        int h = newOpts.outHeight;
        Log.i(TAG, w + "---------------" + h);
        // At present, most of the mainstream mobile phones have 800*480 resolution, so we set the width and height to be 800*480 resolution.
        // float hh = 800f; // Set the height here to 800f
        // float ww = 480f; // Set the width here to 480f
        float hh = 512f;
        float ww = 512f;
        // Zoom ratio. Because of the fixed scale, only one of the high or wide data can be used to calculate.
        int be = 1;// be=1 means no zooming
        if (w > h && w > ww) {// If the width is large, the size is fixed according to the width.
            be = (int) (newOpts.outWidth / ww);
        } else if (w < h && h > hh) { // If the height is high, scale according to the height.
            be = (int) (newOpts.outHeight / hh);
        }
        if (be <= 0)
            be = 1;
        newOpts.inSampleSize = be; // Set zoom ratio
        // NewOpts.in Preferred Config = Config.RGB_565; // Reduce images from ARGB888 to RGB565

        // Reread the picture and notice that options.inJustDecodeBounds has been set back to false at this time.
        isBm = new ByteArrayInputStream(baos.toByteArray());
        bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);

        return compressImage(bitmap);// Compression of the scale before mass compression

        //return bitmap;
    }





--------------------------------------------------------------------------------------------------------------------------------

Share a compressed image size:

  1. public static void compressPicture(String srcPath, String desPath) {  
  2.         FileOutputStream fos = null;  
  3.         BitmapFactory.Options op = new BitmapFactory.Options();  
  4.   
  5. // Start reading in the picture and set options.inJustDecodeBounds back to true.
  6.         op.inJustDecodeBounds = true;  
  7.         Bitmap bitmap = BitmapFactory.decodeFile(srcPath, op);  
  8.         op.inJustDecodeBounds = false;  
  9.   
  10. // Dimensions of zoomed pictures
  11.         float w = op.outWidth;  
  12.         float h = op.outHeight;  
  13.         float hh = 1024f;//  
  14.         float ww = 1024f;//  
  15. // Maximum width or height 1024
  16.         float be = 1.0f;  
  17.         if (w > h && w > ww) {  
  18.             be = (float) (w / ww);  
  19.         } else if (w < h && h > hh) {  
  20.             be = (float) (h / hh);  
  21.         }  
  22.         if (be <= 0) {  
  23.             be = 1.0f;  
  24.         }  
  25. op.inSampleSize = (int) be; // Set the zoom ratio, the larger the number, the smaller the size of the picture.
  26. // Re-read the picture and note that options.inJustDecodeBounds has been set back to false at this time.
  27.         bitmap = BitmapFactory.decodeFile(srcPath, op);  
  28.         int desWidth = (int) (w / be);  
  29.         int desHeight = (int) (h / be);  
  30.         bitmap = Bitmap.createScaledBitmap(bitmap, desWidth, desHeight, true);  
  31.         try {  
  32.             fos = new FileOutputStream(desPath);  
  33.             if (bitmap != null) {  
  34.                 bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);  
  35.             }  
  36.         } catch (FileNotFoundException e) {  
  37.             e.printStackTrace();  
  38.         }  
  39.     }  
public static void compressPicture(String srcPath, String desPath) {
		FileOutputStream fos = null;
		BitmapFactory.Options op = new BitmapFactory.Options();

		// Start reading in the picture, and set options.inJustDecodeBounds back to true
		op.inJustDecodeBounds = true;
		Bitmap bitmap = BitmapFactory.decodeFile(srcPath, op);
		op.inJustDecodeBounds = false;

		// Dimensions of Scaled Pictures
		float w = op.outWidth;
		float h = op.outHeight;
		float hh = 1024f;//
		float ww = 1024f;//
		// Maximum width or height 1024
		float be = 1.0f;
		if (w > h && w > ww) {
			be = (float) (w / ww);
		} else if (w < h && h > hh) {
			be = (float) (h / hh);
		}
		if (be <= 0) {
			be = 1.0f;
		}
		op.inSampleSize = (int) be;// Set the zoom ratio, the bigger the number, the smaller the size of the picture.
		// Reread the picture and notice that options.inJustDecodeBounds has been set back to false at this time.
		bitmap = BitmapFactory.decodeFile(srcPath, op);
		int desWidth = (int) (w / be);
		int desHeight = (int) (h / be);
		bitmap = Bitmap.createScaledBitmap(bitmap, desWidth, desHeight, true);
		try {
			fos = new FileOutputStream(desPath);
			if (bitmap != null) {
				bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}


Two issues need to be addressed:

1. Measure before calling getDrawingCache(), otherwise the bitmap is null, which I have tried in OnCreate(), OnStart(), OnResume().


2. When calling bitmap.compress(CompressFormat.JPEG, 100, fos), when saved as a picture, it is found that the background of the picture is black, as follows:


Just change to png, bitmap.compress(CompressFormat.PNG, 100, fos); as follows:



In practical development, sometimes we need to convert files into strings and upload them as parameters.

bitmap to String and String to bitmap

  1. import android.graphics.Bitmap;  
  2. import android.graphics.BitmapFactory;  
  3. import android.util.Base64;  
  4.   
  5. import java.io.ByteArrayOutputStream;  
  6.   
  7. /** 
  8.  *  
  9.  *  
  10. * Function description: Picture bitmap, a common tool for Android development, is converted to string and String strings to bitmap image format.
  11.  */  
  12. public class BitmapAndStringUtils {  
  13.     /** 
  14. * Picture to string
  15.      * 
  16.      * @param bitmap 
  17.      * @return 
  18.      */  
  19.     public static String convertIconToString(Bitmap bitmap)  
  20.     {  
  21.         ByteArrayOutputStream baos = new ByteArrayOutputStream();// outputstream  
  22.         bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);  
  23. Byte [] appicon = baos.toByteArray(); // to byte array
  24.         return Base64.encodeToString(appicon, Base64.DEFAULT);  
  25.   
  26.     }  
  27.   
  28.     /** 
  29. * string to bitmap
  30.      * 
  31.      * @param st 
  32.      */  
  33.     public static Bitmap convertStringToIcon(String st)  
  34.     {  
  35.         // OutputStream out;  
  36.         Bitmap bitmap = null;  
  37.         try  
  38.         {  
  39.             // out = new FileOutputStream("/sdcard/aa.jpg");  
  40.             byte[] bitmapArray;  
  41.             bitmapArray = Base64.decode(st, Base64.DEFAULT);  
  42.             bitmap =  
  43.                     BitmapFactory.decodeByteArray(bitmapArray, 0,  
  44.                             bitmapArray.length);  
  45.             // bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);  
  46.             return bitmap;  
  47.         }  
  48.         catch (Exception e)  
  49.         {  
  50.             return null;  
  51.         }  
  52.     }  
  53. }  
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Base64;

import java.io.ByteArrayOutputStream;

/**
 * 
 * 
 * Function Description: Android development of common tools such as bitmap to string and String string to bitmap image format
 */
public class BitmapAndStringUtils {
    /**
     * Picture to string
     *
     * @param bitmap
     * @return
     */
    public static String convertIconToString(Bitmap bitmap)
    {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();// outputstream
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
        byte[] appicon = baos.toByteArray();// Convert to byte array
        return Base64.encodeToString(appicon, Base64.DEFAULT);

    }

    /**
     * string Turn to bitmap
     *
     * @param st
     */
    public static Bitmap convertStringToIcon(String st)
    {
        // OutputStream out;
        Bitmap bitmap = null;
        try
        {
            // out = new FileOutputStream("/sdcard/aa.jpg");
            byte[] bitmapArray;
            bitmapArray = Base64.decode(st, Base64.DEFAULT);
            bitmap =
                    BitmapFactory.decodeByteArray(bitmapArray, 0,
                            bitmapArray.length);
            // bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
            return bitmap;
        }
        catch (Exception e)
        {
            return null;
        }
    }
}

If your picture is a File file, you can use the following code:

  1. /** 
  2. * Converts the image file to a specified encoding string
  3.  * 
  4. *@ param imgFile Picture File
  5.  */  
  6. public static String file2String(File imgFile) {  
  7.     InputStream in = null;  
  8.     byte[] data = null;  
  9. // Read the image byte array
  10.     try{  
  11.         in = new FileInputStream(imgFile);  
  12.         data = new byte[in.available()];  
  13.         in.read(data);  
  14.         in.close();  
  15.     } catch (IOException e){  
  16.         e.printStackTrace();  
  17.     }  
  18. // Base64 encoding for byte arrays
  19.     BASE64Encoder encoder = new BASE64Encoder();  
  20.     String result = encoder.encode(data);  
  21. return result; //return Base64 encoded byte array string
  22. }  
    /**
     * Picture file converted to a specified encoding string
     *
     * @param imgFile  Picture file
     */
    public static String file2String(File imgFile) {
        InputStream in = null;
        byte[] data = null;
        //Read image byte array
        try{
            in = new FileInputStream(imgFile);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e){
            e.printStackTrace();
        }
        //Base64 encoding for byte array
        BASE64Encoder encoder = new BASE64Encoder();
        String result = encoder.encode(data);
        return result;//Returns the byte array string encoded by Base64
    }



top 40 step on 1
 
 

My Similar Articles

Android Image Processing (30) Android Development (1100)
http://blog.csdn.net More articles

Posted by vbmurray on Sat, 30 Mar 2019 17:24:29 -0700