你好朋友我在我的项目中使用以下代码。
权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
XML 文件:-
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="Camera Test" />
<ImageView android:id="@+id/camera_image"
android:layout_width="wrap_content" android:layout_height="wrap_content" />
</LinearLayout>
JAVA文件:-
package com.demo.camera;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.widget.ImageView;
public class CameraTest extends Activity {
private static final int CAMERA_PIC_REQUEST = 1111;
private ImageView mImage;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.camera_test);
mImage = (ImageView) findViewById(R.id.camera_image);
//1
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA_PIC_REQUEST);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_PIC_REQUEST) {
//2
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
mImage.setImageBitmap(thumbnail);
//3
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
//4
File file = new File(Environment.getExternalStorageDirectory()+File.separator + "image.jpg");
try {
file.createNewFile();
FileOutputStream fo = new FileOutputStream(file);
//5
fo.write(bytes.toByteArray());
fo.close();
Intent intent=new Intent(this,Second.class);
startActivity(intent);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
当我使用此代码时,它还可以为我提供图像的预览,但是当我尝试导航到第二个活动时,我的应用程序挂起......但是,有时它会快速导航到第二个活动。请帮我解决问题。
此外,每次还会将其他文件添加到相机(DCIM)文件夹中,所以我该如何删除它。
谢谢和问候, onkar