简单粗暴的记录,直接上代码:
通过一个addpic()方法就实现
备注:manifest中的application记得添加android:hardwareAccelerated="false"这个属性
源码地址:http://download.csdn.net/detail/l515518205/7388235
Button choose;
ImageView image;
private Bitmap myBitmap;
private byte[] mContent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
choose=(Button) findViewById(R.id.button1);
image=(ImageView) findViewById(R.id.imageView1);
choose.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
addpic();
}
});
}
//显示对话框
protected void addpic() {
new AlertDialog.Builder(this)
.setItems(new String[] { "拍照", "从手机相册选择" },
new DialogInterface.OnClickListener() { // content
@Override
public void onClick(DialogInterface dialog,
int which) {
switch (which) {
case 0: {//拍照
Intent intent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra("return-data", true);
startActivityForResult(intent, 1);
break;
}
case 1: {//从相册
Intent intent = new Intent(
Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 2);
break;
}
default:
break;
}
}
})
.setNegativeButton("取消",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
dialog.dismiss();
}
}).show();
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != Activity.RESULT_OK)
return;
switch (requestCode) {
case 1://拍照
try {
Bundle extras = data.getExtras();
myBitmap = (Bitmap) extras.get("data");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
myBitmap.compress(Bitmap.CompressFormat.JPEG , 100, baos);
mContent=baos.toByteArray();
} catch (Exception e) {
e.printStackTrace();
// TODO: handle exception
}
image.setImageBitmap(myBitmap);
break;
case 2://从相册选择
try {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
image.setImageBitmap(BitmapFactory.decodeFile(picturePath));
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
break;
}
}
}