force a horizontal screen of activity to ensure that the preview is in the right direction. Using the Orientationeventlistener monitoring device direction, judging the vertical beat, rotate the photo before saving, to ensure that the preview picture when the portrait and save the picture in the same direction.
Operating effect:
Code:
Testcameraactivity.java
Package Com.example.testcamera;import Java.io.bytearrayoutputstream;import Java.io.fileoutputstream;import Java.io.ioexception;import Java.util.list;import Java.util.uuid;import Android.annotation.suppresslint;import Android.app.activity;import Android.content.context;import Android.content.intent;import Android.graphics.Bitmap; Import Android.graphics.bitmapfactory;import Android.graphics.matrix;import Android.hardware.camera;import Android.hardware.camera.parameters;import Android.hardware.camera.size;import Android.os.Build;import Android.os.bundle;import Android.util.log;import Android.view.orientationeventlistener;import Android.view.surfaceholder;import Android.view.surfaceview;import Android.view.view;import Android.view.view.onclicklistener;import Android.widget.button;public class Testcameraactivity extends Activity Implements Onclicklistener,surfaceholder.callback {private static final String TAG = "testcameraactivity";p ublic static Final String key_filename = "FILENAME";p RivaTe Button mtakephoto;private surfaceview msurfaceview;private Camera mcamera;private String mfilename;private Orientationeventlistener Moreventlistener; Device Orientation Listener private Boolean mcurrentorientation; Current device direction horizontal screen false, vertical screen true/* image data processing is not completed when the callback function */private camera.shuttercallback mshutter = new Camera.shuttercallback () {@ overridepublic void Onshutter () {//General display progress bar}};/* image data processing after the completion of the callback function */private camera.picturecallback mJpeg = new CAMERA.PICTU Recallback () {@Overridepublic void Onpicturetaken (byte[] data, Camera camera) {//Save picture Mfilename = Uuid.randomuuid (). ToString () + ". jpg"; LOG.I (TAG, mfilename); FileOutputStream out = null;try {out = Openfileoutput (Mfilename, context.mode_private); byte[] NewData = null;if (mCurrent Orientation) {//Vertical screen, rotate picture to save bitmap Oldbitmap = Bitmapfactory.decodebytearray (data, 0,data.length); Matrix matrix = new Matrix (); Matrix.setrotate (90); Bitmap Newbitmap = Bitmap.createbitmap (oldbitmap, 0, 0,oldbitmap.getwidth (), Oldbitmap.getheight (), Matrix, True); BytearrayoutputstreaM BAOs = new Bytearrayoutputstream (); Newbitmap.compress (Bitmap.CompressFormat.JPEG, baos); NewData = Baos.tobytearray (); Out.write (NewData);} else {out.write (data);}} catch (IOException e) {e.printstacktrace ();} finally {try {if (out! = null) Out.close ();} catch (IOException e) {E.printsta Cktrace ();}} Intent i = new Intent (testcameraactivity.this, Showpicture.class); I.putextra (Key_filename, mfilename); StartActivity ( i); Finish ();}; @SuppressWarnings ("deprecation") @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate ( Savedinstancestate); Setcontentview (r.layout.activity_test_camera); Mtakephoto = (Button) Findviewbyid (R.id.take_ photo); Mtakephoto.setonclicklistener (this); Photo button Listener Startorientationchangelistener (); Start Device orientation listener Msurfaceview = (Surfaceview) Findviewbyid (R.id.my_surfaceview); Surfaceholder holder = Msurfaceview.getholder (); Holder.settype (surfaceholder.surface_type_push_buffers); Holder.addcallback (this); Callback interface}private final void StartorientationchangelisteNER () {moreventlistener = new Orientationeventlistener (this) {@Overridepublic void onorientationchanged (int rotation) { if (((rotation >= 0) && (rotation <= 45)) | | (Rotation >= 315) | | ((rotation >= 135) && (rotation <= 225))) {//portraitmcurrentorientation = true; LOG.I (TAG, "vertical screen");} else if (((Rotation >) && (Rotation < 135)) | | ((Rotation > 225) && (Rotation < 315))) {//landscapemcurrentorientation = false; LOG.I (TAG, "horizontal screen");}}; Moreventlistener.enable ();} @Overridepublic void OnClick (View v) {//Click to take photo switch (V.getid ()) {case R.id.take_photo:mcamera.takepicture (Mshutter, NULL, mJpeg); break;default:break;}} @Overridepublic void Surfacechanged (surfaceholder holder, int format, int width,int height) {// Surfaceview size changes (this method is also called on the first display on the screen), initialize the Mcamera parameter, start the camera preview parameters parameters = Mcamera.getparameters ();// Gets the parameter object of the Mcamera size largestsize = Getbestsupportedsize (parameters.getsupportedpreviewsizes ()); Parameters.setpreviewsize (LARgestsize.width, largestsize.height);//Set preview picture size largestsize = Getbestsupportedsize ( Parameters.getsupportedpicturesizes ());//Set Capture picture size parameters.setpicturesize (Largestsize.width, Largestsize.height); mcamera.setparameters (parameters); try {Mcamera.startpreview ();} catch (Exception e) {if (Mcamera ! = null) {mcamera.release (); mcamera = null;}}} @Overridepublic void surfacecreated (Surfaceholder holder) {//Surfaceview when created, establish contact if for camera and Surfaceview if (mcamera! = NULL) {try {mcamera.setpreviewdisplay (holder);} catch (IOException e) {e.printstacktrace ()}}} @Overridepublic void surfacedestroyed (Surfaceholder holder) {//Surfaceview destroy, Cancel camera preview if (Mcamera! = null) { Mcamera.stoppreview ();}} @SuppressLint ("Newapi") @Overridepublic void Onresume () {super.onresume ();//Turn on camera if (Build.VERSION.SDK_INT >= Build.version_codes. Gingerbread) {Mcamera = Camera.open (0);//i=0 indicates rear camera} Elsemcamera = Camera.open ();} @Overridepublic void OnPause () {super.onpause ();//Release Camera if (Mcamera! = null) {mcamera.release (); mcameRA = null;}} Private Size getbestsupportedsize (list<size> sizes) {///Fetch the largest sizesize largestsize = Sizes.get (0); int Largestarea = Sizes.get (0). Height * Sizes.get (0). Width;for (Size s:sizes) {int area = S.width * s.height;if (Area > L Argestarea) {Largestarea = Area;largestsize = s;}} return largestsize;}}
Showpicture.java
Package Com.example.testcamera;import Android.app.activity;import Android.graphics.bitmap;import Android.graphics.bitmapfactory;import Android.graphics.drawable.bitmapdrawable;import Android.os.Bundle;import Android.util.log;import Android.view.display;import Android.widget.imageview;public class ShowPicture extends Activity {private static final String TAG = "Showpicture";p rivate ImageView mpicture;public void onCreate (Bundle savedinst Ancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_show_picture); mPicture = ( ImageView) Findviewbyid (r.id.picture); String fileName = Getintent (). Getstringextra (Testcameraactivity.key_filename);//Picture Path LOG.I (TAG, fileName); String path = Getfilestreampath (FileName). GetAbsolutePath ();D isplay Display = Getwindowmanager (). Getdefaultdisplay () ; Display size Float destwidth = display.getwidth (), Float destheight = Display.getheight ();//read local picture size bitmapfactory.options options = new Bitmapfactory.options (); options.injustdecodebounds = true; BitMapfactory.decodefile (path, options);//set to True,options still corresponds to this picture, but the decoder will not allocate memory for this picture float srcwidth = options.outwidth; float Srcheight = Options.outheight;int insamplesize = 1;if (srcheight > Destheight | | srcwidth > Destwidth) {//when figure if (Srcwidth > Srcheight) {insamplesize = Math.Round (srcheight/destheight);} else {insamplesize = Math.roun, the length of the piece is wider than the D (srcwidth/destwidth);}} options = new Bitmapfactory.options (); options.insamplesize = Insamplesize; Bitmap Bitmap = bitmapfactory.decodefile (path, options); Bitmapdrawable bdrawable = new Bitmapdrawable (Getresources (), bitmap); mpicture.setimagedrawable (bdrawable);} @Overridepublic void OnDestroy () {if (!) ( Mpicture.getdrawable () instanceof bitmapdrawable)) return;//release bitmap occupied space bitmapdrawable B = (bitmapdrawable) Mpicture.getdrawable (); B.getbitmap (). Recycle (); mpicture.setimagedrawable (null);}}
SOURCE download
Android Camera+surfaceview for custom photography