更換使用者頭像 呼叫手機相簿或相機拍照 選擇圖片並裁剪
阿新 • • 發佈:2019-02-13
佈局 一個ImageView用來顯示處理後的頭像,兩個按鈕 分別為呼叫相機、呼叫手機相簿
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_test_choose_touxiang" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context="ht.testxyapp.com.testapp.activity.TestChooseTouxiang"> <ImageView android:id="@+id/imgTouXiang" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/circle_touxiang"/> <Button android:id="@+id/btnChooseFromCamera"android:layout_width="match_parent" android:layout_height="wrap_content" android:text="拍照上傳" /> <Button android:id="@+id/btnChooseFromXc" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="相簿上傳" /> </LinearLayout>
然後是主activity
public class TestChooseTouxiang extendsAppCompatActivity { private Button btnChooseFromCamera, getBtnChooseFromXc; private ImageView imgTouXiang; /* 頭像檔案 */ private static final String IMAGE_FILE_NAME = "temp_head_image.jpg"; /* 請求識別碼 */ private static final int CODE_GALLERY_REQUEST = 0xa0; private static final int CODE_CAMERA_REQUEST = 0xa1; private static final int CODE_RESULT_REQUEST = 0xa2; // 裁剪後圖片的寬(X)和高(Y),480 X 480的正方形。 private static int output_X = 600; private static int output_Y = 600; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_test_choose_touxiang); imgTouXiang = (ImageView) findViewById(R.id.imgTouXiang); btnChooseFromCamera = (Button) findViewById(R.id.btnChooseFromCamera); getBtnChooseFromXc = (Button) findViewById(R.id.btnChooseFromXc); btnChooseFromCamera.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { choseHeadImageFromCameraCapture(); } }); getBtnChooseFromXc.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { choseHeadImageFromGallery(); } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent intent) { // 使用者沒有進行有效的設定操作,返回 if (resultCode == RESULT_CANCELED) { Toast.makeText(getApplication(), "取消", Toast.LENGTH_LONG).show(); return; } switch (requestCode) { case CODE_GALLERY_REQUEST: Toast.makeText(this, "code--1", Toast.LENGTH_SHORT).show(); cropRawPhoto(intent.getData()); break; case CODE_CAMERA_REQUEST: if (hasSdcard()) { File tempFile = new File( Environment.getExternalStorageDirectory(), IMAGE_FILE_NAME); String path = tempFile.getPath(); Toast.makeText(this, path+"89", Toast.LENGTH_SHORT).show(); cropRawPhoto(Uri.fromFile(tempFile)); } else { Toast.makeText(getApplication(), "沒有SDCard!", Toast.LENGTH_LONG) .show(); } break; case CODE_RESULT_REQUEST: Toast.makeText(this, "code--3", Toast.LENGTH_SHORT).show(); if (intent != null) { setImageToHeadView(intent); } //Toast.makeText(this, "intent為null", Toast.LENGTH_SHORT).show(); break; } super.onActivityResult(requestCode, resultCode, intent); } /** * 裁剪原始的圖片 */ public void cropRawPhoto(Uri uri) { Intent intent = new Intent("com.android.camera.action.CROP"); intent.setDataAndType(uri, "image/*"); // 設定裁剪 intent.putExtra("crop", "true"); // aspectX , aspectY :寬高的比例 intent.putExtra("aspectX", 1); intent.putExtra("aspectY", 1); // outputX , outputY : 裁剪圖片寬高 intent.putExtra("outputX", output_X); intent.putExtra("outputY", output_Y); intent.putExtra("return-data", true); startActivityForResult(intent, CODE_RESULT_REQUEST); } //設定圖片作為頭像 private void setImageToHeadView(Intent intent) { PhotoUtil photoUtil = new PhotoUtil(); Bundle extras = intent.getExtras(); if (extras != null) { // Toast.makeText(this, extras.getParcelable("data")+"*", Toast.LENGTH_SHORT).show(); Bitmap photo = extras.getParcelable("data"); photo = photoUtil.toRoundBitmap(photo); imgTouXiang.setImageBitmap(photo); } } // 啟動手機相機拍攝照片作為頭像 private void choseHeadImageFromCameraCapture() { Intent intentFromCapture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); // 判斷儲存卡是否可用,儲存照片檔案 if (hasSdcard()) { intentFromCapture.putExtra(MediaStore.EXTRA_OUTPUT, Uri .fromFile(new File(Environment .getExternalStorageDirectory(), IMAGE_FILE_NAME))); } startActivityForResult(intentFromCapture, CODE_CAMERA_REQUEST); } // 從本地相簿選取圖片作為頭像 private void choseHeadImageFromGallery() { Intent intentFromGallery = new Intent(); // 設定檔案型別 intentFromGallery.setType("image/*");//選擇圖片 intentFromGallery.setAction(Intent.ACTION_GET_CONTENT); //如果你想在Activity中得到新開啟Activity關閉後返回的資料, //你需要使用系統提供的startActivityForResult(Intent intent,int requestCode)方法開啟新的Activity startActivityForResult(intentFromGallery, CODE_GALLERY_REQUEST); } /** * 檢查裝置是否存在SDCard的工具方法 */ public static boolean hasSdcard() { String state = Environment.getExternalStorageState(); if (state.equals(Environment.MEDIA_MOUNTED)) { // 有儲存的SDCard return true; } else { return false; } } }
其中設定圖片作為頭像方法中 有一個PhotoUtil 類 它主要用於將所選擇裁剪後的影象變為圓形 設定
這個類為:
public class PhotoUtil { public Bitmap toRoundBitmap(Bitmap bitmap) { int width = bitmap.getWidth(); int height = bitmap.getHeight(); float roundPx; float left, top, right, bottom, dst_left, dst_top, dst_right, dst_bottom; if (width <= height) { roundPx = width / 2; top = 0; bottom = width; left = 0; right = width; height = width; dst_left = 0; dst_top = 0; dst_right = width; dst_bottom = width; } else { roundPx = height / 2; float clip = (width - height) / 2; left = clip; right = width - clip; top = 0; bottom = height; width = height; dst_left = 0; dst_top = 0; dst_right = height; dst_bottom = height; } Bitmap output = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(output); final int color = 0xff424242; final Paint paint = new Paint(); final Rect src = new Rect((int) left, (int) top, (int) right, (int) bottom); final Rect dst = new Rect((int) dst_left, (int) dst_top, (int) dst_right, (int) dst_bottom); final RectF rectF = new RectF(dst); paint.setAntiAlias(true); canvas.drawARGB(0, 0, 0, 0); paint.setColor(color); canvas.drawRoundRect(rectF, roundPx, roundPx, paint); paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN)); canvas.drawBitmap(bitmap, src, dst, paint); return output; } }
好了,到此就實現了,許可權需要加上儲存、讀取檔案的許可權
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
拿走即可使用!