相信很多朋友做上传图片的时候都苦恼过获取不到图片,本篇博客解决你的烦恼
这里是选择本地图片
try {
// 选择本地文件
Intent fileIntent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
/* 取得相片后返回本画面 */
startActivityForResult(fileIntent, myRequestCode);
} catch (Exception e) {
LogUtil.e(e);
}
//这里是拍照上传
// 调用系统照相功能
try {
// 调用系统摄像头,进行拍照
String state = Environment.getExternalStorageState();
if (state.equals(Environment.MEDIA_MOUNTED)) {
Intent phoneIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
String saveDir = GlobalParams.SAVE_PATH;
File dir = new File(saveDir);
if (!dir.exists()) {
dir.mkdir();
}
file = new File(saveDir, System.currentTimeMillis()+".jpg");
phoneIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
startActivityForResult(phoneIntent, 2);
}
} catch (Exception e) {
LogUtil.e(e);
}
下面就开始怎么获取图片了
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
if (requestCode == myRequestCode) {
Uri uri = data.getData();
if (bitmap != null) {
bitmap.recycle();
bitmap = null;
file = null;
}
if(uri != null){
String[] proj = { MediaStore.Images.Media.DATA };
Cursor actualimagecursor = managedQuery(uri, proj, null, null, null);
int actual_image_column_index = actualimagecursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
actualimagecursor.moveToFirst();
String img_path = actualimagecursor
.getString(actual_image_column_index);
file = new File(img_path);
if (Integer.parseInt(Build.VERSION.SDK) < 14) {
actualimagecursor.close();
}
ImageSize imageSize = ImageSizeUtil
.getImageViewSize(iv_preview);
// 2、压缩图片
// 获得图片的宽和高,并不把图片加载到内存中
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(img_path, options);
options.inSampleSize = ImageSizeUtil.caculateInSampleSize(
options, imageSize.width, imageSize.height);
// 使用获得到的InSampleSize再次解析图片
options.inJustDecodeBounds = false;
bitmap = BitmapFactory.decodeFile(img_path, options);
}else{
//获取图片
Bundle extras = data.getExtras();
bitmap = (Bitmap) extras.get("data");
}
iv_preview.setImageBitmap(bitmap);
}else if(requestCode == 2){
if(file != null){
//压缩图片
compressionImage();
}
}
} catch (Exception e) {
Log.e("Exception", e.getMessage(), e);
}
}
/**
* 压缩图片
*/
private void compressionImage() {
/*ImageSize imageSize = ImageSizeUtil
.getImageViewSize(iv_preview);*/
// 2、压缩图片
// 获得图片的宽和高,并不把图片加载到内存中
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(file.getAbsolutePath(), options);
/*options.inSampleSize = ImageSizeUtil.caculateInSampleSize(
options, imageSize.width, imageSize.height);*/
options.inSampleSize = 8;
// 使用获得到的InSampleSize再次解析图片
options.inJustDecodeBounds = false;
bitmap = BitmapFactory.decodeFile(file.getAbsolutePath(), options);
iv_preview.setImageBitmap(bitmap);
}
就这么简单,就这么任性搞定选择图片和拍照上传获取不到图片问题