使用AlertDialog弹窗实现相机拍照或者从图库选取图片显示

通过图库选图片主要就是onActivityResult方法中返回的intent中获取Uri,再根据Uri和指定列名使用contentProvider去查找出此图片的路径

使用相机拍照显示之前一篇文章已经有描述,此篇文章不对图片的大小进行处理。


2016/12/28

今天偶尔看到拍摄后再调用系统截图的,自己也搬过来吧。



代码:

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;


public class MainActivity extends Activity implements OnClickListener {
	private static final int FROM_CAMERA=1;
	private static final int FROM_PIC=2;
	private ImageView img;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		findViewById(R.id.btn).setOnClickListener(this);
		img=(ImageView) findViewById(R.id.img);
	}

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

	private void initView(){
		AlertDialog.Builder builder=new AlertDialog.Builder(this)
		.setIcon(R.drawable.ic_launcher)
		.setTitle("选择图片:")
				//设置两个item
				.setItems(new String[]{"相机","图库"}, new android.content.DialogInterface.OnClickListener(){

					@Override
					public void onClick(DialogInterface dialog, int which) {
						switch (which) {
						case 0:
							pickPicFromCam();
							break;
						case 1:
							pickPicFromPic();
							break;
						default:
							break;
						}
						
					}});
		builder.create().show();
		
		
	}
	
	private void pickPicFromCam(){
		try {
			Intent intent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
			intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(createImageFile()));
			startActivityForResult(intent, FROM_CAMERA);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		
		
	}
	private void pickPicFromPic(){
		Intent intent=new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
		startActivityForResult(intent, FROM_PIC);
	}
	
	
	
	String mCurrentPhotoPath;  
    //创建路径  
    private File createImageFile() throws IOException {  
        // Create an image file name  
        // String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new  
        // Date());  
        // String imageFileName = "JPEG_" + timeStamp + "_";  
        // File storageDir =  
        // getExternalFilesDir(Environment.DIRECTORY_PICTURES);//由getExternalFilesDir(),以及getFilesDir()创建的目录,应用卸载后会被删除!  
        //  
        // File image = File.createTempFile(  
        // imageFileName, /* prefix */  
        // ".jpg", /* suffix */  
        // storageDir /* directory */  
        // );  
        //  
        // // Save a file: path for use with ACTION_VIEW intents  
        // mCurrentPhotoPath = "file:" + image.getAbsolutePath();  
        // return image;  
        //检测内存卡是否存在  
        if (!Environment.getExternalStorageState().equals(  
                Environment.MEDIA_MOUNTED)) {  
            Log.d("my", "no SDCARD!!!!");  
  
        } else {  
            String pre = new SimpleDateFormat("yyyy_MM_dd_hh_mm_ss_SSS")  
                    .format(new Date());  
            //创建图片保存的位置  
            File path = new File(Environment.getExternalStorageDirectory(),  
                    "myImage");  
            //如果路径不存在  
            if (!path.exists()) {  
                //创建路径,需要权限  
                path.mkdirs();  
            }  
            //组合全部的路径  
            mCurrentPhotoPath = path.toString() + File.separator + pre + ".jpg";  
  
            Log.d("my", mCurrentPhotoPath);  
            File file = new File(mCurrentPhotoPath);  
  
            return file;  
  
        }  
  
        return null;  
    }  
	
	
	
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    	// TODO Auto-generated method stub
    	super.onActivityResult(requestCode, resultCode, data);
    	
    	if(requestCode==FROM_CAMERA && resultCode==RESULT_OK){
    		//为了方便起见,没有对图片进行压缩
    		img.setImageBitmap(BitmapFactory.decodeFile(mCurrentPhotoPath));
    	}
    	//从图库选择返回的结果
    	if(requestCode==FROM_PIC && resultCode==RESULT_OK && data!=null){
    		Uri uri=data.getData();
    		Log.d("my", uri.toString());
    													//要返回的列名
    		Cursor cursor=getContentResolver().query(uri, new String[]{MediaStore.Images.Media.DATA}, null, null, null);
    		if(cursor.moveToFirst()){
    			String ImgPath=cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
    			Log.d("my", ImgPath);
    			img.setImageBitmap(BitmapFactory.decodeFile(ImgPath));
    			
    			
    		}
    		
    	}
    	
    }
	
	
}
//添加后,添加了几个方法。
 
  
 
  
 
  
package secretbase.testcroppic;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;


