2013-05-21 50 views
0

我已经提出了一个应用程序来捕捉相机的照片。如何从Android摄像头捕捉图像?

我已经创建了两个活动:在Activity1中有一个Button,点击时启动相机。当图像被捕获时,它被传递给Activity2。

但是,当我运行应用程序并启动Activity1(使用一个按钮),然后单击按钮启动摄像头时,它会弹出一个窗口,显示消息“不幸,摄像头已停止”。日志猫或控制台中没有错误。

任何人都可以帮助我。请。非常感谢。

回答

1

看看这篇博客写我正好在这个题目:

Use Camera Activity for Thumbnail and Full Size Image

它可以帮助你找出你的问题。

的步骤是:

所以首先像以前一样,我们需要创建一个静态INT这将是我们

public static final int CAPTURE_IMAGE_FULLSIZE_ACTIVITY_REQUEST_CODE = 1777; 

2.接下来我们火的意图开始对于结果的活动:

Intent intent = new Intent("android.media.action.IMAGE_CAPTURE"); 
File file = new File(Environment.getExternalStorageDirectory()+File.separator + "image.jpg"); 
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file)); 
startActivityForResult(intent, CAPTURE_IMAGE_FULLSIZE_ACTIVITY_REQUEST_CODE); 

在这里,我们实际上是传递一个URI作为一个额外的意图,以便将图像保存在这个位置,当它将被采取。

最后,我们将得到的结果onActivityResult

protected void onActivityResult(int requestCode, int resultCode, Intent data) 
{ 
    //Check that request code matches ours: 
    if (requestCode == CAPTURE_IMAGE_FULLSIZE_ACTIVITY_REQUEST_CODE) 
    { 
     //Get our saved file into a bitmap object: 
     File file = new File(Environment.getExternalStorageDirectory()+File.separator + "image.jpg"); 
     Bitmap bitmap = decodeSampledBitmapFromFile(file.getAbsolutePath(), 1000, 700); 
    } 
} 

decodeSampledBitmapFromFile方法是:

public static Bitmap decodeSampledBitmapFromFile(String path, int reqWidth, int reqHeight) 
{ // BEST QUALITY MATCH 

    //First decode with inJustDecodeBounds=true to check dimensions 
    final BitmapFactory.Options options = new BitmapFactory.Options(); 
    options.inJustDecodeBounds = true; 
    BitmapFactory.decodeFile(path, options); 

    // Calculate inSampleSize, Raw height and width of image 
    final int height = options.outHeight; 
    final int width = options.outWidth; 
    options.inPreferredConfig = Bitmap.Config.RGB_565; 
    int inSampleSize = 1; 

    if (height > reqHeight) 
    { 
     inSampleSize = Math.round((float)height/(float)reqHeight); 
    } 
    int expectedWidth = width/inSampleSize; 

    if (expectedWidth > reqWidth) 
    { 
     //if(Math.round((float)width/(float)reqWidth) > inSampleSize) // If bigger SampSize.. 
     inSampleSize = Math.round((float)width/(float)reqWidth); 
    } 

    options.inSampleSize = inSampleSize; 

    // Decode bitmap with inSampleSize set 
    options.inJustDecodeBounds = false; 

    return BitmapFactory.decodeFile(path, options); 
} 

不要忘记将培训相关相机权限添加到清单文件:

<uses-permission android:name="android.permission.CAMERA" /> 
<uses-feature android:name="android.hardware.camera" /> 
<uses-feature android:name="android.hardware.camera.autofocus" /> 
1

确保添加权限

<uses-permission android:name="android.permission.CAMERA" /> 
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 

如果不解决问题的youre妳比应该告诉我们您选择的代码

+0

它不需要任何权限,如果他调用本机相机应用。拍摄照片的是相机,而不是自己的应用程序。如果您想在相机api上访问,则需要相机权限。 – Jarvis

+0

摄像头许可他不需要,但是我自己正在使用摄像头应用程序,并且我发现了一些帖子,他们说由于某些设备的问题而添加权限。从来没有可以测试这个,但只是添加它是肯定的。他需要能够保存他的图像,不是吗? –

1

你,如果你使用startActiviyForResult()只需要一个活动:

贝洛,一个简单的源代码用于从相机应用拍摄照片,您需要使用startActiviyForResult()启动Activity并从相机应用程序接收该意图。

Java源代码:

