安卓呼叫相機拍照并回傳預覽及相關型別換(略縮圖,畫質糊)原圖預覽參考傳送門
- 一、demo預覽
- 二、xml代碼和activity簡單代碼描述,
- 三、順便寫幾個轉換工具方法吧
- 今年主要在忙新專案,安卓也有很一段時間沒有寫了,安卓相關的博客也沒有更新,今天來簡單分享一下一個小需求吧,
- 寫在之后,由于此方法回傳的道德bitmap是被壓縮過的,預覽圖片會很糊,不滿足需求固又嘗試了一個新的辦法拍斬訓傳預覽!
- 》》》安卓呼叫系統相機拍照并回傳預覽(原圖預覽)《《《
一、demo預覽
先簡單寫一個demo,效果如圖,點擊拍照以后回傳圖片覆寫在指定位置,

點擊拍照以后直接呼叫相機

拍照成功后回傳顯示預覽

以上便是demo預覽,
二、xml代碼和activity簡單代碼描述,
布局檔案代碼:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="10sp"
android:orientation="vertical">
<ImageView
android:id="@+id/photoImageView"
android:layout_width="match_parent"
android:layout_height="400dp"
android:layout_marginTop="10sp"
android:layout_marginBottom="20sp"
android:layout_weight="1"
android:src="@drawable/boundary" />
<Button
android:id="@+id/takePhotoButton"
android:layout_width="200sp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1"
android:background="@drawable/button_shape"
android:onClick="onTakePhotoButtonClicked"
android:text="拍 照"
android:textSize="23sp" />
</LinearLayout>
</android.support.constraint.ConstraintLayout>
Activity代碼:
//初始化activity
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.take_photo);
photoImageView = (ImageView)findViewById(R.id.photoImageView);
}
//監聽拍照按鈕,點擊拍照呼叫相機
public void onTakePhotoButtonClicked(View v){
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 2);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 2 && resultCode == RESULT_OK && null != data) {
Bundle bundle = data.getExtras();
//intent跳轉攜帶引數回傳,data轉化成Bitmap,獲得的是個略縮圖
photo = (Bitmap) bundle.get("data");
//將預覽圖放進預覽框
photoImageView.setImageBitmap(photo);
photoBytes = CommonCode.bitmapToByte(photo);
}
super.onActivityResult(requestCode, resultCode, data);
}
以上便大功告成
三、順便寫幾個轉換工具方法吧
Bitmap旋轉角度:
public static Bitmap rotateBitmap(Bitmap origin, float alpha) {
if (origin == null) {
return null;
}
int width = origin.getWidth();
int height = origin.getHeight();
Matrix matrix = new Matrix();
matrix.setRotate(alpha);
// 圍繞原地進行旋轉
Bitmap newBM = Bitmap.createBitmap(origin, 0, 0, width, height, matrix, false);
if (newBM.equals(origin)) {
return newBM;
}
origin.recycle();
return newBM;
}
Bitmap轉byte[]
public static byte[] bitmapToByte(Bitmap bitmap){
int bytes = bitmap.getByteCount();
ByteBuffer buf = ByteBuffer.allocate(bytes);
bitmap.copyPixelsToBuffer(buf);
return buf.array();
}
最近忙著離職、作業交接和搬家,一直沒時間來寫博客了,今天遇到個簡單的功能,簡單分享記錄下這個demo吧,希望對需要的小伙伴有所幫助!2020結束了,博主這邊作業也算是告一段落了,現在已經2021了,希望小伙伴們在新的一年里升職加薪,技術進步!過幾天來分享下前段時間遇到的面筋吧,
- 一直(只)不務正業的Java后端
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/246641.html
標籤:其他
