<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
2 . 設定 RequestCode
public static final int TAKE_PHOTO_IMAGE_CODE = 1234;
3 . 開啟相機
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
startActivityForResult(intent, TAKE_PHOTO_IMAGE_CODE);
4 . 接收拍照結果
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == TAKE_PHOTO_IMAGE_CODE)
{
//Check if data in not null
if (data != null)
{
Bitmap bitmap = (Bitmap)data.getExtras().get("data");
imageView.setImageBitmap(bitmap);
}
}
}
5 . 如果要有儲存照片功能
public static final String FileName = "Hello";
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//Check that request code matches ours:
if (requestCode == TAKE_PHOTO_IMAGE_CODE)
{
// 建立資料夾
File imageStorageFolder =
new File(Environment.getExternalStorageDirectory()+File.separator + FileName);
if (!imageStorageFolder.exists())
{
imageStorageFolder.mkdirs();
Log.d(TAG , "Folder created at: "+imageStorageFolder.toString());
}
//Check if data in not null
if (data != null)
{
String imageName = "image";
String fileNameExtension = ".jpg";
File sdCard = Environment.getExternalStorageDirectory();
String strImageStorageFolder = File.separator + FileName + File.separator;
File destinationFile =
new File(sdCard, strImageStorageFolder + imageName + fileNameExtension);
Log.d(TAG, "the destination for image file is: " + destinationFile );
if (data.getExtras() != null)
{
Bitmap bitmap = (Bitmap)data.getExtras().get("data");
//判斷照片為橫向或者為直向,並進入ScalePic判斷圖片是否要進行縮放
if(bitmap.getWidth()>bitmap.getHeight())
ScalePic(bitmap,mPhone.heightPixels);
else
ScalePic(bitmap,mPhone.widthPixels);
try
{
FileOutputStream out = new FileOutputStream(destinationFile);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
}
catch (Exception e)
{
Log.e(TAG, "ERROR:" + e.toString());
}
}
}
}
}
private void ScalePic(Bitmap bitmap,int phone)
{
//縮放比例預設為1
float mScale = 1 ;
//如果圖片寬度大於手機寬度則進行縮放,否則直接將圖片放入ImageView內
if(bitmap.getWidth() > phone )
{
//判斷縮放比例
mScale = (float)phone/(float)bitmap.getWidth();
Matrix mMat = new Matrix() ;
mMat.setScale(mScale, mScale);
Bitmap mScaleBitmap = Bitmap.createBitmap(bitmap,
0,
0,
bitmap.getWidth(),
bitmap.getHeight(),
mMat,
false);
imageView.setImageBitmap(mScaleBitmap);
}
else imageView.setImageBitmap(bitmap);
}
參考資料 : Android : Use Camera Activity for Thumbnail and FullSize Image
參考資料 : 【Android】開啟相機-照相功能與相簿-相片集並讀取相片匯入至程式
歡迎轉載,請註明出處。
沒有留言:
張貼留言