2017-12-12 6 views
-1

私のアプリケーションでギャラリー作物から画像を選択したい場合はbase64に変換してください。私のアプリケーションで
写真アプリから画像を選択すると、boolean android.graphics.Bitmap.compressを修正する方法はありますか?

私は、これはその後、を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); 

    } 

+0

Androidは 'CROP'' Intent'を持っていません。多くの[Android用の画像トリミングライブラリ](https://android-arsenal.com/tag/45)があります。 1つを使用してください。また、(ActivityNotFoundException'のように)例外を無視しないでください。 – CommonsWare

+0

@CommonsWare、上記のコードで私にコードを送信できますか? – Ketrt

答えて

0

NullPointerExceptionは、nullであると思われるオブジェクトで何かをしようとしていることを伝えます。 関数に渡されたビットマップ(base64表現ではない)がnullである理由をデバッグする必要があります。おそらく、引数Bundleに間違って入れます。

私はどの行例外マークを見ることができないので、自分でビットをしなければならないので、適切な答えを与えるのは難しいです:)

+0

私の上記のコードで私にコードを送ることができますか? please – Ketrt

+0

Base64ConverterUtilsのbitmap.compress()行のビットマップがnullなので、なぜnullであるのかを確認する必要があります – Xirate

関連する問題