package com.example.coursandroid_chp; 

    import android.os.Bundle; 
    import android.provider.MediaStore; 
    import android.app.Activity; 
    import android.content.Intent; 
    import android.graphics.Bitmap; 
    import android.util.Log; 
    import android.view.Menu; 
    import android.view.View; 
    import android.view.View.OnClickListener; 
    import android.widget.Button; 
    import android.widget.ImageView; 

    public class MediaActivity extends Activity { 

     private static final String TAG = "MediaActivity"; 
     private static final int REQUEST_IMAGE_CAPTURE = 1; 
     private static final int REQUEST_VIDEO_CAPTURE = 2; 
     private Button mCameraPhotoButton; 
     private Button mCameraVideoButton; 
     private ImageView mPhotoImageView; 

     @Override 
     protected void onCreate(Bundle savedInstanceState) { 
      super.onCreate(savedInstanceState); 
      setContentView(R.layout.screen_media); 
      mCameraPhotoButton = (Button) this.findViewById(R.id.screen_media_camera_photo_button); 
      mCameraVideoButton = (Button) this.findViewById(R.id.screen_media_camera_video_button); 
      mPhotoImageView = (ImageView) this.findViewById(R.id.screen_media_photo_imageview); 
      mCameraPhotoButton.setOnClickListener(onClickListener); 
      mCameraVideoButton.setOnClickListener(onClickListener); 

     } 

     @Override 
     public boolean onCreateOptionsMenu(Menu menu) { 
      // Inflate the menu; this adds items to the action bar if it is present. 
      getMenuInflater().inflate(R.menu.screen_media, menu); 
      return true; 
     } 

     private OnClickListener onClickListener = new OnClickListener() { 

      @Override 
      public void onClick(View v) { 
       switch (v.getId()) { 
       case R.id.screen_media_camera_photo_button: 
        startActivityForResult(new Intent(MediaStore.ACTION_IMAGE_CAPTURE), REQUEST_IMAGE_CAPTURE); 
        break; 
       case R.id.screen_media_camera_video_button: 
        startActivityForResult(new Intent(MediaStore.ACTION_VIDEO_CAPTURE), REQUEST_VIDEO_CAPTURE); 
        break; 
       } 
      } 
     }; 

     @Override 
     protected void onActivityResult(int requestCode, int resultCode, Intent data) { 

      if (requestCode == REQUEST_IMAGE_CAPTURE) { 

       switch (resultCode) { 
       case RESULT_OK: 
        Log.v(TAG, "Picture taken! :)"); 
        if (data != null) { 
         Bitmap bitmap = data.getParcelableExtra("data"); 
         mPhotoImageView.setImageBitmap(bitmap); 
        } 
        break; 
       case RESULT_CANCELED: 
        Log.v(TAG, "Picture canceled! :("); 
        break; 
       } 
      } else if (requestCode == REQUEST_VIDEO_CAPTURE) { 

       switch (resultCode) { 
       case RESULT_OK: 
        Log.v(TAG, "Video taken! :)"); 
        break; 
       case RESULT_CANCELED: 
        Log.v(TAG, "Video canceled! :("); 
        break; 
       } 
      } 

     } 

    } 



Xml layout file 


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
      xmlns:tools="http://schemas.android.com/tools" 
      android:layout_width="match_parent" 
      android:layout_height="match_parent" 
      tools:context=".MediaActivity" > 

      <Button 
       android:id="@+id/screen_media_camera_photo_button" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:layout_alignParentTop="true" 
       android:layout_centerHorizontal="true" 
       android:layout_marginTop="32dp" 
       android:text="Camera photo" /> 

      <Button 
       android:id="@+id/screen_media_camera_video_button" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:layout_below="@+id/screen_media_camera_photo_button" 
       android:layout_centerHorizontal="true" 
       android:layout_marginTop="28dp" 
       android:text="Camera video" /> 

      <ImageView 
       android:id="@+id/screen_media_photo_imageview" 
       android:layout_width="match_parent" 
       android:layout_height="match_parent" 
       android:layout_below="@+id/screen_media_camera_video_button" 
       android:layout_centerHorizontal="true" 
       android:layout_marginLeft="32dp" 
       android:layout_marginTop="57dp" 
       android:src="@drawable/ic_bitmap" /> 

     </RelativeLayout> 
1

试试下面的代码:

package com.example.sample1; 


import java.io.BufferedOutputStream; 
import java.io.File; 
import java.io.FileOutputStream; 



import android.os.Bundle; 
import android.os.Environment; 
import android.os.StatFs; 
import android.provider.MediaStore; 
import android.app.Activity; 
import android.content.Intent; 
import android.graphics.Bitmap; 
import android.view.Menu; 
import android.view.MenuInflater; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.widget.Button; 
import android.widget.ImageView; 

public class CapturePhotoSample1 extends Activity implements OnClickListener 
{ 


    public static final int TAKE_PHOTO=1; 
    ImageView imageView=null; 

