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:
- 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, then set options.inJustDecodeBounds back to true, that is, read-only without reading the 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 you want to zoom in
- float hh = pixelH; / / / Setting the height to 240f, you can clearly see that the image is reduced.
- float ww = pixelW; / / / Set the width to 120f, and you can see that the picture is reduced significantly.
- // Scale-up ratio. Because it is a 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 > W w) {// if the width is large, scale according to the width.
- be = (int) (newOpts.outWidth / ww);
- } Otherwise (w < H & H > H h) {// Scale according to width if height is high.
- 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);
- // After compressing the scale, the mass compression is carried out.
- // return compress(bitmap, maxSize); // There is little significance of quality compression here, but it consumes resources and deletes.
- 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 if the picture is larger than 1M, compress to avoid overflow when generating the picture (BitmapFactory.decodeStream)
- os.reset(); // Reset baos is to empty baos.
- image.compress(Bitmap.CompressFormat.JPEG, 50, os); //Here compress 50%, 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; / / / Setting the height to 240f, you can clearly see that the image is reduced.
- float ww = pixelW; / / / Set the width to 120f, and you can see that the picture is reduced significantly.
- // Scale-up ratio. Because it is a 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 > W w) {// if the width is large, scale according to the width.
- be = (int) (newOpts.outWidth / ww);
- } Otherwise (w < H & H > H h) {// Scale according to width if height is high.
- be = (int) (newOpts.outHeight / hh);
- }
- if (be <= 0) be = 1;
- newOpts.inSampleSize = be; // Set Scale Ratio
- // Reread the picture and note that options.inJustDecodeBounds has been set back to false at this time.
- is = new ByteArrayInputStream(os.toByteArray());
- bitmap = BitmapFactory.decodeStream(is, null, newOpts);
- // After compressing the scale, the mass compression is carried out.
- // return compress(bitmap, maxSize); // There is little significance of quality compression here, but it consumes resources and deletes.
- 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();
- }
- }
- }
- }
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(); } } } }
- /**
- * Quality Compression Method
- *
- * @param image
- * @return
- */
- public static Bitmap compressImage(Bitmap image) {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- image.compress(Bitmap.CompressFormat.JPEG, 100, baos); // quality compression method, where 100 means uncompressed, storing compressed data in baos
- int options = 90;
- while (baos. toByteArray (). len gt h / 1024 > 100) {// Cycle judges if the compressed image is greater than 100kb, greater than the continued compression.
- baos.reset(); // Reset baos to clear baos
- image.compress(Bitmap.CompressFormat.JPEG, options, baos); // Here compress options, and store the compressed data in baos.
- options - = 10; // Decrease by 10 each time.
- }
- ByteArray InputStream isBm = new ByteArray InputStream (baos. to ByteArray ()); // Store the compressed data baos in ByteArray InputStream.
- Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null); // Generate pictures from ByteArray InputStream data
- return bitmap;
- }
/** * 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)
- /**
- * Picture Scale Compression Method
- *
- *@ param srcPath
- * @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, new Opts); // At this time, 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 height and width as follows:
- float hh = 800f; // Set height to 800f here
- float ww = 480f; // Set the width here to 480f
- // Scale-up ratio. Because it is a fixed scale, only one of the data with high or wide can be calculated.
- int be=1; // be=1 means no zooming.
- if (w > h & & W > W w) {// if the width is large, scale according to the width.
- be = (int) (newOpts.outWidth / ww);
- } if (w < H & & H > H h) {// if the height is high, scale according to the width.
- be = (int) (newOpts.outHeight / hh);
- }
- if (be <= 0)
- be = 1;
- newOpts.inSampleSize = be; // Set zoom ratio.
- // Re-read the picture and note that options.inJustDecodeBounds has been set back to false at this time.
- bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
- return compress Image (bitmap); // Compress the scale before compressing the quality.
- }
3. Bitmap/** * 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 }
- /**
- * Picture Scale Compression Method
- *
- *@ param image (compressed according to Bitmap picture)
- * @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(); // Reset baos to empty baos
- image.compress(Bitmap.CompressFormat.JPEG, 80, baos); // Here compress 50%, 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 height and width as follows:
- // float hh = 800f; // Set height to 800f here
- // float ww = 480f; // Set the width here to 480f
- float hh = 512f;
- float ww = 512f;
- // Scale-up ratio. Because it is a fixed scale, only one of the data with high or wide can be calculated.
- int be=1; // be=1 means no zooming.
- if (w > h & & W > W w) {// if the width is large, scale according to the width.
- be = (int) (newOpts.outWidth / ww);
- } if (w < H & H > H h) {// / 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
- // Re-read the picture and note that options.inJustDecodeBounds has been set back to false at this time.
- isBm = new ByteArrayInputStream(baos.toByteArray());
- bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
- return compress Image (bitmap); // Compress the scale before compressing the quality.
- //return bitmap;
- }
/** * 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; }
- 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 zoomed 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 larger the number, the smaller the size of the picture.
- // Re-read the picture and note 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();
- }
- }
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(); } }
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
- import android.graphics.Bitmap;
- import android.graphics.BitmapFactory;
- import android.util.Base64;
- import java.io.ByteArrayOutputStream;
- /**
- *
- *
- * Function description: Picture bitmap, a common tool for Android development, is converted to string and String strings 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(); // to byte array
- return Base64.encodeToString(appicon, Base64.DEFAULT);
- }
- /**
- * string 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;
- }
- }
- }
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:
- /**
- * Converts the image file to a specified encoding string
- *
- *@ param imgFile Picture File
- */
- public static String file2String(File imgFile) {
- InputStream in = null;
- byte[] data = null;
- // Read the 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 arrays
- BASE64Encoder encoder = new BASE64Encoder();
- String result = encoder.encode(data);
- return result; //return Base64 encoded byte array string
- }
/** * 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 }
- Last article Detailed Explanation of SQLite Application in Android
- Next article An efficient way to compress Android images below 100K without distortion
My Similar Articles
- •Perfect example of Android open source framework ImageLoader 2015-04-19 Reading 2644
- •Android: Source code for image compression methods with specified resolution and clarity 2015-04-08 Reading 1571
- •An efficient way to compress Android images below 100K without distortion 2015-03-12 Reading 10112
- •Gray Head Image Processing for Android Offline Users 2013-07-12 Reading 1278
- •Ultimate Solution for Android Big Picture Clipping (Part 2: Photo Screenshots) 2013-02-22 Reading 693
- •Summary of android Picture Compression 2015-04-08 Reading 1232
- •Bitmap Picture Compression Size for Android Programming 2015-04-08 Reading 955
- •Android - Memory issues when views display large numbers of images 2015-01-06 Reading 1037
- •android selects pictures or photos to upload to the server (including upload parameters) 2013-03-01 Reading 7742
- •The ultimate solution for Android big picture clipping (in: screenshots from albums) 2013-02-22 Reading 586