1. 程式人生 > >android拍照後圖片路徑的獲取(解決不同手機存在拍照後旋轉的問題)

android拍照後圖片路徑的獲取(解決不同手機存在拍照後旋轉的問題)

呼叫拍照功能:

Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(openCameraIntent, TAKE_PICTURE);

該方法在拍照後自動呼叫:
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case TAKE_PICTURE:
			if (StaticData.photoList.size() < MAXSISE && resultCode == RESULT_OK) {				
				PhotoInfo photo = new PhotoInfo();
				//拍照後圖片的絕對路徑
				String videoPath = null;
				 if (data != null) {  
		                // 取得返回的Uri,基本上選擇照片的時候返回的是以Uri形式,但是在拍照中有得機子呢Uri是空的,所以要特別注意  
		                Uri uri = data.getData();  
		                /*
		                 * 返回的Uri不為空時,那麼圖片資訊資料都會在Uri中獲得。如果為空,那麼我們就進行下面的方式獲取  
		                 * 拍照後儲存到相簿的手機
		                 */
		                if (uri != null) {  
		                	Cursor cursor = this.getContentResolver().query(uri, null,
		    						null, null, null);
		    			if (cursor.moveToFirst()) {
		    				videoPath = cursor.getString(cursor.getColumnIndex("_data"));// 獲取絕對路徑
		    			}
		                }
		                //小米等 拍照後不儲存的手機
		                else {
		                	Bitmap bm = (Bitmap) data.getExtras().get("data");
		                	File file = getFile(bm);
		                	videoPath = file.getPath()
				}
		     <span style="white-space:pre">	</span>}  			
		}
		break;
		}
	}

接下來是getFile方法:將bitmap轉化為File
private File getFile(Bitmap bitmap){
		String pictureDir = "";
		FileOutputStream fos = null;
		BufferedOutputStream bos = null;
		ByteArrayOutputStream baos = null;
		File file = null;
		try {
			baos = new ByteArrayOutputStream();
			bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
			byte[] byteArray = baos.toByteArray();
			String saveDir = Environment.getExternalStorageDirectory()
					+ "/dreamtownImage";
			File dir = new File(saveDir);
			if (!dir.exists()) {
				dir.mkdir();
			}
			file = new File(saveDir, userId+DTCalTime.getMTime()+DTCalTime.generateShortUuid()+".jpg");
			file.delete();
			if (!file.exists()) {
				file.createNewFile();
			}
			fos = new FileOutputStream(file);
			bos = new BufferedOutputStream(fos);
			bos.write(byteArray);
			pictureDir = file.getPath();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (baos != null) {
				try {
					baos.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			if (bos != null) {
				try {
					bos.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			if (fos != null) {
				try {
					fos.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}


		return file;
	}