Step-by-Step android Development 66: android Image Selection
I recently made a page to provide feedback on the problem page, which provides a function for users to upload problematic images. I was so stupid that I wanted to list all the images in the system and asked the user to select them. Later I found that I could directly open the api for all images on the mobile phone. Effect
Provide the main code:
1. Select an image
Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); startActivityForResult(i, 1);
2. retrieve images
Protected void onActivityResult (int requestCode, int resultCode, Intent data) {super. onActivityResult (requestCode, resultCode, data); try {if (requestCode = 1 & resultCode = RESULT_ OK & null! = Data) {Uri selectedImage = data. getData (); String [] filePathColumn = {MediaStore. images. media. DATA}; Cursor cursor = getContentResolver (). query (selectedImage, filePathColumn, null, null); cursor. moveToFirst (); int columnIndex = cursor. getColumnIndex (filePathColumn [0]); String picturePath = cursor. getString (columnIndex); cursor. close (); BitmapFactory. options opts = new BitmapFactory. optio Ns (); opts. inJustDecodeBounds = true; BitmapFactory. decodeFile (picturePath, opts); opts. inSampleSize = computeSampleSize (opts,-1,160*160); // convert it to a 160*160 size image. // you must set it back to false, because we set it to true opts. inJustDecodeBounds = false; try {Bitmap bmp = BitmapFactory. decodeFile (picturePath, opts); if (mPosition! = 0) // replace {fba. getmImgs (). set (mPosition, bmp); fba. getmImgPaths (). set (mPosition, picturePath);} else {fba. getmImgs (). add (bmp); fba. getmImgPaths (). add (picturePath) ;}} catch (OutOfMemoryError err) {if (err! = Null) {err. printStackTrace () ;}} fba. policydatasetchanged () ;}} catch (Exception e) {if (e! = Null) {e. printStackTrace () ;}} catch (OutOfMemoryError e) {if (e! = Null) {e. printStackTrace ();}}}
public int computeSampleSize(BitmapFactory.Options options, int minSideLength, int maxNumOfPixels) { int initialSize = computeInitialSampleSize(options, minSideLength, maxNumOfPixels); int roundedSize; if (initialSize <= 8) { roundedSize = 1; while (roundedSize < initialSize) { roundedSize <<= 1; } } else { roundedSize = (initialSize + 7) / 8 * 8; } return roundedSize; } private int computeInitialSampleSize(BitmapFactory.Options options, int minSideLength, int maxNumOfPixels) { double w = options.outWidth; double h = options.outHeight; 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 lowerBound; } if ((maxNumOfPixels == -1) && (minSideLength == -1)) { return 1; } else if (minSideLength == -1) { return lowerBound; } else { return upperBound; } }