Android's camera Usage example detailed _android

Source: Internet
Author: User
Tags file permissions

This example describes the camera usage of Android. Share to everyone for your reference. Specifically as follows:

1. About the preview of the difference of 90 degrees

Cause analysis

After verification and experimentation, it can be confirmed that the Android SDK (Android.hardware.Camera) may not normally use the vertical screen (portrait layout) to load the camera, when the camera is loaded in vertical mode will produce the following conditions:

①. Camera imaging left-leaning 90 degrees (tilt);

②. Camera imaging aspect ratio is not correct (loss ratio).

The reason is "approximate" because it may be solved by some more complicated means. If the above set up, then why the vertical screen is not normal imaging is very obvious. Why is this happening, please look at the following research analysis.

In general, the camera must be landscape layout (horizontal screen), you can prove that the first to write a camera (as long as you can preview), if manifest activity does not join android:screenorientation= "Landscape", that is, the default android:screenorientation= "Portrait" (vertical screen), the camera preview will appear left-leaning 90 degrees phenomenon, and loss ratio. The reason for this (I suspect) is that the camera control map is fixed by the Android bottom, is landscape, and produces a 320*480-like image, and if replaced by portrait, the camera still produces a 320*480 image, Then the corresponding to put into a 480*320 screen, obviously will be lost, and then according to the vertical, horizontal screen rules, produced a left-leaning 90-degree situation. To further substantiate my assumption of the reason for the loss of the ratio, the surfaceview that I loaded in my camera became 320*213, which is probably (320:213) *1.5= (480:320), and the image of the result as desired to form a left-leaning but no loss of ratio, confirms my opinion.

It can be seen from the view that the left is because of the camera mapping, and the loss ratio is due to the pixel proportional mapping generated.

Solution

No good solution, only force horizontal screen, record code added

Copy Code code as follows:
Setrequestedorientation (Activityinfo.screen_orientation_landscape);

No good solution, only force horizontal screen, record code added
Copy Code code as follows:
android:screenorientation= "Landscape"

2. About the shot out of the image can not be correctly imaged, such as green screen, red and green, overlapping and so on

Cause analysis

Some mobile phones do not support parameter.setpicturesize (width,height), Parameters.setpreviewsize (Width,height) methods, for compatibility recommendations do not set these two methods.

Attached: Complete Sample code:

Main.xml Layout file:

<?xml version= "1.0" encoding= "Utf-8"?> <linearlayout xmlns:android= "http://schemas.android.com/apk/res/" Android "Android:layout_width=" Fill_parent "android:layout_height=" fill_parent "android:orientation=" vertical " > <linearlayout xmlns:android= "http://schemas.android.com/apk/res/android" android:layout_width= "Fill_ Parent "android:layout_height=" fill_parent "android:orientation=" vertical "android:layout_weight=" 2 "> <Surfa 
 Ceview android:id= "@+id/surfaceview" android:layout_width= "fill_parent" android:layout_height= "Fill_parent"/> </LinearLayout> <linearlayout xmlns:android= "Http://schemas.android.com/apk/res/android" Android:layout_ Width= "Fill_parent" android:layout_height= "wrap_content" android:orientation= "Horizontal" android:layout_weight= " 1 "android:background=" @android: Color/white "android:layout_gravity=" center "> <imagebutton android:layout_ Width= "Fill_parent" android:layout_height= "80dip" andRoid:id= "@+id/btntakepicture" android:layout_gravity= "center" android:textsize= "30dip" android:layout_weight= "1" android:src= "@drawable/btn_take_pic"/> <imagebutton android:layout_width= "Fill_parent" Android:layout_heigh t= "80dip" android:id= "@+id/btnautofocus" android:layout_gravity= "center" android:textsize= "30dip" Android:layo ut_weight= "1" android:src= "@drawable/btn_auto_focus"/> </LinearLayout> </LinearLayout>

Second, mainactivity camera core code:

