在相机或相册选择图片上传

2017-10-15  本文已影响0人  巡皇wx

/**

* 选择图片的返回码

*/

public final static intSELECT_IMAGE_RESULT_CODE=200;

public final static intSELECT_PHOTO_RESULT_CODE=300;

/**

* 当前选择的图片的路径

*/

publicStringmImagePath;

privateStringimagePath;

privateFileimageFile;

privateUriuri;

//调取相机

private voidtakePhoto() {

// 执行拍照前,应该先判断SD卡是否存在

String SDState = Environment.getExternalStorageState();

if(SDState.equals(Environment.MEDIA_MOUNTED)) {

/**

* 通过指定图片存储路径,解决部分机型onActivityResult回调 data返回为null的情况

*/

//获取与应用相关联的路径

String imageFilePath = getExternalFilesDir(Environment.DIRECTORY_PICTURES).getAbsolutePath();

SimpleDateFormat formatter =newSimpleDateFormat("yyyyMMddHHmmss",Locale.CHINA);

//根据当前时间生成图片的名称

String timestamp ="/"+ formatter.format(newDate()) +".jpg";

// 通过路径创建保存文件

imageFile=newFile(imageFilePath,timestamp);

mImagePath=imageFile.getAbsolutePath();

Uri imageFileUri = Uri.fromFile(imageFile);// 获取文件的Uri

Intent intent =newIntent(MediaStore.ACTION_IMAGE_CAPTURE);

intent.putExtra(MediaStore.EXTRA_OUTPUT,imageFileUri);// 告诉相机拍摄完毕输出图片到指定的Uri

startActivityForResult(intent,SELECT_IMAGE_RESULT_CODE);

}else{

Toast.makeText(this,"内存卡不存在!",Toast.LENGTH_LONG).show();

}

}

//调用相册

public voidchoosePhoto() {

//调用相册

Intent intent =newIntent(Intent.ACTION_PICK,

android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

startActivityForResult(intent,SELECT_PHOTO_RESULT_CODE);

}

//回调

@Override

protected voidonActivityResult(intrequestCode, intresultCode,Intent data) {

super.onActivityResult(requestCode,resultCode,data);

//获取图片路径

if(requestCode ==SELECT_PHOTO_RESULT_CODE&& resultCode == Activity.RESULT_OK&& data !=null) {

Uri uri = data.getData();

try{

String[] filePathColumn = {MediaStore.MediaColumns.DATA};

// 也可用下面的方法拿到cursor

Cursor cursor =this.managedQuery(uri,filePathColumn, null, null, null);

cursor.moveToFirst();

intcolumnIndex = cursor.getColumnIndex(filePathColumn[0]);

imagePath= cursor.getString(columnIndex);

cursor.close();

imageFile=newFile(imagePath);

Bitmap bm = BitmapFactory.decodeFile(imagePath);

head_pic.setImageBitmap(bm);

postHeadImage();

}catch(Exception e) {

e.printStackTrace();

}

}else if(requestCode ==SELECT_IMAGE_RESULT_CODE&& resultCode ==RESULT_OK) {

imageFile=newFile(mImagePath);

imagePath=mImagePath;

uri= Uri.fromFile(imageFile);

showImage(imagePath);

}

SharedPreferences.Editor edit =sharedPreferences.edit();

edit.putString("picpath",imagePath);

edit.commit();

}

上一篇下一篇

猜你喜欢

热点阅读