[英]method 'boolean android.graphics.Bitmap.compress(android.graphics.Bitmap$CompressFormat, int, java.io.OutputStream)
[英]How to fix boolean android.graphics.Bitmap.compress when select image from Photos app?
在我的应用程序中,我想从图库中选择图像并进行裁剪,然后转换为base64 。
在我的应用程序中,我想从图库中选择图像并进行裁剪,然后转换为base64 。
当我从图库中选择图像时,不会显示我错误 ,但是从“照片”应用中选择图像时,会显示此错误!
错误:
FATAL EXCEPTION: main
Process: com.app.test, PID: 19778
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null,request=131073, result=0, data=Intent { launchParam=MultiScreenLaunchParams { mDisplayId=0 mFlags=0 }(has extras) }} to activity {com.app.test/com.app.test.Activity.MainActivity}: 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 android.app.ActivityThread.deliverResults(ActivityThread.java:4550)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4593)
at android.app.ActivityThread.-wrap22(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1709)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6724)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)
Caused by: 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 com.bidzila.android.Utils.Base64ConverterUtils.convert(Base64ConverterUtils.java:25)
at com.bidzila.android.Fragments.DashBoardFragment.onActivityResult(DashBoardFragment.java:172)
at android.support.v4.app.FragmentActivity.onActivityResult(FragmentActivity.java:159)
at android.app.Activity.dispatchActivityResult(Activity.java:7256)
at android.app.ActivityThread.deliverResults(ActivityThread.java:4546)
转换器类别:
public class Base64ConverterUtils {
public static Bitmap convert(String base64Str) throws IllegalArgumentException {
byte[] decodedBytes = Base64.decode(
base64Str.substring(base64Str.indexOf(",") + 1),
Base64.DEFAULT
);
return BitmapFactory.decodeByteArray(decodedBytes, 0, decodedBytes.length);
}
public static String convert(Bitmap bitmap) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
return Base64.encodeToString(outputStream.toByteArray(), Base64.DEFAULT);
}
}
我的片段类:
public class DashBoardFragment extends BaseFragment {
/* @BindView(R.id.addPhoto)
ImageView addPhoto;*/
private Handler handler;
private Context context;
private View v;
private PrefsUtils prefsUtils;
private ImageView addPhoto;
private LinearLayout noLoginFrag_btn;
private TextView textView2, dash_winnerTxt, dash_allBidsTxt, dash_allBidsTxt2, dash_winnerTxt2, dash_notWinTxt, dash_bougthTxt;
private ProgressBar profileProgress;
private File file;
private Uri uri;
private Intent CamIntent, GalIntent, CropIntent;
public static final int RequestPermissionCode = 1;
private DisplayMetrics displayMetrics;
private int width, height;
private String base64String, base64StringForSite;
private APIs apIs;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
handler = new Handler();
context = getActivity();
prefsUtils = new PrefsUtils(context);
if (prefsUtils.isExist(PrefsKeys.PHONE_NUMBER.name())) {
v = inflater.inflate(R.layout.fragment_dashboard, null);
addPhoto = v.findViewById(R.id.addPhoto);
textView2 = v.findViewById(R.id.textView2);
dash_winnerTxt = v.findViewById(R.id.dash_winnerTxt);
dash_allBidsTxt = v.findViewById(R.id.dash_allBidsTxt);
dash_allBidsTxt2 = v.findViewById(R.id.dash_allBidsTxt2);
dash_winnerTxt2 = v.findViewById(R.id.dash_winnerTxt2);
dash_notWinTxt = v.findViewById(R.id.dash_notWinTxt);
dash_bougthTxt = v.findViewById(R.id.dash_bougthTxt);
profileProgress = v.findViewById(R.id.profileProgress);
apIs = ApiClient.getClient().create(APIs.class);
handler.postDelayed(new Runnable() {
@Override
public void run() {
try {
textView2.setText(Constants.profileResponse.getRes().getUser().getName());
dash_winnerTxt.setText(Constants.profileResponse.getRes().getWinner() + "");
dash_winnerTxt2.setText(Constants.profileResponse.getRes().getWinner() + "");
dash_allBidsTxt.setText(Constants.profileResponse.getRes().getRegistered() + "");
dash_allBidsTxt2.setText(Constants.profileResponse.getRes().getRegistered() + "");
dash_bougthTxt.setText(Constants.profileResponse.getRes().getBought() + "");
dash_notWinTxt.setText(Constants.profileResponse.getRes().getRegistered() - Constants.profileResponse.getRes().getWinner() + "");
Glide.with(context)
.load(Constants.SERVERImg + Constants.profileResponse.getRes().getUser().getAvatarFile())
.asBitmap()
.centerCrop()
//.diskCacheStrategy(DiskCacheStrategy.NONE)
//.skipMemoryCache(true)
.signature(new StringSignature(String.valueOf(System.currentTimeMillis())))
.into(new BitmapImageViewTarget(addPhoto) {
@Override
protected void setResource(Bitmap resource) {
RoundedBitmapDrawable circularBitmapDrawable =
RoundedBitmapDrawableFactory.create(context.getResources(), resource);
circularBitmapDrawable.setCircular(true);
addPhoto.setImageDrawable(circularBitmapDrawable);
}
});
addPhoto.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
getImageFromGallery();
}
});
} catch (Exception e) {
}
}
}, 1000);
} else {
v = inflater.inflate(R.layout.fragment_no_login_dash, null);
noLoginFrag_btn = v.findViewById(R.id.noLoginFrag_btn);
noLoginFrag_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startActivity(new Intent(context, RegisterPhoneActivity.class));
getActivity().finish();
}
});
}
return v;
}
@Override
public void onActivityResult(final int requestCode, int resultCode, Intent data) {
if (requestCode == 0 && resultCode == RESULT_OK) {
imageCropFunction();
} else if (requestCode == 2) {
if (data != null) {
uri = data.getData();
imageCropFunction();
}
} else if (requestCode == 1) {
if (data != null) {
Bundle bundle = data.getExtras();
Bitmap bitmap = bundle.getParcelable("data");
base64String = Base64ConverterUtils.convert(bitmap);
Bitmap bitmap1 = Base64ConverterUtils.convert(base64String);
addPhoto.setImageBitmap(bitmap1);
profileProgress.setVisibility(View.VISIBLE);
addPhoto.setVisibility(View.GONE);
Call<ProfileResponse> call = apIs.getUploadBase64Avatar(sendBase64Image(prefsUtils.getFromShared(PrefsKeys.PHONE_NUMBER.name()), base64String, "jpg"));
call.enqueue(new Callback<ProfileResponse>() {
@Override
public void onResponse(Call<ProfileResponse> call, Response<ProfileResponse> response) {
if (response.body().getStatus().equals("ok")) {
profileProgress.setVisibility(View.GONE);
addPhoto.setVisibility(View.VISIBLE);
Glide.with(context)
.load(Constants.SERVERImg + Constants.profileResponse.getRes().getUser().getAvatarFile())
.asBitmap()
.centerCrop()
//.diskCacheStrategy(DiskCacheStrategy.NONE)
//.skipMemoryCache(true)
.signature(new StringSignature(String.valueOf(System.currentTimeMillis())))
.into(new BitmapImageViewTarget(addPhoto) {
@Override
protected void setResource(Bitmap resource) {
RoundedBitmapDrawable circularBitmapDrawable =
RoundedBitmapDrawableFactory.create(context.getResources(), resource);
circularBitmapDrawable.setCircular(true);
addPhoto.setImageDrawable(circularBitmapDrawable);
}
});
}
}
@Override
public void onFailure(Call<ProfileResponse> call, Throwable t) {
profileProgress.setVisibility(View.GONE);
}
});
}
}
}
private void imageCropFunction() {
try {
CropIntent = new Intent("com.android.camera.action.CROP");
CropIntent.setDataAndType(uri, "image/*");
CropIntent.putExtra("crop", "true");
CropIntent.putExtra("outputX", 200);
CropIntent.putExtra("outputY", 200);
CropIntent.putExtra("aspectX", 3);
CropIntent.putExtra("aspectY", 3);
CropIntent.putExtra("scaleUpIfNeeded", true);
CropIntent.putExtra("return-data", true);
startActivityForResult(CropIntent, 1);
} catch (ActivityNotFoundException e) {
}
}
private void getImageFromGallery() {
GalIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(Intent.createChooser(GalIntent, "Select image"), 2);
}
我该如何解决?
NullPointerException告诉您,您正在尝试对对象执行某些操作,该对象似乎为空。 您将不得不调试为什么传递给函数的位图(不是base64表示形式)为null,也许您将其错误地放入了参数Bundle中。
很难给出正确的答案,因为我看不到异常标记的哪几行,因此您必须自己做一点:)
因为位图为空,所以导致错误。
声明位图位图; 作为全局变量。
并在onActivityResult方法中使用位图对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.