玩qq或者是微信的盆友都知道,這些聊天工具裡都要設定頭像,一般情況下大家的解決辦法是從本地圖庫選擇圖片或是從相機拍照,然後根據自己的喜愛截取圖片。上述過程已經實現好了,最後一步我加上了把截取好的圖片在儲存到本地的操作,來儲存頭像。為了大家需要,下面雲棲社區小編把完整的代碼貼出來供大家參考。
先給大家展示效果圖:
代碼部分:
布局代碼(其實就是兩個按鈕和一個ImageView來顯示頭像)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical" ><ImageViewandroid:id="@+id/imageView"android:layout_width="wrap_content"android:layout_height="wrap_content"/><Buttonandroid:id="@+id/buttonLocal"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="本地相簿選取頭像" /><Buttonandroid:id="@+id/buttonCamera"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="手機拍照選取頭像" /></LinearLayout>
本文代碼:
public class MainActivity extends AppCompatActivity {/* 頭像檔案 */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;private ImageView headImage = null;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);headImage = (ImageView) findViewById(R.id.imageView);Button buttonLocal = (Button) findViewById(R.id.buttonLocal);buttonLocal.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {choseHeadImageFromGallery();}});Button buttonCamera = (Button) findViewById(R.id.buttonCamera);buttonCamera.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {choseHeadImageFromCameraCapture();}});}// 從本地相簿選取圖片作為頭像private void choseHeadImageFromGallery() {Intent intentFromGallery = new Intent();// 設定檔案類型intentFromGallery.setType("image/*");//選擇圖片intentFromGallery.setAction(Intent.ACTION_GET_CONTENT);//如果你想在Activity中得到新開啟Activity關閉後返回的資料,//你需要使用系統提供的startActivityForResult(Intent intent,int requestCode)方法開啟新的ActivitystartActivityForResult(intentFromGallery, CODE_GALLERY_REQUEST);}// 啟動手機相機拍攝照片作為頭像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);}@Overrideprotected 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://如果是來自本地的cropRawPhoto(intent.getData());//直接裁剪圖片break;case CODE_CAMERA_REQUEST:if (hasSdcard()) {File tempFile = new File(Environment.getExternalStorageDirectory(),IMAGE_FILE_NAME);cropRawPhoto(Uri.fromFile(tempFile));} else {Toast.makeText(getApplication(), "沒有SDCard!", Toast.LENGTH_LONG).show();}break;case CODE_RESULT_REQUEST:if (intent != null) {setImageToHeadView(intent);//設定圖片框}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);}/*** 提取儲存裁剪之後的圖片資料,並設定頭像部分的View*/private void setImageToHeadView(Intent intent) {Bundle extras = intent.getExtras();if (extras != null) {Bitmap photo = extras.getParcelable("data");headImage.setImageBitmap(photo);<br> //建立檔案夾 先選好路徑 再調用mkdir函數 現在是根目錄下面的Ask檔案夾File nf = new File(Environment.getExternalStorageDirectory()+"/Ask");nf.mkdir();<br> //在根目錄下面的ASk檔案夾下 建立okkk.jpg檔案File f = new File(Environment.getExternalStorageDirectory()+"/Ask", "okkk.jpg");FileOutputStream out = null;try {<br><br> //開啟輸出資料流 將圖片資料填入檔案中out = new FileOutputStream(f);photo.compress(Bitmap.CompressFormat.PNG, 90, out);try {out.flush();out.close();} catch (IOException e) {e.printStackTrace();}} catch (FileNotFoundException e) {e.printStackTrace();}}}/*** 檢查裝置是否存在SDCard的工具方法*/public static boolean hasSdcard() {String state = Environment.getExternalStorageState();if (state.equals(Environment.MEDIA_MOUNTED)) {// 有儲存的SDCardreturn true;} else {return false;}}}
因為涉及到檔案讀寫,要加入兩個許可權!!!
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/><uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
關於本文給大家介紹的Android實現從本地圖庫/相機拍照後裁剪圖片並設定頭像的相關知識就給大家介紹到這裡,希望對大家有所協助!