public class MainActivity extends Activity implements OnClickListener {
    private static final int FROM_CAMERA=1;
    private static final int FROM_PIC=2;
    private ImageView img;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewById(R.id.btn).setOnClickListener(this);
        img=(ImageView) findViewById(R.id.img);
    }

    @Override
    public void onClick(View v) {
        initView();

    }

    private void initView(){
        AlertDialog.Builder builder=new AlertDialog.Builder(this)
                .setIcon(R.mipmap.ic_launcher)
                .setTitle("选择图片:")
                //设置两个item
                .setItems(new String[]{"相机","图库"}, new android.content.DialogInterface.OnClickListener(){

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (which) {
                            case 0:
                                pickPicFromCam();
                                break;
                            case 1:
                                pickPicFromPic();
                                break;
                            default:
                                break;
                        }

                    }});
        builder.create().show();


    }

    private void pickPicFromCam(){
        try {
            Intent intent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(createImageFile()));
            startActivityForResult(intent, FROM_CAMERA);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }




    }
    private void pickPicFromPic(){
        Intent intent=new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, FROM_PIC);
    }



    String mCurrentPhotoPath;
    //创建路径
    private File createImageFile() throws IOException {
        // Create an image file name
        // String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new
        // Date());
        // String imageFileName = "JPEG_" + timeStamp + "_";
        // File storageDir =
        // getExternalFilesDir(Environment.DIRECTORY_PICTURES);//由getExternalFilesDir(),以及getFilesDir()创建的目录,应用卸载后会被删除!
        //
        // File image = File.createTempFile(
        // imageFileName, /* prefix */
        // ".jpg", /* suffix */
        // storageDir /* directory */
        // );
        //
        // // Save a file: path for use with ACTION_VIEW intents
        // mCurrentPhotoPath = "file:" + image.getAbsolutePath();
        // return image;
        //检测内存卡是否存在
        if (!Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            Log.d("my", "no SDCARD!!!!");

        } else {
            String pre = new SimpleDateFormat("yyyy_MM_dd_hh_mm_ss_SSS")
                    .format(new Date());
            //创建图片保存的位置
            File path = new File(Environment.getExternalStorageDirectory(),
                    "myImage");
            //如果路径不存在
            if (!path.exists()) {
                //创建路径,需要权限
                path.mkdirs();
            }
            //组合全部的路径
            mCurrentPhotoPath = path.toString() + File.separator + pre + ".jpg";

            Log.d("my", mCurrentPhotoPath);
            File file = new File(mCurrentPhotoPath);

            return file;

        }

        return null;
    }

    //裁剪图片
    private void cropImageUri(Uri uri, int outputX, int outputY, int requestCode){
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", outputX);
        intent.putExtra("outputY", outputY);
        intent.putExtra("scale", true);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        //使用Uri返回数据,不用bitmap
        intent.putExtra("return-data", false);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true); // no face detection
        startActivityForResult(intent, requestCode);
    }



    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);

        if(requestCode==FROM_CAMERA && resultCode==RESULT_OK){
            //为了方便起见,没有对图片进行压缩
            //img.setImageBitmap(BitmapFactory.decodeFile(mCurrentPhotoPath));

            //对图片进行裁剪
            cropImageUri(Uri.fromFile(new File(mCurrentPhotoPath)),100,100,11);
        }
        //从图库选择返回的结果
        if(requestCode==FROM_PIC && resultCode==RESULT_OK && data!=null){
            Uri uri=data.getData();
            Log.d("my", uri.toString());
            //要返回的列名
            Cursor cursor=getContentResolver().query(uri, new String[]{MediaStore.Images.Media.DATA}, null, null, null);
            if(cursor.moveToFirst()){
                String ImgPath=cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
                Log.d("my", ImgPath);
                img.setImageBitmap(BitmapFactory.decodeFile(ImgPath));
            }
        }
            //裁剪后返回的圖片
            if(requestCode==11 && resultCode==RESULT_OK){
                img.setImageBitmap(decodeUriAsBitmap(Uri.fromFile(new File(mCurrentPhotoPath))));
            }


    }


    //可以使用Uri創建BItmap,比用cursor方便
    private Bitmap decodeUriAsBitmap(Uri uri){
        Bitmap bitmap = null;
        try {
            bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        }
        return bitmap;
    }


}
//比较好的版本
http://blog.csdn.net/yueqinglkong/article/details/24729727


