Common Bitmap operations in Android (II. Code)

Source: Internet
Author: User
Package com. testbitmapscale; import java. io. file; import java. io. fileInputStream; import java. io. fileOutputStream; import java. io. IOException; import java. io. inputStream; import java. util. iterator; import com. testbitmapscale. r. drawable; import android. app. activity; import android. graphics. bitmap; import android. graphics. bitmap. config; import android. graphics. bitmapFactory; import android. graphics. canvas; import Android. graphics. matrix; import android. graphics. paint; import android. graphics. porterDuff. mode; import android. graphics. porterduxfermode; import android. graphics. rect; import android. graphics. rectF; import android. graphics. drawable. bitmapDrawable; import android. graphics. drawable. drawable; import android. media. thumbnailUtils; import android. OS. bundle; import android. OS. environment; import android. view. vi Ew; import android. widget. imageView; // method: // 1 generate a Bitmap image with rounded corners // 2 generate a Bitmap scaling chart // 3. compress the image length and width and kB // Note: // the above Code, when testing one of the methods, it is best to comment out other codes: public class MainActivity extends Activity {private ImageView imageView; private Bitmap copyRawBitmap1; private Bitmap copyRawBitmap2; private Bitmap copyRawBitmap3; @ Overridepublic void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. m Ain); imageView = (ImageView) findViewById (R. id. imageView); // Method 1: Obtain the image Bitmap rawBitmap = BitmapFactory from the resource file. decodeResource (getResources (), R. drawable. haha); copyRawBitmap1 = rawBitmap; copyRawBitmap2 = rawBitmap; copyRawBitmap3 = rawBitmap; // Method 2: Obtain the image from the SD card (method 1) String SDCarePath = Environment. getExternalStorageDirectory (). toString (); String filePath = SDCarePath + "/" + "haha.jpg"; Bitmap rawBitmap1 = BitmapFactory. DecodeFile (filePath, null); // Method 2: Obtain an image from the SD card (method 2) InputStream inputStream = getBitmapInputStreamFromSDCard ("haha.jpg"); Bitmap rawBitmap2 = BitmapFactory. decodeStream (inputStream); // ----> The following is the Bitmap roundCornerBitmap = this. toRoundCorner (rawBitmap, 40); imageView. setImageBitmap (roundCornerBitmap ); // ----> the rounded corner of the image will be set above // ----> The following is the size of the image's height and width kB compressed // get the original height and width int rawHeight = rawBitmap. getHeight (); int rawWidth = RawBitmap. getWidth (); // set the new int newHeight = 500; int newWidth = 500; // calculate the scaling factor float heightScale = (float) newHeight)/rawHeight; float widthScale = (float) newWidth)/rawWidth; // newly created Matrix matrix = new Matrix (); matrix. postScale (heightScale, widthScale); // sets the image rotation angle // matrix. postRotate (-30); // sets the image skew // matrix. postSkew (0.1f, 0.1f); // After the image size is compressed, the width and height of the image and the size of kB change Bitmap newBitmap = Bitmap. CRES AteBitmap (rawBitmap, 0, 0, rawWidth, rawWidth, matrix, true); // converts Bitmap to DrawableDrawable newBitmapDrawable = new BitmapDrawable (newBitmap); imageView. setImageDrawable (newBitmapDrawable); // Save the Bitmap to the SDCard to facilitate the comparison of the original image. compressAndSaveBitmapToSDCard (newBitmap, "xx100.jpg", 80); // problem: // The Source image size is 625x690 90.2kB // if the image size is set to 171kB after 500x500 compression. that is, the size of kB increases after compression. // The cause is: compress (Bitmap. compressFormat. JPEG, quality, FileOutputStream); // The second parameter quality is set to a bit large (for example, 100 ). // commonly used is 80, which is caused by the size of the first 100. // ----> the above is to compress the Image Height and size kB/----> the following is to compress the image kB, and the width and height remain unchanged this. compressAndSaveBitmapToSDCard (copyRawBitmap1, "0011fa.jpg", 80); // ----> to compress the kB of the image, width and height unchanged // ----> The following is the method for obtaining the thumbnail of the SD card image 1 String SDCarePath1 = Environment. getExternalStorageDirectory (). toString (); String filePath1 = SDCarePath1 + "/" + "haha.jpg"; Bitmap bitmapThumbnail1 = this. getBitmapThumbnail (filePat H1); imageView. setImageBitmap (bitmapThumbnail1); // ----> the above is the method for obtaining the thumbnail of the SD card image. 1 // ----> The following is the method for obtaining the thumbnail of the SD card image. 2 String SDCarePath2 = Environment. getExternalStorageDirectory (). toString (); String filePath2 = SDCarePath2 + "/" + "haha.jpg"; Bitmap tempBitmap = BitmapFactory. decodeFile (filePath2); Bitmap bitmapThumbnail2 = ThumbnailUtils. extractThumbnail (tembitmap, 100,100); imageView. setImageBitmap (bitmapThumbnail2); // ----> Card image thumbnails method 2} // read the image private InputStream getBitmapInputStreamFromSDCard (String fileName) {if (Environment. getExternalStorageState (). equals (Environment. MEDIA_MOUNTED) {String SDCarePath = Environment. getExternalStorageDirectory (). toString (); String filePath = SDCarePath + File. separator + fileName; File file = new File (filePath); try {FileInputStream fileInputStream = new FileInputStream (file); return fileInputS Tream;} catch (Exception e) {e. printStackTrace () ;}} return null;} // obtain the directory path function of SDCard: private String getSDCardPath () {String SDCardPath = null; // judge whether the SDCard has boolean IsSDcardExist = Environment. getExternalStorageState (). equals (android. OS. environment. MEDIA_MOUNTED); if (IsSDcardExist) {SDCardPath = Environment. getExternalStorageDirectory (). toString () ;}return SDCardPath;} // compress and save the image to SDCardprivate void comp RessAndSaveBitmapToSDCard (Bitmap rawBitmap, String fileName, int quality) {String saveFilePaht = this. getSDCardPath () + File. separator + fileName; File saveFile = new File (saveFilePaht); if (! SaveFile. exists () {try {saveFile. createNewFile (); FileOutputStream fileOutputStream = new FileOutputStream (saveFile); if (fileOutputStream! = Null) {// imageBitmap. compress (format, quality, stream ); // write the bitmap compression information to a specified output stream // The first parameter format is the compression format // The second parameter quality is the image compression ratio value, 0-100.0 means small size compression, 100 means high quality compression // The third parameter stream is the output stream rawBitmap. compress (Bitmap. compressFormat. JPEG, quality, fileOutputStream);} fileOutputStream. flush (); fileOutputStream. close ();} catch (IOException e) {e. printStackTrace () ;}}// obtain the image thumbnail private Bitmap getBitmapThumbnail (String filePath) {B ItmapFactory. options options = new BitmapFactory. options (); // true, the actual bitmap object is not returned, and the memory space is not allocated to the object. However, some decoded boundary information such as the image size can be obtained. options. inJustDecodeBounds = true; // at this time, rawBitmap is nullBitmap rawBitmap = BitmapFactory. decodeFile (filePath, options); if (rawBitmap = null) {System. out. println ("rawBitmap is null");} // inSampleSize indicates that the thumbnail size is a fraction of the size of the original image, if the value is 3 //, the width and height of the thumbnail are 1/3 of the original image, and the image size is 1/9 of the original size. // calculate sampleSizeint sampleSize = comp UteSampleSize (options, 150,200*200); // to read the image, you must set options. inJustDecodeBounds sets falseoptions. inJustDecodeBounds = false; options. inSampleSize = sampleSize; // the original image size is 625x690 90.2kB // test the call computeSampleSize (options, 100,200*100 ); // get sampleSize = 8 // get width and height 79 and 87 // 79*8 = 632 87*8 = 696 Bitmap thumbnailBitmap = BitmapFactory. decodeFile (filePath, options); // save it to the SD card to make it easier to compare this. compressAndSaveBitmapToSDCard (thumbnailBitmap, "15.jpg", 80); return thumbnailBitmap;} // reference: // initiate static int computeSampleSize (BitmapFactory. options options, int minSideLength, int maxNumOfPixels) {int initialSize = values (options, minSideLength, maxNumOfPixels); int roundedSize; if (initialSize <= 8) {roundedSize = 1; while (roundedSize <initialSize) {roundedSize <= 1 ;}} else {roundedSize = (initialSize + 7)/8*8;} return roundedSize ;} private static int computeInitialSampleSize (BitmapFactory. options options, int minSideLength, int maxNumOfPixels) {// width of the original image, double w = options. outWidth; // The height of the original image, double h = options. outHeight; System. out. println ("===========w =" + w + ", h =" + h); int lowerBound = (maxNumOfPixels =-1 )? 1: (int) Math. ceil (Math. sqrt (w * h/maxNumOfPixels); int upperBound = (minSideLength =-1 )? 128: (int) Math. min (Math. floor (w/minSideLength), Math. floor (h/minSideLength); if (upperBound <lowerBound) {// return the larger one when there is no overlapping zone. return lowerBound;} if (maxNumOfPixels =-1) & (minSideLength =-1) {return 1;} else if (minSideLength =-1) {return lowerBound;} else {return upperBound;}/*** @ param bitmap the image to be modified * @ param pixels radian * @ return rounded corner image * // Reference: // http://blog.csdn.net/c8822882/article/details/6906768 public Bitmap toRoundCorner (Bitmap bitmap, int pixels) {Bitmap roundCornerBitmap = Bitmap. createBitmap (bitmap. getWidth (), bitmap. getHeight (), Config. ARGB_8888); Canvas canvas = new Canvas (roundCornerBitmap); int color = 0xff0000242; // int color = 0xff0000242; Paint paint = new Paint (); paint. setColor (color); // prevents sawtooth paint. setAntiAlias (tr Ue); Rect rect = new Rect (0, 0, bitmap. getWidth (), bitmap. getHeight (); RectF rectF = new RectF (rect); float roundPx = pixels; // This is equivalent to the canvas. drawARGB (0, 0, 0, 0); // first draws a rectangular canvas with rounded corners. drawRoundRect (rectF, roundPx, roundPx, paint); paint. setXfermode (new porterduduxfermode (Mode. SRC_IN); // draw the original bitmap to the current bitmap !!! Pay attention to this understanding canvas. drawBitmap (bitmap, rect, rect, paint); return roundCornerBitmap ;}}

 

PS:

In the example of "compressing the Image Height and size kB", there are several parameters with the height and width reversed or incorrect. You need to modify the following:

Matrix. postScale (heightScale, widthScale );

Bitmap newBitmap = Bitmap. createBitmap (rawBitmap, 0, 0, rawWidth, rawWidth, matrix, true );

January 30, 2013 15:36:20

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.