<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:android_custom="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Button
android:id="@+id/btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="btn" >
</Button>
<Button
android:id="@+id/btn2"
android:layout_below="@+id/btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="btn2" >
</Button>
<ImageView
android:id="@+id/img"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@+id/btn2" >
</ImageView>
</RelativeLayout>
public class MainActivity extends Activity implements OnClickListener {
private static final int REQUEST_CODE_IMAGE_CATURE = 0x11;
private static final int REQUEST_CODE_IMAGE_CATURE_SAVE = 0x12;
ImageView img;
String imgPath;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.paomadeng);
img = (ImageView) findViewById(R.id.img);
Button btn = (Button) findViewById(R.id.btn);
Button btn2 = (Button) findViewById(R.id.btn2);
btn.setOnClickListener(this);
btn2.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if (v.getId() == R.id.btn) {
takePicture();
} else if (v.getId() == R.id.btn2) {
savePicture();
}
}
public void takePicture() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CODE_IMAGE_CATURE );
}
public void savePicture() {
// File.pathSeparator换成这个会出现问题
imgPath = Environment.getExternalStorageDirectory() + File.separator + "tmp.png";
File file = new File(imgPath);
if (file.exists()) {
file.delete();
}
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
Uri imgUri = Uri.fromFile(file);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imgUri);
startActivityForResult(intent, REQUEST_CODE_IMAGE_CATURE_SAVE );
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != Activity.RESULT_OK) {
return;
}
if (requestCode == REQUEST_CODE_IMAGE_CATURE) {
Bundle bundle = data.getExtras();
/**
* 获取拍照的数据,注意此时还没有生成相关的图片文件
* 还有就是这里获取的bitmap,其实仅仅是缩略图,并不是原始的数据。
*/
Bitmap bitmap = bundle.getParcelable("data");
img.setImageBitmap(bitmap);
} else if (requestCode == REQUEST_CODE_IMAGE_CATURE_SAVE) {
try {
FileInputStream fis = new FileInputStream(new File(imgPath));
// 从文件输入流中获取bitmap对象
Bitmap bitmap = BitmapFactory.decodeStream(fis);
img.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
}
注意:需要加入相关的权限。
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>