| /** * Summary of image compression methods */ /* * Image compression method 01: quality compression method */ Private Bitmap compressImage (Bitmap beforBitmap ){ // Capture the data in the memory buffer and convert it into a byte array. ByteArrayOutputStream bos = new ByteArrayOutputStream (); If (beforBitmap! = Null ){ // The first parameter is the image compression format, the second parameter is the compression ratio, and the third parameter is the compressed data stored in bos. BeforBitmap. compress (CompressFormat. JPEG, 100, bos ); Int options = 100; // Cyclically determine whether the compressed image is larger than kb. If the size is greater than kb, continue to compress the image; otherwise, the image is not compressed. While (bos. toByteArray (). length/1024> 100 ){ Bos. reset (); // set to null // Compress options % BeforBitmap. compress (CompressFormat. JPEG, options, bos ); // Decrease by 10 each time Options-= 10; } // Read data from bos and store it in ByteArrayInputStream ByteArrayInputStream bis = new ByteArrayInputStream ( Bos. toByteArray ()); // Convert data into images Bitmap afterBitmap = BitmapFactory. decodeStream (bis ); Return afterBitmap; } Return null; } /* * Image compression method 02: Obtain the thumbnail */ Public Bitmap getThumbnail (int id ){ // Obtain the source Image Bitmap beforeBitmap = BitmapFactory. decodeResource ( MContext. getResources (), id ); // Width Int w = mContext. getResources () . GetDimensionPixelOffset (R. dimen. image_w ); // High Int h = mContext. getResources (). getDimensionPixelSize (R. dimen. image_h ); // Obtain the thumbnail Bitmap afterBitmap = ThumbnailUtils . ExtractThumbnail (beforeBitmap, w, h ); Return afterBitmap; } /** * Image Compression 03 * * @ Param id * Size of the image to be operated * @ Param newWidth * The specified width of the image. * @ Param newHeight * Image Height * @ Return */ Public Bitmap compressBitmap (int id, double newWidth, double newHeight ){ // Obtain the source Image Bitmap beforeBitmap = BitmapFactory. decodeResource ( MContext. getResources (), id ); // Original width and height of the image Float beforeWidth = beforeBitmap. getWidth (); Float beforeHeight = beforeBitmap. getHeight (); // Calculate the width-to-height scaling rate Float scaleWidth = 0; Float scaleHeight = 0; If (beforeWidth> beforeHeight ){ ScaleWidth = (float) newWidth)/beforeWidth; ScaleHeight = (float) newHeight)/beforeHeight; } Else { ScaleWidth = (float) newWidth)/beforeHeight; ScaleHeight = (float) newHeight)/beforeWidth; } // Matrix object Matrix matrix = new Matrix (); // Scale the image. Matrix. postScale (scaleWidth, scaleHeight ); // Create a new Bitmap to cut the image from the original image Bitmap afterBitmap = Bitmap. createBitmap (beforeBitmap, 0, 0, (Int) beforeWidth, (int) beforeHeight, matrix, true ); Return afterBitmap; } |