这是我的例外:
E/UploadBill: Error writing bitmap
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.graphics.Bitmap.compress(android.graphics.Bitmap$CompressFormat, int, java.io.OutputStream)' on a null object reference
at kmsg.com.onetouch.activity.UploadDocumentActivity$UploadBill.doInBackground(UploadDocumentActivity.java:299)
at kmsg.com.onetouch.activity.UploadDocumentActivity$UploadBill.doInBackground(UploadDocumentActivity.java:279)
这是我的代码:
File imageFile;
Bitmap photo;
这是我的按钮单击:
public void getFile(View view) {
if (ContextCompat.checkSelfPermission(UploadDocumentActivity.this, Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(UploadDocumentActivity.this,new String[]{Manifest.permission.CAMERA},
MY_CAMERA_PERMISSION_CODE);
} else {
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File pictureDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
String pictureNm = getPictureName();
imageFile = new File(pictureDirectory , pictureNm);
Uri pictureUri = Uri.fromFile(imageFile);
System.out.println("URI"+pictureUri);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT,pictureUri);
cameraIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY,1);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
}
这是onActivityResult:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//super.onActivityResult(requestCode, resultCode, data);
Bitmap myBitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
mImgDocument.setImageBitmap(myBitmap);
}
在这里我尝试压缩位图时发生错误:
try {
os = new FileOutputStream(imageFile.getAbsolutePath());
photo.compress(Bitmap.CompressFormat.JPEG, 100, os);
os.flush();
os.close();
} catch (Exception e) {
Log.e(getClass().getSimpleName(), "Error writing bitmap", e);
}
partList.add(new FilePart("file", imageFile));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
我试图像这样将图像发送到服务器,但是我找不到我的代码出了什么问题。我想发送此图像文件,但是当我看到日志时,它显示如下内容:
I/System.out: partList:[file]
我只想发送图像。我正在尝试正确的方式吗?
Bitmap.compress怎么了?答案 0 :(得分:1)
您的photo
变量未初始化。您需要先初始化该变量,然后再使用它。
替换
Bitmap myBitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath()); // You never use myBitmap after creating and initializing it...
mImgDocument.setImageBitmap(myBitmap);
与
if (requestCode==CAMERA_REQUEST && resultCode==RESULT_OK){ // <- this ensures the user didn't cancel the Camera Intent
photo= BitmapFactory.decodeFile(imageFile.getAbsolutePath()); // <- this initializes the variable so you can use it later.
mImgDocument.setImageBitmap(photo);
}
答案 1 :(得分:0)
在onActivityResult()中,使用该文件而不是“ myBitmap”将其存储到“ photo”变量中。在这里该文件可能存在或不存在,所以在成功完成图像捕获后,请执行此操作。
if (requestCode==CAMERA_REQUEST && resultCode==RESULT_OK){
//load bitmap
}