Package cn.itcast.takepicture;
Import Java.io.File;
Import Java.io.FileOutputStream;
Import android.app.Activity;
Import Android.content.pm.ActivityInfo;
Import Android.graphics.Bitmap;
Import Android.graphics.BitmapFactory;
Import Android.graphics.Matrix;
Import Android.graphics.PixelFormat;
Import Android.graphics.Bitmap.CompressFormat;
Import Android.hardware.Camera;
Import Android.hardware.Camera.PictureCallback;
Import Android.os.Bundle;
Import android.os.Environment;
Import Android.view.SurfaceHolder;
Import Android.view.SurfaceView;
Import Android.view.View;
Import Android.view.Window;
Import Android.view.WindowManager;
Import Android.view.SurfaceHolder.Callback;
Import Android.widget.ImageButton;
 public class Mainactivity extends activity {private ImageButton btntakepicture = null;
 Private ImageButton btnautofocus = null;
 Private Camera Camera = null;
  @Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Set Window caption RequestwiNdowfeature (Window.feature_no_title);
  Horizontal screen setrequestedorientation (activityinfo.screen_orientation_landscape); Full screen displays GetWindow (). SetFlags (WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_
  fullscreen);
  When this window is visible to the user, keep the device open and keep the brightness unchanged.
  GetWindow (). Addflags (WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
  Setcontentview (R.layout.main);
  Surfaceview Surfaceview = (Surfaceview) this. Findviewbyid (R.id.surfaceview);
  Surfaceview.getholder (). SetType (Surfaceholder.surface_type_push_buffers); Surfaceview.getholder (). Setfixedsize (320, 240);
  Set resolution Surfaceview.getholder (). Addcallback (New Surfacecallback ());
  Btntakepicture = (ImageButton) Findviewbyid (r.id.btntakepicture);
  Btnautofocus = (ImageButton) Findviewbyid (R.id.btnautofocus);
  Btntakepicture.setonclicklistener (Onclicklistener);
 Btnautofocus.setonclicklistener (Onclicklistener);
 Private final View.onclicklistener Onclicklistener = new View.onclicklistener () {@Override public void OnClick (View v) {if (v = = btntakepicture) {if (camera!= null) camera.takepicture (NULL, NULL, n EW Takepicturecallback ());
 Take pictures} else if (v = = Btnautofocus) {if (camera!= null) camera.autofocus (null);//Focus}}}; Private Final class Surfacecallback implements Callback {private Boolean preview;/is previewing @Override public void s Urfacechanged (surfaceholder holder, int format, int width, int height) {} @Override public void surfacecreated (
    Surfaceholder holder) {try {camera = Camera.open ();
    Camera.parameters Parameters = Camera.getparameters (); Parameters.setpreviewframerate (5); 5 frames per second parameters.setpictureformat (pixelformat.jpeg);//Set the output format of the photo Parameters.set ("jpeg-quality", 85);//photo quality Cam
    Era.setparameters (parameters);
    Camera.setpreviewdisplay (holder);
    Camera.startpreview ();
   Preview = true;
   catch (Exception e) {e.printstacktrace (); }} @Override public void SurfacedeStroyed (Surfaceholder holder) {if (camera!= null) {if (preview) {Camera.stoppreview ();
    Preview = false;
    } camera.release (); camera = null; Remember to release}} private Final class Takepicturecallback implements Picturecallback {public void Onpicturetaken (byt
   e[] data, Camera Camera) {Bitmap Bitmap = bitmapfactory.decodebytearray (data, 0, data.length);
   Matrix matrix=new Matrix ();
   Set Zoom Matrix.postscale (0.5f, 0.5f);
   Bitmap=bitmap.createbitmap (bitmap, 0, 0, bitmap.getwidth (), Bitmap.getheight (), Matrix, True);
   File File = new file (Environment.getexternalstoragedirectory (), System.currenttimemillis () + ". jpg");
    try {fileoutputstream OutStream = new FileOutputStream (file);
    Bitmap.compress (Compressformat.jpeg, OutStream);
    Outstream.close ();
   Camera.startpreview ();
   catch (Exception e) {e.printstacktrace ();

 }
  }
 }
}

Manifest file:

<?xml version= "1.0" encoding= "Utf-8"?> <manifest xmlns:android= "http://schemas.android.com/apk/res/" Android "package=" Cn.itcast.takepicture "android:versioncode=" 1 "android:versionname=" 1.0 "> <application Andr oid:icon= "@drawable/icon" android:label= "@string/app_name" > <activity android:label= "@string/app_name" Droid:name= ". Mainactivity "> <intent-filter > <action android:name=" Android.intent.action.MAIN "/> <catego Ry android:name= "Android.intent.category.LAUNCHER"/> </intent-filter> </activity> </application&
 Gt &LT;USES-SDK android:minsdkversion= "7"/> <uses-permission android:name= "Android.permission.CAMERA"/> <
 !--Create and delete file permissions in SDcard--> <uses-permission android:name= "Android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/> <!--Write data permissions to SDcard--> <uses-permission android:name= "Android.permission.WRITE_EXTERNAL_STORAGE"/> < /manifest>

I hope this article will help you with your Android program.

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.