android 拍照或从相册获取图片 返回 bitmap

这里用简单的方法实现:

1、申明对象:

private Uri photoUri1;
private static final int PHOTO_REQUEST_CAMERA = 1;// 拍照
private static final int PHOTO_REQUEST_GALLERY = 2;// 从相册中选择

2、弹出菜单选择拍照 或者 相册,将下面代码放在你的事件里:

AlertDialog.Builder builder = new AlertDialog.Builder(
PublishImgActivity.this);
builder.setTitle("选择方式");
builder.setPositiveButton("拍照", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
dialog.dismiss();
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
// 判断存储卡是否可以用,可用进行存储
if (hasSdcard())
{
SimpleDateFormat timeStampFormat = new SimpleDateFormat(
"yyyy_MM_dd_HH_mm_ss");
String filename = timeStampFormat.format(new Date());
ContentValues values = new ContentValues();
values.put(Media.TITLE, filename); 

photoUri1 = getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
values);

intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri1);

}
startActivityForResult(intent, PHOTO_REQUEST_CAMERA);
}
});
builder.setNeutralButton("相册", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
dialog.dismiss();
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, PHOTO_REQUEST_GALLERY);
}
});
builder.create().show();


3、获取返回图片:

这里我用了开源的imageloader,根据Uri来获取bitmap,相当方便,也不用考虑OOM。

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == PHOTO_REQUEST_GALLERY)
{
if (data != null)
{
// 得到图片的全路径 
photoUri1 = data.getData();
// bitmap1 = decodeUriAsBitmap(photoUri1);
// img1.setImageBitmap(bitmap1);

// imageLoader.getInstance().displayImage(
// photoUri1.toString(), img1, animateFirstListener);
bitmap1 = small(imageLoader.getInstance().loadImageSync(
photoUri1.toString()));
img1.setImageBitmap(bitmap1);  
}

}
else if (requestCode == PHOTO_REQUEST_CAMERA)
{
if (hasSdcard())
{
if (resultCode == -1)

// bitmap1 = decodeUriAsBitmap(photoUri1);
// img1.setImageBitmap(bitmap1);

// imageLoader.getInstance().displayImage(
// photoUri1.toString(), img1,
// animateFirstListener);
// bitmap1 = img1.getDrawingCache();
bitmap1 = small(imageLoader.getInstance()
.loadImageSync(photoUri1.toString()));
img1.setImageBitmap(bitmap1); 
}
}
else
{
Toast.makeText(PublishImgActivity.this, "未找到存储卡,无法存储照片!", 0)
.show();
}



super.onActivityResult(requestCode, resultCode, data);
}


4、相关方法:

private Bitmap small(Bitmap bitmap)
{
try
{

Matrix matrix = new Matrix();
matrix.postScale((float) 480 / bitmap.getWidth(), (float) 480
/ bitmap.getWidth()); // 长和宽放大缩小的比例
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
bitmap.getHeight(), matrix, true);

}
catch (Exception e)
{
e.printStackTrace();
return null;
}
return bitmap;
}

你可能感兴趣的:(Android)