android手機有自帶的照相機和圖庫,我們做的項目中有時用到上傳圖片到服務器,今天做了壹個項目用到這個功能,所以把我的代碼記錄下來和大家分享,第壹次寫博客希望各位大神多多批評。
首先上壹段調用android相冊和相機的代碼:
復制代碼
代碼如下:
Intent intent = new
Intent(MediaStore.ACTION_IMAGE_CAPTURE);//調用android自帶的照相機
photoUri =
MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
startActivityForResult(intent,
1);
復制代碼
代碼如下:
Intent i = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);//調用android的圖庫
startActivityForResult(i, 2);
復制代碼
代碼如下:
@Override
protected void
onActivityResult(int requestCode, int resultCode, Intent data) {
//完成照相後回調用此方法
super.onActivityResult(requestCode, resultCode, data);
case 1:
switch (resultCode) {
case Activity.RESULT_OK://照相完成點擊確定
String sdStatus = Environment.getExternalStorageState();
if
(!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 檢測sd是否可用
Log.v("TestFile", "SD card is not avaiable/writeable right now.");
return; }
Bundle bundle = data.getExtras();
Bitmap bitmap = (Bitmap)
bundle.get("data");// 獲取相機返回的數據,並轉換為Bitmap圖片格式
FileOutputStream b = null;
File file = new File("/sdcard/pk4fun/");
file.mkdirs();//
創建文件夾,名稱為pk4fun //
照片的命名,目標文件夾下,以當前時間數字串為名稱,即可確保每張照片名稱不相同。網上流傳的其他Demo這裏的照片名稱都寫死了,則會發生無論拍照多少張,後壹張總會把前壹張照片覆蓋。細心的同學還可以設置這個字符串,比如加上“IMG”字樣等;然後就會發現sd卡中myimage這個文件夾下,會保存剛剛調用相機拍出來的照片,照片名稱不會重復。
String str = null;
Date date = null;
SimpleDateFormat format = new
SimpleDateFormat("yyyyMMddHHmmss");// 獲取當前時間,進壹步轉化為字符串
date = new
Date(resultCode);
str = format.format(date);
String fileName =
"/sdcard/myImage/" + str + ".jpg";
sendBroadcast(fileName);
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();
}
} break;
case Activity.RESULT_CANCELED://
取消
break;
}
break;
case 2:
switch (resultCode) {
case
Activity.RESULT_OK: {
Uri uri = data.getData();
Cursor cursor =
mActivity.getContentResolver().query(uri, null,
null, null, null);
cursor.moveToFirst();
String imgNo = cursor.getString(0); // 圖片編號
String imgPath = cursor.getString(1); // 圖片文件路徑
String imgSize =
cursor.getString(2); // 圖片大小
String imgName = cursor.getString(3); // 圖片文件名
cursor.close();
// Options options = new BitmapFactory.Options();
//
options.inJustDecodeBounds = false;
// options.inSampleSize = 10;
//
Bitmap bitmap = BitmapFactory.decodeFile(imgPath, options);
}
break;
case Activity.RESULT_CANCELED:// 取消
break;
}
break;
}