很长一段时间没更新了,今天回家了写一些这段时间的总结
下面这个函数用于调用时调用系统照相机拍照并返回路径的方法:
private String takephoto(int i) {
Time time1 = new Time("GMT+8");
time1.setToNow(); //设置time1为当前的时间,避免照片名重复被覆盖掉
String time =time1.toString();
String status=Environment.getExternalStorageState();
if(status.equals(Environment.MEDIA_MOUNTED))
{
try {
File dir=new File(Environment.getExternalStorageDirectory() + "/tonynotepic/");
if(!dir.exists())
dir.mkdirs();
Intent intent=new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
File f=new File(dir, time+".jpg");//dir 文件夹路径 time.jpg是图片名字
Uri u=Uri.fromFile(f);
intent.putExtra(MediaStore.Images.Media.ORIENTATION, 0);
intent.putExtra(MediaStore.EXTRA_OUTPUT, u);
startActivityForResult(intent, i);//跳转到系统照相界面,请求码为i;
} catch (ActivityNotFoundException e) {
// TODO Auto-generated catch block
Toast.makeText(AddNoteActivity.this, "没有找到储存目录",Toast.LENGTH_LONG).show();
}
}else{
Toast.makeText(AddNoteActivity.this, "没有储存卡",Toast.LENGTH_LONG).show();
// TODO Auto-generated method stub
}
return time;//返回照片名
}
@Override //在当前activity重写这个方法,当请求码为i时执行如下操作
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode){
switch (resultCode) {
case Activity.RESULT_OK://照相完成点击确定
File f=new File(Environment.getExternalStorageDirectory()
+"/tonynotepic/"+time1+".jpg"); //time1是刚才takephoto的返回值,图片的路径,定义 :private String time1;
try {
Uri u =
Uri.parse(android.provider.MediaStore.Images.Media.insertImage(getContentResolver(),
f.getAbsolutePath(), null, null));
picturePath1=Environment.getExternalStorageDirectory()
+"/tonynotepic/"+time1+".jpg"; //根据time1,生成图片的完整路径;类型为String
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace(); }
break;
case Activity.RESULT_CANCELED:// 取消
break;
}
break;}
@Override
protected void onStart() {//然后再重写onstart方法,这样从系统照相点确认返回当前activity后,图片设置为拍摄图像
// TODO Auto-generated method stub
super.onStart();
if(!picturePath1.equals("0"))
img1.setImageBitmap(getimage((picturePath1)));
}
然后是调用系统图库并设置图片的代码,调用代码如下
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, i);
当你选择了图片后,系统执行如下代码
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode){
case i:
if (requestCode == i && resultCode == RESULT_OK && null != data) {
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]);
picturePath1 = cursor.getString(columnIndex);//picturepath设置为选择的图片路径
cursor.close(); } break;
同样,重写onstart代码即可实现点击后设置activity的imageview为选择的图片