1. 程式人生 > >android 選取相簿並剪裁

android 選取相簿並剪裁

package com.example.camera_demo;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.ImageView;

public class MainActivity extends Activity {

   private ImageView imageView;
   private String path = Environment.getExternalStorageDirectory()+"/1601v.png";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        imageView = (ImageView) findViewById(R.id.image);
        
        
    }
    
    //開啟相機  MediaStore.ACTION_IMAGE_CAPTURE 開啟相機的Action
    public void getcamera(View v){
          //1.開啟相簿
          Intent it = new Intent(Intent.ACTION_PICK);
          //2.設定圖片的格式
          it.setType("image/*");
          startActivityForResult(it, 1000);
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
          super.onActivityResult(requestCode, resultCode, data);
          
          //得到圖片進行裁剪
          if(requestCode == 1000 && resultCode == RESULT_OK){
             //3.得到圖片的路徑
             Uri uri =  data.getData();
             //4.com.android.camera.action.CROP 調取系統裁剪功能的Action
             Intent it = new Intent("com.android.camera.action.CROP");
             //得得到拍完照的圖片進行裁剪
             it.setDataAndType(uri, "image/*");
             //設定是否支援裁剪
             it.putExtra("crop", true);
             //設定框的寬高比
             it.putExtra("aspactX", 1);
             it.putExtra("aspactY", 1);
             //設定輸出圖片的大小
             it.putExtra("outputX", 250);
             it.putExtra("outputY", 250);
             //將圖片進行返回
             it.putExtra("return-data", true);
             
             startActivityForResult(it, 2000);
             
          }
          
          
          
          if(requestCode == 2000 && resultCode == RESULT_OK){

             //拿到剪裁後的圖片;
             Bitmap  bitmap = data.getParcelableExtra("data");
             imageView.setImageBitmap(bitmap);
             
             
          }
          
          
          
    }
    
    
    
    
}