调用系统照相机,将照片保存在SDK上,并将照片赋值给一个ImageView显示出来
定义一个照相机类CameraOneActivityActivity,这个类中有一个Button一个ImageView
?
public class CameraOneActivityActivity extends Activity {@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.camera);Button button = (Button) findViewById(R.id.button);button.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);startActivityForResult(intent, 1);}});}@Overrideprotected void onActivityResult(int requestCode, int resultCode, Intent data) {super.onActivityResult(requestCode, resultCode, data);if (resultCode == Activity.RESULT_OK) {String sdStatus = Environment.getExternalStorageState();// 检测sd是否可用if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { Log.v("TestFile","SD card is not avaiable/writeable right now.");return;}Bundle bundle = data.getExtras();// 获取相机返回的数据,并转换为Bitmap图片格式Bitmap bitmap = (Bitmap) bundle.get("data");FileOutputStream b = null;File file = new File("/sdcard/myImage/");// 创建文件夹file.mkdirs();// 将时间命名为照片的名字String str = null;Date date = null;// 获取当前时间,进一步转化为字符串SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");date = new Date();str = format.format(date);//以时间的名字保存在SDK下,并且格式为JPGString fileName = "/sdcard/myImage/" + str + ".jpg";try {b = new FileOutputStream(fileName);// 把数据写入文件bitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);} catch (FileNotFoundException e) {e.printStackTrace();} finally {try {b.flush();b.close();} catch (IOException e) {e.printStackTrace();}}// 将图片显示在ImageView里((ImageView) findViewById(R.id.imageView)).setImageBitmap(bitmap);}}}
?
定义界面的camer.xml
?
<?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" > <Button android:id="@+id/button" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="点击启动相机" /> <ImageView android:id="@+id/imageView" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="#999999" /></LinearLayout>
?以上代码就是系统调用一个照相机并将照片赋值给一个ImageView,并将照片保存在Sd卡下?