    private File folder; 
    String imageFileName=null; 


    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_capture_photo_sample1); 

     Button button=(Button)this.findViewById(R.id.capture_button); 
     button.setOnClickListener(this); 
     button=null; 

     imageView=(ImageView)this.findViewById(R.id.image_view1); 

     folder = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES)+ "/sample1/"); 
     if (!folder.exists()) { 
      folder.mkdir(); 
     } 


    } 

    private void dispatchTakePictureIntent(int actionCode) { 
     Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
     startActivityForResult(takePictureIntent,actionCode); 

    } 

    @Override 
    public void onClick(View v) { 
     // TODO Auto-generated method stub 

     int id=v.getId(); 

     if(id==R.id.capture_button) 
      this.dispatchTakePictureIntent(TAKE_PHOTO); 
    } 

    @Override 

    public boolean onCreateOptionsMenu(Menu menu) { 

     MenuInflater inflater = getMenuInflater(); 

     inflater.inflate(R.menu.menu1, menu); 

     return true; 

    } 

    public void handleCameraPhoto(Intent intent) 
    { 
     Bundle extras=intent.getExtras(); 
     Bitmap bitmap=(Bitmap)extras.get("data"); 
     this.imageView.setImageBitmap(bitmap); 

     if(this.isExternalStorageAvailable()) 
     { 
      this.imageFileName="img_"+SDUtil.now(-1)+".png"; 

        /*SDUtil.now() is our own library.It is for creating file name with respect to data and time.IF u copy the hole program means sdutil shows error.For that you write a logic for creating a file name. */ 

      String path=folder+"/"+this.imageFileName; 

      FileOutputStream fos=null; 
      BufferedOutputStream bos=null; 

      try 
      { 
       fos=new FileOutputStream(path); 
       bos=new BufferedOutputStream(fos); 
       bitmap.compress(Bitmap.CompressFormat.PNG, 40, bos); 
      } 
      catch(Exception ex) 
      { 
       ex.printStackTrace(); 
      } 

      if(bos!=null) 
      { 
       try 
       { 
        bos.flush(); 
        //bos.close(); 
       } 
       catch(Exception ex) 
       { 
        ex.printStackTrace(); 
       } 
      } 

      if(bos!=null) 
      { 
       try 
       { 
        bos.close(); 
       } 
       catch(Exception ex) 
       { 
        ex.printStackTrace(); 
       } 
      } 


      if(fos!=null) 
      { 
       try 
       { 
        fos.close(); 
       } 
       catch(Exception ex) 
       { 
        ex.printStackTrace(); 
       } 

      } 

      bos=null; 
      fos=null; 

     } 
    } 

    @Override 
    protected void onActivityResult(int requestCode, int resultCode, Intent data) 
    { 
     super.onActivityResult(requestCode, resultCode, data); 

     if(resultCode==Activity.RESULT_OK) 
     { 
      if(requestCode==TAKE_PHOTO) 
      { 
       handleCameraPhoto(data); 
      } 
     } 


    } 

    private boolean isExternalStorageAvailable() { 

     StatFs stat = new StatFs(Environment.getExternalStorageDirectory() 
       .getPath()); 
     double sdAvailSize = (double) stat.getAvailableBlocks() 
       * (double) stat.getBlockSize(); 
     // One binary gigabyte equals 1,073,741,824 bytes. 
     double mbAvailable = sdAvailSize/1048576; 

     String state = Environment.getExternalStorageState(); 
     boolean mExternalStorageAvailable = false; 
     boolean mExternalStorageWriteable = false; 

     if (Environment.MEDIA_MOUNTED.equals(state)) { 
      // We can read and write the media 
      mExternalStorageAvailable = mExternalStorageWriteable = true; 
     } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) { 
      // We can only read the media 
      mExternalStorageAvailable = true; 
      mExternalStorageWriteable = false; 
     } else { 
      // Something else is wrong. It may be one of many other states, but 
      // all we need 
      // to know is we can neither read nor write 
      mExternalStorageAvailable = mExternalStorageWriteable = false; 
     } 

     if (mExternalStorageAvailable == true 
       && mExternalStorageWriteable == true && mbAvailable > 10) { 
      return true; 
     } else { 
      return false; 
     } 
    } 

} 
+0

此行显示错误(import com.ivy.lib.SDUtil;)。如何导入SDTUtil? – TJM

+0

Tazeen我更新了我的答案,现在检查它 –

1

检查下面的代码在你的活动

protected void onActivityResult(int requestCode, int resultCode, Intent data) 
{ 
    //Check that request code matches ours: 
    if (requestCode == CAPTURE_IMAGE_THUMBNAIL_ACTIVITY_REQUEST_CODE) 
    { //Check if your application folder exists in the external storage, if not create it: 
     your code should be here..... 
     //Check if data in not null and extract the Bitmap: 
     if (data != null) 
     { 
      String filename = "image"; 
      String fileNameExtension = ".jpg"; 
      File sdCard = Environment.getExternalStorageDirectory(); 
      String imageStorageFolder = File.separator+"Your application Folder"+File.separator; 
      File destinationFile = new File(sdCard, imageStorageFolder + filename + fileNameExtension); 
      Log.d(TAG, "the destination for image file is: " + destinationFile); 
      if (data.getExtras() != null) 
      { 
       Bitmap bitmap = (Bitmap)data.getExtras().get("data"); 
       try 
       { 
        FileOutputStream out = new FileOutputStream(destinationFile); 
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, out); 
        out.flush(); 
        out.close(); 
       } 
       catch (Exception e) 
       { 
        Log.e(TAG, "ERROR:" + e.toString()); 
       } 
      }}}