android通過相冊、相機設置頭像

上源碼,簡單.

工具類

/**
 * SelPhotoUtils  相片選擇
 * @author zgq
 * @version 1.0, 2017/5/16 0016
 * @since
 */
public class SelPhotoUtils {

   public static final int CHOOSE_PICTURE = 0;
   public static final int TAKE_PICTURE = 1;
   public static final int CROP_SMALL_PICTURE = 2;

   private Activity activity;
   public Uri tempUri;
   private String imgPath;

   public SelPhotoUtils(Activity activity) {
      this.activity = activity;
   }

   /** 選擇照片 */
   public void showSelPicture(){
      Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
      intent.setType("image/*");
      activity.startActivityForResult(intent,CHOOSE_PICTURE);
   }


   /** 拍照 */
   public void showTakePicture(){
      Intent intent1 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
      tempUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "image.jgp"));
      intent1.putExtra(MediaStore.EXTRA_OUTPUT, tempUri);
      activity.startActivityForResult(intent1, TAKE_PICTURE);
   }


   /**
    * 裁剪圖片方法實現
    *
    * @param uri
    */
   public void startPhotoZoom(Uri uri) {
      if (uri == null){
//       Toast.makeText(activity, "uri空", Toast.LENGTH_SHORT).show();
      }

      tempUri = uri;
      Intent intent = new Intent("com.android.camera.action.CROP");
      intent.setDataAndType(tempUri, "image/*");
      // 設置裁剪
      intent.putExtra("crop", "true");
      // aspectX aspectY 是寬高的比例
      intent.putExtra("aspectX", 1);
      intent.putExtra("aspectY", 1);
      // outputX outputY 是裁剪圖片寬高
      intent.putExtra("outputX", 300);
      intent.putExtra("outputY", 300);
      intent.putExtra("return-data", true);
      activity.startActivityForResult(intent, CROP_SMALL_PICTURE);
   }



   /**
    * 保存裁剪之後的圖片數據
    *
    * @param data
    *
    * @param showImg
    */
   public String setImageToView(Intent data, ImageView showImg) {
      Bundle extras = data.getExtras();
      if (extras != null) {
         Bitmap photo = extras.getParcelable("data");
//            photo = toRoundBitmap(photo, tempUri); // 處理成圓形
         showImg.setImageBitmap(photo);
         imgPath = uploadPic(photo);
         return imgPath;
      }
      return "";
   }


   public String uploadPic(Bitmap bitmap) {
      // 可以在這裏把Bitmap轉換成file,然後得到file的url,做文件上傳操作
      
      String imagePath = savePhoto(bitmap, Environment
            .getExternalStorageDirectory().getAbsolutePath(), String
            .valueOf(System.currentTimeMillis()));
      Log.e("imagePath", imagePath+"");
      if(imagePath == null){
         return "";
      }
      return imagePath;
   }


   /**
    * Save image to the SD card
    * 
    * @param photoBitmap
    * @param photoName
    * @param path
    */
   public String savePhoto(Bitmap photoBitmap, String path,
         String photoName) {
      String localPath = null;
      if (android.os.Environment.getExternalStorageState().equals(
            android.os.Environment.MEDIA_MOUNTED)) {
         File dir = new File(path);
         if (!dir.exists()) {
            dir.mkdirs();
         }

         File photoFile = new File(path, photoName + ".png");
         FileOutputStream fileOutputStream = null;
         try {
            fileOutputStream = new FileOutputStream(photoFile);
            if (photoBitmap != null) {
               if (photoBitmap.compress(Bitmap.CompressFormat.PNG, 100,
                     fileOutputStream)) {
                  localPath = photoFile.getPath();
                  fileOutputStream.flush();
               }
            }
         } catch (FileNotFoundException e) {
            photoFile.delete();
            localPath = null;
            e.printStackTrace();
         } catch (IOException e) {
            photoFile.delete();
            localPath = null;
            e.printStackTrace();
         } finally {
            try {
               if (fileOutputStream != null) {
                  fileOutputStream.close();
                  fileOutputStream = null;
               }
            } catch (IOException e) {
               e.printStackTrace();
            }
         }
      }
      return localPath;
   }


   /**
    * SelPhotoUtils  剪切爲圓形
    *
    * @since
    */
   public Bitmap toRoundBitmap(Bitmap bitmap, Uri tempUri) {
      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;
         left = 0;
         top = 0;
         right = width;
         bottom = 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, 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.drawCircle(roundPx, roundPx, roundPx, paint);

      paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
      canvas.drawBitmap(bitmap, src, dst, paint);

      return output;
   }

使用方法

public class MainActivity extends AppCompatActivity {

    private ImageView iv_personal_icon;
    private SelPhotoUtils selPhotoUtils;
    private String path;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button btn_change = (Button) findViewById(R.id.btn_change);
        iv_personal_icon = (ImageView) findViewById(R.id.iv_personal_icon);
        btn_change.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                showChoosePicDialog();
            }
        });

        selPhotoUtils = new SelPhotoUtils(this);
    }


    /**
     * 顯示修改頭像的對話框
     */
    private void showChoosePicDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("剪切");
        builder.setNegativeButton("取消", null);
        String[] item = {"本地照片", "拍照"};
        builder.setItems(item, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                switch (which){
                    case 0:
                        selPhotoUtils.showSelPicture();
                        break;
                    case 1:
                        selPhotoUtils.showTakePicture();
                        break;
                }
            }
        });
        builder.create().show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK){
            switch (requestCode){
                case SelPhotoUtils.TAKE_PICTURE:
                    selPhotoUtils.startPhotoZoom(selPhotoUtils.tempUri); // 開始對圖片進行裁剪處理
                    break;
                case SelPhotoUtils.CHOOSE_PICTURE:
                    selPhotoUtils.startPhotoZoom(data.getData()); // 開始對圖片進行裁剪處理
                    break;
                case SelPhotoUtils.CROP_SMALL_PICTURE:
                    if (data != null) {
                        // 讓剛纔選擇裁剪得到的圖片顯示在界面上,並拿到路徑
                        path = selPhotoUtils.setImageToView(data, iv_personal_icon);
                        Toast.makeText(this, path, Toast.LENGTH_SHORT).show();
                    }
            }
        }
    }


}

最後是佈局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_horizontal">


    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#f2c690"
        android:padding="30dp" >

        <ImageView
            android:id="@+id/iv_personal_icon"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:src="@mipmap/ic_launcher" />
    </RelativeLayout>

    <Button
        android:id="@+id/btn_change"
        android:layout_marginTop="20dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="修改頭像" >
    </Button>
</LinearLayout>

記得加權限:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

OK,這是全部源碼

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章