Android多媒體之拍照

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>


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章