public class MainActivity extends Activity {

        private ImageView img = null;

        private File tempFile = new File(Environment.getExternalStorageDirectory(),
                getPhotoFileName());
        private static final int PHOTO_REQUEST_TAKEPHOTO = 1;// 拍照
        private static final int PHOTO_REQUEST_GALLERY = 2;// 从相册中选择
        private static final int PHOTO_REQUEST_CUT = 3;// 结果

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

        private void init() {
            // TODO Auto-generated method stub
            img = (ImageView) findViewById(R.id.img);


            ((Button) findViewById(R.id.btn))
                    .setOnClickListener(new OnClickListener() {

                        public void onClick(View v) {
                            // TODO Auto-generated method stub
                            Intent cameraintent = new Intent(
                                    MediaStore.ACTION_IMAGE_CAPTURE);
                            // 指定调用相机拍照后照片的储存路径
                            cameraintent.putExtra(MediaStore.EXTRA_OUTPUT,
                                    Uri.fromFile(tempFile));
                            startActivityForResult(cameraintent,
                                    PHOTO_REQUEST_TAKEPHOTO);
                        }
                    });

        }

        /**
         * 回调
         */
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
            switch (requestCode) {
                case PHOTO_REQUEST_TAKEPHOTO:// 当选择拍照时调用
                    startPhotoZoom(Uri.fromFile(tempFile));
                    break;
                case PHOTO_REQUEST_GALLERY:// 当选择从本地获取图片时
                    // 做非空判断,当我们觉得不满意想重新剪裁的时候便不会报异常,下同
                    if (data != null)
                        startPhotoZoom(data.getData());
                    break;
                case PHOTO_REQUEST_CUT:// 返回的结果
                    if (data != null)
                        sentPicToNext(data);
                    break;
            }
        }

        private void startPhotoZoom(Uri uri) {
            Intent intent = new Intent("com.android.camera.action.CROP");
            intent.setDataAndType(uri, "image/*");
            // crop为true是设置在开启的intent中设置显示的view可以剪裁
            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);
            intent.putExtra("noFaceDetection", true);
            startActivityForResult(intent, PHOTO_REQUEST_CUT);
        }

        // 将进行剪裁后的图片传递到下一个界面上
        private void sentPicToNext(Intent picdata) {
            Bundle bundle = picdata.getExtras();
            if (bundle != null) {
                Bitmap photo = bundle.getParcelable("data");
                if (photo == null) {
                    img.setImageResource(R.mipmap.ic_launcher);
                } else {
                    photo = toRoundCorner((Bitmap) bundle.getParcelable("data"), 50);
                    Drawable drawable = new BitmapDrawable(this.getResources(),
                            photo);
                    img.setImageDrawable(drawable);
                    // 设置文本内容为 图片绝对路径和名字
                  ;
                }
            }
        }

        /**
         * 圆角图片处理
         *
         * @param bitmap
         * @param radius半径50
         * @return
         */
        public static Bitmap toRoundCorner(Bitmap bitmap, int pixels) {
            Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
                    bitmap.getHeight(), Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(output);
            final int color = 0xff424242;
            final Paint paint = new Paint();
            final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
            final RectF rectF = new RectF(rect);
            final float roundPx = pixels;
            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, rect, rect, paint);
            return output;
        }

        // 使用系统当前日期加以调整作为照片的名称
        private String getPhotoFileName() {
            Date date = new Date(System.currentTimeMillis());
            SimpleDateFormat dateFormat = new SimpleDateFormat(
                    "'IMG'_yyyyMMdd_HHmmss");
            return dateFormat.format(date) + ".jpg";
        }


}


 
  
 
  
 
  
 
  
 
  
 
  
 
  使用AlertDialog弹窗实现相机拍照或者从图库选取图片显示_第1张图片 
  

 
  
 
  
 
  
 
 

你可能感兴趣的:(Andriod)