Let's have some chicken soup first:
Stay Hungry,stay Foolish
The interpretation of this sentence: we must understand their own insignificance. If we do not learn, the pace of technological development will allow us to be emptied after five years. Therefore, we must embrace the knowledge of the future with the humble self-awareness of beginners and the desire of the hungry.
- In these days, you need to select a picture from the gallery or take a photo to create a picture, and then show it on the Iamgeview control. Of course, the ability to select pictures from the gallery and take photos to select them is easy to implement. Write the code directly:
charsequence[] items = {"Take photos","Gallery"};NewAlertdialog.builder (context). Settitle ("Please select:"). SetIcon (R.drawable.ic_choose_picture). Setitems (Items,NewOnclicklistener () { Public void OnClick(Dialoginterface Dialog,intwhich) {Switch(which) { Case 0://Call photo function //Create a file object to store the photographed objectTakephotoimage =NewFile (Environment.getexternalstoragedirectory (),"Take_photo_image.jpg");Try{if(Takephotoimage.exists ()) {Takephotoimage.delete (); } takephotoimage.createnewfile (); }Catch(Exception e) {E.printstacktrace (); }//Convert a file object to a URI objectImageuri =uri.fromfile (takephotoimage); Intent Intent =NewIntent (mediastore.action_image_capture);//Specify the output address of the pictureIntent.putextra (Mediastore.extra_output, Imageuri); Startactivityforresult (Intent, Take_photo); Break; Case 1://Call System Gallery //Create a file object for storing pictures after selecting galleryFile Choosephoto =NewFile (Environment.getexternalstoragedirectory (),"Choose_photo.jpg");Try{if(Choosephoto.exists ()) {Choosephoto.delete (); } choosephoto.createnewfile (); }Catch(Exception e) {E.printstacktrace (); }//Convert a file object to a URI objectImageuri = Uri.fromfile (Choosephoto); Intent Intent2 =NewIntent ("Android.intent.action.GET_CONTENT"); Intent2.settype ("image/*"); Intent2.putextra ("Crop","true"); Intent2.putextra ("Scale",true); Intent2.putextra (Mediastore.extra_output,imageuri); Startactivityforresult (Intent2, Crop_photo); Break; }}). Show ();
The code is simple enough to create a dialog box with two item options. One is a picture, one is a library. As shown below:
-
The two item option is designed to generate a picture and set it on the ImageView control.
-
Taking photos and selecting pictures from the gallery first creates a file object that stores the pictures taken by the camera or stores the pictures selected from the gallery.
-
Then put it in the root directory of the phone, my phone is in the memory device root directory, this does not matter. The FromFile () method of the URI is then called to convert the file object to a URI object. This URI object identifies the unique address of the picture.
-
If you click on a photo, you will then build a intent object and specify the intent ACTION as: mediastore.action_image_capture, and then call Intent's Putextra () method to specify the output address of the picture , this fills in the URI object that you just got, and finally calls Startactivityforresult () to start the activity.
- Because the code above uses Startactivityforresult () to start the activity, the Onactivityresult () method is called back after the photo is successful, that is, the result is returned to the Onactivityresult () method after the photo is taken. Therefore, the method can be rewritten to take pictures after the picture to do further processing. The method is as follows:
/** * Callback This method when calling Startactivityforresult * / @Override Public void Onactivityresult(intRequestcode,intResultCode, Intent data) {Switch(Requestcode) {//Photo CaseTake_photo:if(ResultCode = = ACTIVITY.RESULT_OK) {Intent Intent =NewIntent ("Com.android.camera.action.CROP"); Intent.setdataandtype (Imageuri,"image/*"); Intent.putextra ("Scale",true); Intent.putextra (Mediastore.extra_output, Imageuri); Startactivityforresult (Intent, Crop_photo); } Break;//Crop picture CaseCrop_photo:if(ResultCode = = ACTIVITY.RESULT_OK) {Try{//Compress bitmap objectsBitmapfactory.options Options =NewBitmapfactory.options (); Options.insamplesize =8; Options.inpreferredconfig = Bitmap.Config.RGB_565; Options.inpurgeable =true; Options.ininputshareable =true; Bitmap=bitmapfactory.decodestream (Getactivity (). Getcontentresolver (). Openinputstream (ImageUri),NULL, options); Setimagedata (bitmap);if(bitmapentities.size () = =1) {adapter =NewBitmapadapter (context, bitmapentities); Gv_picture.setadapter (adapter); }Else{adapter.notifydatasetchanged (); } Linear_picture.addview (View_picture,1); }Catch(Exception e) {E.printstacktrace (); } } Break; } }
- It says that if the camera is successfully photographed and the Onactivityresult () method is recalled, the intent object will continue to be built and its action specified as:
"Com.android.camera.action.CROP".
This intent is used to crop the photograph taken. Because the camera is bigger, we may just want to intercept a small part of it. Then set some necessary properties on the intent and then call Startactivityforresult () to start the clipping program. The cropped image is also exported to the image file in the root directory of the phone.
===========================================
- If you click on the item option is the gallery. Then the system's library will be called to select the picture. Here, there is not much difference with the basic operation when taking pictures.
is to create a file object that holds the files selected from the gallery. It then constructs a intent object and assigns its action as:"Android.intent.action.GET_CONTENT". Next, set some necessary parameters for the intent object, including whether to allow zooming and cropping, the output position of the picture, and so on. Finally call the Startactivityforresult () method, you can open the album program to select Photos.
-
Here is a small trick, that is, when we call the Startactivityforresult () method, the value passed to the second parameter is still: Crop_photo constant, so that you can reuse the camera to display the image of the logic, You don't have to write the logic to display the picture again.
-
Well, the above two item options are all done, and the next is the critical moment.
After the cropping operation is completed, the program will callback to the Onactivityresult method, this time can use the Bitmapfactory Decodestream () method to store the image file stored in the root directory of the phone to the bitmap object, It is then set to show up on the ImageView control.
-
I'm here with the GridView control to display some pictures. But all the same, in the GridView setting adapter, you need to set the bitmap object to the ImageView control in the custom adapter. The first time you set up one or two images is as follows:
However, once the picture is more, the program crashes directly and looks at the Logcat error log.
An eye-catching Java.lang.OutOfMemoryError (Memory overflow error), the last to meet the error. Say the truth, the egg hurts. Puzzled for a while, tried a lot of methods, and finally very good to do some effective image compression method to optimize the memory overflow problem, but does not completely solve the memory overflow problem. So sometimes we have to make some restrictions on the number of images. Like nails for the business management of the picture selection allows the selection of up to 9 photos, send friends to send pictures up to 9 photos allowed. Sometimes it takes a few restrictions to solve some unavoidable problems.
The code above, which has a memory overflow error, is positioned and navigates directly to the following line, as shown in:
The line code is as follows:
Bitmap=bitmapfactory.decodestream (Getactivity (). Getcontentresolver (). Openinputstream (ImageUri));
Why does this line of code lead to Oom? Let's talk about this: the line code is used to parse and create bitmap objects from the specified input stream. However, due to the small memory of the mobile phone system, if you continue to parse and create the bitmap object, it is possible that the bitmap used by the previously created memory has not been reclaimed, causing outofmemory errors when the program runs. so we need to compress the bitmap object first and use it to reduce the memory consumption, which can effectively solve the problem. My workaround is to replace the above code with the code shown:
The lines of code shown are explained below:
======
BitmapFactory.Options options = new BitmapFactory.Options();
This line of code is used to create a Bitmapfactory.options object, and the options only save the size of the picture, without saving the image to memory.
======
options.inSampleSize = 8;
This line of code is the most critical code . Let's go inside to see the source code, the source code is as follows:
The source code comments for everyone to talk about.
Note: If the value is set to >1, the parser is asked to make a second sample of the original, that is, two parse, and return a smaller image to save memory. The pixel size of the secondary sample size, corresponding to a pixel that decodes the bitmap. For example, if insamplesize = = 4, it will return an image that is the original 1/4 height and 1/4 width, and the number of 1/16 pixels. Values of any value < = 1 are assigned by =.
The above source notes are a good illustration of the key to this line of code. Everyone to effectively avoid the oom error must remember to add Oh! Only in this way can you effectively save the memory that the bitmap object occupies. Don't forget it!
======
options.inPreferredConfig = Bitmap.Config.RGB_565;
This line of code is the config parameter of the add-on, the parser or the corresponding resolution according to the current parameter configuration, which can also effectively reduce the loaded memory.
======
true;
The line code works: The resulting bitmap will allocate its pixels so that they can be purged by the system to reclaim the memory.
======
true;
The function of the line code: theininputshareable property is related to Inpurgeable, and when the Inpurgeable property is set to False, the Ininputshareable property can be ignored. But if both of these properties are set to True, the source comment says this: Make sure the bitmap can share a reference input data if it must be deep-copied. OK, this is not the key, not set is also possible.
======
Last Call Method:
bitmap=BitmapFactory.decodeStream(getActivity().getContentResolver().openInputStream(imageUri),null, options);
The line of code is to set the parse input stream to return a compressed bitmap object based on options. the use of bitmap at this time can effectively avoid the oom. The following is attached to the test picture of my project for everyone to see, seeing is real! Such as:
Well, without an oom error, 9 images were successfully presented on the interface. ( burst material, the middle of the picture is my Oh!) Do not envy elder brother, have time to remember exercise! You can have my body, too! :))
===========================================
In the first place, there will be more practical development of small problems, then continue to learn progress and to share some solutions to everyone.
All right, it's been so long. The dry goods are on!
Give us some tips on how to get rid of the fatigue of programmers (blog, but I think it's good):
The link address is: How programmers get rid of fatigue
Make a little progress every day! Come on!
An effective solution to oom when parsing, creating bitmap objects in Android development and attaching some dry goods