在我的应用程序中,我想裁剪图像,然后将其转换为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:尝试在 com.example 的空对象引用上调用虚拟方法 'boolean android.graphics.Bitmap.compress(android.graphics.Bitmap$CompressFormat, int, java.io.OutputStream)' .app.Utils.Componenets.ImageConvertBase64.convert(ImageConvertBase64.java:25) 在 com.example.app.Activities.ProfileEditActivity.handleCrop(ProfileEditActivity.java:326) 在 com.example.appt.Activities.ProfileEditActivity.onActivityResult(ProfileEditActivity .java:192) 在 android.app.Activity.dispatchActivityResult(Activity.java:6222) 在 android.app.ActivityThread.deliverResults(ActivityThread.java:3627)
我该如何解决?请帮我。
我是业余爱好者,真的需要你的帮助。谢谢