android - 如何使用相机捕获图像并将其保存在服务器上?
问题描述
我想使用相机捕获图像并将其存储在服务器中。但是在捕获图像后我得到了空指针异常。大部分都完成了,但这个错误很烦人。我是android新手,不知道为什么会出现这个错误。需要帮助提前谢谢
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == CAMERA) {
if (data == null) {
Snackbar.make(parentView, R.string.string_unable_to_pick_image, Snackbar.LENGTH_INDEFINITE).show();
return;
}
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
// CALL THIS METHOD TO GET THE URI FROM THE BITMAP
Uri tempUri = getImageUri(getApplicationContext(), photo);
// CALL THIS METHOD TO GET THE ACTUAL PATH
File finalFile = new File(getRealPathFromURI(tempUri));
decodeFile(finalFile.toString());}}
**getImageUri 方法**
public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "aadhar", null);
return Uri.parse(path);//getting error here
}
getRealPathFromURI 方法
public String getRealPathFromURI(Uri uri) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
return cursor.getString(idx);
}
decodeFile 方法
public void decodeFile(String filePath) {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 1024;
// Find the correct scale value. It should be the power of 2.
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
Bitmap bitmap = BitmapFactory.decodeFile(filePath, o2);
imageView.setImageBitmap(bitmap);
}
错误
Caused by: java.lang.NullPointerException: uriString
at android.net.Uri$StringUri.<init>(Uri.java:475)
at android.net.Uri$StringUri.<init>(Uri.java)
at android.net.Uri.parse(Uri.java:437)
at com.androidbuts.ui.MainActivity.getImageUri(MainActivity.java:274)
at com.androidbuts.ui.MainActivity.onActivityResult(MainActivity.java:233)
at android.app.Activity.dispatchActivityResult(Activity.java:7139)
解决方案
<!--First define permissions in Menifest-->
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_INTERNAL_STORAGE" />
// 打开相机为
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA);
// 然后将图像检索为
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA && data != null) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
File imageStorageDir = new File(Environment.getExternalStorageDirectory(),
getResources().getString(R.string.app_name));
if (!imageStorageDir.exists()) {
imageStorageDir.mkdirs();
}
imagePath = imageStorageDir + File.separator + "_NAME_YOU_WISH" + ".jpg";
fileImage = new File(imagePath); // FILE
try {
FileOutputStream out = new FileOutputStream(imagePath);
photo.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
if (fileImage != null) {
if (fileImage.isFile() && fileImage.exists()) {
// MyApplication.log(LOG_TAG, "onActivityResult() SHOWING IMAGE BY GLIDE, fileImage:-> " + fileImage.getAbsolutePath());
Glide.with(context)
.load(fileImage.getAbsoluteFile())
.asBitmap()
.placeholder(R.drawable.ic_broken_image)
.into(img_camera);
}
}
} catch (Exception e) {
//MyApplication.log(LOG_TAG, "onActivityResult() , Exception: " + e.getMessage());
}
}
}
// 调用函数将图像发送到服务器
public void callSendCheckReport() {
MyApplication.showDialog(context, "Please Wait...");
HashMap<String, Object> map = new HashMap<>();
map.put("date", today);
map.put("salesman_id", MyApplication.get_session(MyApplication.SESSION_SALESMAN_ID));
if (actionStatus.equals("do_CHECK_IN")) { //// do_CHECK_IN, do_NO_CHANGE, do_CHECK_OUT
map.put("checkin", "yes");
map.put("in_time", checkTimeStamp);
if (fileImage != null)
map.put("in_image", new TypedFile("image*//*", fileImage));
}
RestClient.getWebServices().sendCheckReport(map,
new Callback<String>() {
@Override
public void success(String s, Response response) {
MyApplication.log(LOG_TAG, "Responce is----> " + s);
try {
JSONObject res = new JSONObject(s); // "status":"TRUE","message":"Shop Registered Successfully."}
String status = res.getString("status");
String message = res.getString("message");
MyApplication.stopLoading();
if (status.equals("TRUE")) {
if (fileImage.exists())
fileImage.delete();
}
showDialogBox(context, getResources().getString(R.string.app_name), message);
} catch (JSONException e) {
MyApplication.stopLoading();
// MyApplication.log(LOG_TAG + "RESPONSE JSONException ->" + e.getMessage());
}
}
@Override
public void failure(RetrofitError error) {
MyApplication.log(LOG_TAG + " RetrofitError ->" + error.getMessage());
MyApplication.stopLoading();
}
});
}
推荐阅读
- node.js - 授权。尝试在 Azure 上查询我的 PostgreSQL 时出错
- latex - 如何减少 TikZposter 中 2 个块之间的空间?
- c++ - 写入 WAV 文件 C++
- xml - 完成后将变量保存在 .awk 文件中以供下次运行
- javascript - Apollo 客户端订阅的缓存策略未按预期工作
- deep-learning - 双深度 Q 学习:下一个状态总是错误的
- reactjs - 许多小的 react.CreateElement 对同一文档的性能影响?
- python - calcOpticalFlowFarneback 的结果是否需要在翘曲中进行一些处理?
- javascript - SVG 动画只能在网站的正确页面/部分上启动
- python-3.x - @client.event 从一个为假的 if 条件返回一个输出