public class PhotoTest extends Activity { private ImageView iv; private Bitmap bitmap; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.photo); iv = (ImageView) findViewById(R.id.photo); } public void pai(View view){ //调用系统拍照功能的Action Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); //跳转到拍照的Action startActivityForResult(intent, 0); } //startActivityForResult(intent, 0)所返回数据的方法 @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { // TODO Auto-generated method stub if(data!=null){ //获取拍摄的图片 bitmap = (Bitmap) data.getExtras().get("data"); //设置图片的两种方式: //第一种方式:直接调用setImageBitmap方法把bitmap对象放进去 //iv.setImageBitmap(bitmap); //第二种方式:通过BitmapDrawable把bitmap对象转为drawable类型,再调用setImageDrawable()方法设置ImageView显示的图片 BitmapDrawable db = new BitmapDrawable(bitmap); Drawable drawable = db; iv.setImageDrawable(drawable); try { OutputStream os = new FileOutputStream(Environment.getExternalStorageDirectory().getAbsolutePath()+ "/2015011301.jpg"); //把图片对象(bitmap)内容压缩为字节 放入写流 bitmap.compress(CompressFormat.JPEG, 100, os); os.flush(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } super.onActivityResult(requestCode, resultCode, data); } }
.xml代码:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:orientation="vertical" > <Button android:id="@+id/button1" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="拍照" android:onClick="pai"/> <ImageView android:id="@+id/photo" android:layout_width="match_parent" android:layout_height="match_parent" /> </LinearLayout>
时间: 2024-11-05 18:28:56