在我的应用程序中,我希望裁剪图像,然后将其转换为bitmap
。
对于裁剪图片,我使用库:https://github.com/jdamcd/android-crop
我想在致电onActivityResult
时将此图片转换为bitmap
,为此我写下以下代码:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent result) {
if (requestCode == Crop.REQUEST_PICK && resultCode == RESULT_OK) {
beginCrop(result.getData());
} else if (requestCode == Crop.REQUEST_CROP) {
handleCrop(resultCode, result);
}
}
private void beginCrop(Uri source) {
Uri destination = Uri.fromFile(new File(getCacheDir(), "cropped"));
Crop.of(source, destination).asSquare().start(this);
}
private void handleCrop(int resultCode, Intent result) {
if (resultCode == RESULT_OK) {
if (result != null) {
Bundle bundle = result.getExtras();
Bitmap bitmap = bundle.getParcelable("data");
//imageView.setImageBitmap(bitmap);
base64String = ImageConvertBase64.convert(bitmap);
//Edit base64 for site
base64StringForSite = "data:image/png;base64," + base64String;
//Upload image call api
UploadAvatarImageSendData sendData = new UploadAvatarImageSendData();
sendData.setBase64ImageData(base64StringForSite);
profileEdit_avatarProgressBar.setVisibility(View.VISIBLE);
Call<SendCommentResponse> call = api.getUserUploadAvatar(token, "2", sendData);
call.enqueue(new Callback<SendCommentResponse>() {
@Override
public void onResponse(Call<SendCommentResponse> call, Response<SendCommentResponse> response) {
if (response.body().getData() != null) {
profileEdit_avatarProgressBar.setVisibility(View.GONE);
getUpdateAvatarImage();
Toasty.success(context, response.body().getStatusMessage(), Toast.LENGTH_SHORT, true).show();
} else {
Toasty.info(context, context.getResources().getString(R.string.retryAgainAgain), Toast.LENGTH_SHORT, true).show();
}
}
@Override
public void onFailure(Call<SendCommentResponse> call, Throwable t) {
profileEdit_avatarProgressBar.setVisibility(View.GONE);
Log.e("uploadImage", "Err : " + t.getMessage());
}
});
}
} else if (resultCode == Crop.RESULT_ERROR) {
Toast.makeText(this, Crop.getError(result).getMessage(), Toast.LENGTH_SHORT).show();
}
}
这是我将位图转换为base64的方法:
public static String convert(Bitmap bitmap) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
return Base64.encodeToString(outputStream.toByteArray(), Base64.DEFAULT);
}
但是当运行应用程序时,会在LogCat
中的错误消息下面显示:
引起:java.lang.NullPointerException:尝试调用虚拟 方法&#39;布尔值 android.graphics.Bitmap.compress(android.graphics.Bitmap $ CompressFormat, int,java.io.OutputStream)&#39;在null对象引用上 at com.example.app.Utils.Componenets.ImageConvertBase64.convert(ImageConvertBase64.java:25) at com.example.app.Activities.ProfileEditActivity.handleCrop(ProfileEditActivity.java:326) at com.example.appt.Activities.ProfileEditActivity.onActivityResult(ProfileEditActivity.java:192) 在android.app.Activity.dispatchActivityResult(Activity.java:6222) 在android.app.ActivityThread.deliverResults(ActivityThread.java:3627)
我该如何解决?请帮我。
我很业余,真的需要你的帮助。谢谢