您的位置:首页 > 移动开发 > Android开发

Android部分手机拍照上传返回为空处理,和拍照后图片压缩后保存到指定路径下

2017-08-02 15:26 851 查看
Android手机拍照返回时,部分手机拍照返回时,在onActivityResult方法中使用data.getData()返回为空,解决方法为: private Uri photoUri=null;
private File oldFile;
private File newFile;

public void takePhoto() {
try {
// 执行拍照前,应该先判断SD卡是否存在
if (Bimp.checkSDCardAvailable()) {
Intent openFileIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
openFileIntent.putExtra(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
SimpleDateFormat timeStampFormat = new SimpleDateFormat("yyyyMMddHHmmss");
String filename = timeStampFormat.format(new Date());
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, filename);
photoUri = getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
openFileIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
startActivityForResult(openFileIntent, SELECT_PIC_BY_TACK_PHOTO);
} else {
Toast.makeText(SbtjclActivity.this, "SD卡不存在",
Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != RESULT_OK) {
return;
} else {
switch (requestCode) {
case SELECT_PIC_BY_TACK_PHOTO:
String sdStatus = Environment.getExternalStorageState();
if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
Log.i("TestFile",
"SD card is not avaiable/writeable right now.");
return;
}

Bitmap bitmap = null;
try {
Uri result = null;
if (data != null) {
result = data.getData();
}else {
result = photoUri;
}
oldFile = FileUtil.getTempFile(this, result);
//压缩原图片 得到压缩后的图片
newFile = CompressHelper.getDefault(getApplicationContext()).compressToFile(oldFile);
bitmap = BitmapFactory.decodeFile(newFile.getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
}

/*以下将压缩后的照片保存到指定的路径下*/
String name = CommonUtils.getGMTime("yyyyMMddHHmmss") + ".jpg";
String path = ConstantValue.IMG_LOCAL_POSITION_SP;
FileOutputStream b = null;
// 不能直接保存在系统相册位置
File file = new File(path);
if (!file.exists()){
file.mkdirs();// 创建文件夹
}
String fileName = path + name;
try {
b = new FileOutputStream(fileName);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, b);// 把数据写入文件
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
try {
b.flush();
b.close();
} catch (IOException e) {
e.printStackTrace();
}
}
break;
}
}
}

图片压缩采用的github上大神写的开源项目: https://github.com/nanchen2251/CompressHelper
项目中遇到的问题,写下来,避免以后忘了。

部分知识点参考:
http://www.jianshu.com/p/82c54dd67c51
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