Recent projects in the Android project, some of which involve image processing. Here's how to call the camera app to take a picture, and save the difficulties and workarounds that appear in the ImageView control as well.
PS: The author purchased the first line of Android code: Guo Lin, referring to the contents of the complete (recommended the book, the layout and application of the front is very good). This kind of information on the Internet is very much, the author just share to the beginner at the same time online record some content, hope to be helpful to everyone.
First, set Activity_main.xml to LinearLayout layout and android:orientation="vertical"
<button android:id= "@+id/button1" android:layout_width= "match_parent" android:layout_height= " Wrap_content " android:text=" Takephoto button "/> <imageview android:id=" @+id/imageview1 " Android:layout_width= "Wrap_content" android:layout_height= "wrap_content" android:layout_gravity= " Center_horizontal "/>
then, in the Mainactivity.java file , the public class Mainactivity extends activity modifies the source code. Add a Custom variable:
Custom variable public static final int take_photo = 1;public static final int crop_photo = 2;private Button takephotobn;private Im Ageview showimage;private Uri Imageuri; Picture path private String filename; Picture name
Add functions to achieve the click-to-
photo function:
@Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); Takephotobn = (Button) Findviewbyid (R.id.button1); ShowImage = (ImageView) Findviewbyid (R.ID.IMAGEVIEW1); Click the "Photo button" button to photograph Takephotobn.setonclicklistener (new Onclicklistener () {@Override public void OnClick (View V) {//Picture name time named SimpleDateFormat format = new SimpleDateFormat ("Yyyymmddhhmmss"); Date date = new Date (System.currenttimemillis ()); filename = Format.format (date); Create a File object to store a picture of the photo SD card root//file outputimage = new File (Environment.getexternalstoragedirectory (), "test.jpg "); Save to DCIM folder File Path = Environment.getexternalstoragepublicdirectory (ENVIRONMENT.DIRECTORY_DCIM); File Outputimage = new file (path,filename+ ". jpg"); try {if (outputimage.exists ()) {outputimage.delete (); } outputimage.createnewfile (); } catch (IOException e) {e.Printstacktrace (); }//Convert the file object to a Uri and start the camera program Imageuri = Uri.fromfile (outputimage); Intent Intent = new Intent ("Android.media.action.IMAGE_CAPTURE"); Photographic Intent.putextra (Mediastore.extra_output, Imageuri); Specifies the picture output address Startactivityforresult (Intent,take_photo); Start Photo//Finish Startactivityforresult () result return Onactivityresult () function}); if (savedinstancestate = = null) {Getfragmentmanager (). BeginTransaction (). Add (R.id.container, new P Laceholderfragment ()). commit (); }}
capture and save functions with Startactivityforresult and Onactivityresult methods:
protected void Onactivityresult (int requestcode, int resultcode, Intent data) {Super.onactivityresult (Requestcode, ResultCode, data), if (resultcode! = RESULT_OK) {toast.maketext (Mainactivity.this, "Activityresult resultcode error", Toast.length_short). Show (); return; }switch (requestcode) {case Take_photo:intent Intent = new Intent ("Com.android.camera.action.CROP");// Trim Intent.setdataandtype (Imageuri, "image/*"); Intent.putextra ("scale", true);//Set width-height ratio intent.putextra ("Aspectx", 1) ; Intent.putextra ("Aspecty", 1); Set crop picture width height Intent.putextra ("outputx", 340); Intent.putextra ("Outputy", 340); Intent.putextra (Mediastore.extra_output, Imageuri); Toast.maketext (mainactivity.this, "crop picture", Toast.length_short). Show ();//Broadcast Refresh album Intent INTENTBC = new Intent (intent.act Ion_media_scanner_scan_file); Intentbc.setdata (Imageuri); This.sendbroadcast (INTENTBC); Startactivityforresult (Intent, Crop_photo); Set crop parameters display picture to Imageviewbreak;case crop_photo:try {//Picture parsed into bitmap object bitmap biTMap = Bitmapfactory.decodestream (Getcontentresolver (). Openinputstream (Imageuri)); Toast.maketext (Mainactivity.this, imageuri.tostring (), Toast.length_short). Show (); Showimage.setimagebitmap ( Bitmap); The cropped photo is displayed} catch (FileNotFoundException e) {e.printstacktrace ();} Break;default:break;}}
due to the write data operation and camera operation in the SD card, it is necessary to declare the permissions in the Androidmainfest.xml file:
The results of the operation are as follows:
There are several issues to note:
1. Photography and both involve startactivityforresult and onactivityresult interactions.
Startactivityforresult (Intent Intent, //intent object int Requestcode //>=0 When activity ends Requestcode will be returned in Onactivityresult () onactivityresult (int requestcode, //provided to Onactivityresult, To confirm that the returned data is the int resultcode returned from which activity, //The activity is returned by its Setresult () method, typically result_canceled or result_okintent data //A Intent object with returned data)
requestcode corresponds. At the same time combined with intent intent to achieve photo and, the core code is as follows: (intent parameter setting omitted)
&NBSP;&NBSP; intent Intent = new Intent ("Android.media.action.IMAGE_CAPTURE");
startactivityforresult (Intent,take_photo);
intent Intent = new Intent ("Com.android.camera.action.CROP");
Startactivityforresult (Intent, crop_photo);
2. Using Android to take photos saved in the System album, the library cannot immediately display the latest photos. The workaround is to send the system built-in broadcast to refresh the album implementation display. The code is as follows:
Intent INTENTBC = new Intent (intent.action_media_scanner_scan_file); Intentbc.setdata (Imageuri); This.sendbroadcast (INTENTBC);
You may use the following broadcast to scan the entire SD card, but 4.4 has forbidden such an operation:
Sendbroadcast (New intent (intent.action_media_mounted, uri.parse (...)))
reference http://blog.csdn.net/xiaanming/article/details/ 8990627
3. When the program is run it is possible to find that the resulting image is displayed very small when triggered by a intent intent, The camera program does not return a full-size image to the main event, which requires a lot of memory and a limited amount of memory on the mobile device. Usually the camera returns a small thumbnail in the intent of the return, and a larger image may cause an oom problem. Reference: Advanced Programming for Android Multimedia development : Shawn Van every
provides bitmapfactory classes for large image Android, Allows bitmap images to be loaded through various resources. Calling the Bitmapfactory.options class defines how the bitmap is read into memory when the image is loaded. You can set the Bitmapfactory sample size. and specify the insamplesize parameter to indicate the proportion of the resulting bitmap image at load time. As insamplesize=8 indicates that an image with a size of 1/8 of the original image is produced. Refer to the following code:
IF ( RESULTCODE==RESULT_OK) {displaymetrics dm = new Displaymetrics (); Getwindowmanager (). Getdefaultdisplay (). GetMetrics ( DM); int width = dm.widthpixels; width int height = dm.heightpixels; Height//Load image size instead of image itself bitmapfactory.options bmpfactoryoptions = new Bitmapfactory.options (); Bmpfactoryoptions.injustdecodebounds = true; Bitmap is null just put the width of the picture in options int heightratio = (int) Math.ceil (bmpfactoryoptions.outheight/(float) height); int WidthRatio = (int) Math.ceil (bmpfactoryoptions.outwidth/(float) width);//Set Picture compression ratio if the two scale is greater than the 1 image side will be greater than the screen if (heightratio >1&&widthratio>1) {if (heightratio>widthratio) {bmpfactoryoptions.insamplesize = HeightRatio;} else {bmpfactoryoptions.insamplesize = WidthRatio;}} Image true Decoding bmpfactoryoptions.injustdecodebounds = false; Bitmap Bitmap = Bitmapfactory.decodefile (imageuri.tostring (), bmpfactoryoptions); Showimage.setimagebitmap (BITMAP); The cropped photo is displayed}
4. You cannot setimagebitmap the ImageView control with the Nexus 4 clip, only the Save button and no Trim button. The test found that no RESULT_OK was returned. The problem cannot be solved.
Reference:Unable to Save Photo edits
finally hope that the article is helpful to everyone, this is my study of the Android image processing part of the basic article and the solution process.
references and recommended blog posts: (All very good information-.-)
"Android first line code" Guo Lin reference 8.3 call camera and album
Android photo image selection and picture clipping By:lee_allen
android_ camera Camera_ call system camera return data to null by:strawberry2013
Android Picture clipping feature solid detailed by: Pony
Android Development Photography, photo album Save photos Tips
Android photographed and displayed in ImageView (Advanced) By:leesa
Android Transfers the system's camera and displays the photos on the ImageView
cameraintent data null in Onactivityresult (int requestcode, int resultcode, intentdata)
Android High-efficiency loading large map, multi-figure solution, effectively avoid the program Oom By:guolin
Android camera, photo album get picture display and save to SD card by: Tang Yu _ryan
Android, get local pictures | Get photos directly by:zcljy0318
(By:eastmount 2014-10-23 10 o'clock in the evening http://blog.csdn.net/eastmount/)
[Android] photo, save and display in the ImageView control