我想知道如何使用Camera API捕捉照片并保存在相机文件夹或图库中。 请帮我一些示例代码。
由于 Monali
答案 0 :(得分:2)
试试这个...... 在你的onCreate()中添加它, String img = getImageName(); 现在在你的onCreate()中调用下面的方法,然后就可以了。
private void startCamera(String ImageName) {
Intent cameraIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
cameraIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT,
Uri.fromFile(new File(ImageName)));
startActivityForResult(cameraIntent, TAKE_PICTURE_WITH_CAMERA);
}
private String getImageName() {
String imgname = "";
String imgpath = "";
try {
imgname = String.format("%d.png", System.currentTimeMillis());
imgpath = strDirectoy + "/" + imgname;
File file = new File(strDirectoy);
boolean exists = file.exists();
if (!exists) {
boolean success = (new File(strDirectoy)).mkdir();
if (success)
Log.e("Directory Created", "Directory: " + strDirectoy
+ " created");
else
Log.e("Directory Creation","Directory Creation failed");
}
} catch (Exception e) {
e.printStackTrace();
}
return imgpath;
}
答案 1 :(得分:1)
在mainActivity中使用以下代码:
public class MainActivity extends Activity implements OnClickListener {
private static final int CAMERA_REQUEST= 1888;
private Button photoBtn;
private ImageView imageView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
photoBtn=(Button) findViewById(R.id.photobtn);
photoBtn.setOnClickListener(this);
imageView=(ImageView) findViewById(R.id.imageview);
}
@Override
public void onClick(View v) {
Intent cameraIntent=new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == CAMERA_REQUEST && resultCode == RESULT_OK){
Bitmap photo=(Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
}
}
}
- 在manifest.xml文件中添加以下行
<uses-feature android:name="android.hardware.camera" />
- 使用activity_main.xml布局是:
<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" >
<Button
android:id="@+id/photobtn"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:text="Open Camera" />
<ImageView
android:id="@+id/imageview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/photobtn"
android:layout_centerHorizontal="true"
android:src="@drawable/ic_launcher" />
</RelativeLayout>