在App中使用Camera的兩種方式
- 調用系統相機、或者是具有相機功能的應用
- 自定義相機
調用系統相機
調用系統相機很簡單,直接只用Intent就可以了
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivity(intent);
不過這種調用方式,主導權全在系統相機里,也無法獲得相機所拍的照片。所以可簡單調整下,使用startActivityForResult的方式調用,然后在onActivityResult中接收數據。
public static final int REQ_1 = 1;
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQ_1);
@Overrideprotected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK){
if(requestCode == REQ_1){
//為防止數據溢出,該data返回的是縮略圖
Bundle bundle = data.getExtras();//包含相機返回的照片的二進制流
Bitmap bitmap = (Bitmap) bundle.get("data");
img.setImageBitmap(bitmap);
}
}
}
因為Bitmap數據過大,所以Android系統為了防止數據溢出,返回的data是個縮略圖。如果想獲得原圖,可修改照片存放到指定路徑,然后直接獲取SD下的圖片。
public static final int REQ_2 = 2;
private String filePath;
filePath = Environment.getExternalStorageDirectory().getPath();
filePath = filePath + "/" + "temp.png";
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
Uri photoUri = Uri.fromFile(new File(filePath));
intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);//將系統拍的照片,存放到自定路徑
startActivityForResult(intent, REQ_2);
//在onActivityResult中處理
FileInputStream fis = null;
try {
fis = new FileInputStream(filePath);
Bitmap bitmap = BitmapFactory.decodeStream(fis);
img.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}finally {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
使用這種方式獲取SD圖片時,有可能因為Bitmap過大而出現異常,可以根據需要將Bitmap壓縮下。
FileInputStream is = null;Bitmap bitmap = null;
BufferedInputStream bis = null;
try {
is = new FileInputStream(filePath);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 2;//長寬都調為原來的1/2
bis = new BufferedInputStream(is);
bitmap = BitmapFactory.decodeStream(bis, null, options);
img.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}finally {
try {
is.close();
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}