Bitmap Compressor()返回空指针异常

时间:2018-03-14 12:56:03

标签: java android firebase firebase-realtime-database firebase-storage

我在片段中使用此方法压缩图片,如果我没有弄错,然后将其上传到google firebase服务器:

Bitmap thumb_bitmap = new Compressor(this.getActivity())
                    .setMaxWidth(200)
                    .setMaxHeight(200)
                    .setQuality(75)
                    .compressToBitmap(thumb_filePath);

我最终从Android Studio收到以下错误:

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

这是该方法的其余代码:

private void uploadImage() {

        if (filePath[0] != null && filePath[1] != null) {

            final ProgressDialog progressDialog = new ProgressDialog(getActivity());
            //progressDialog.setTitle("Uploading...");
            //progressDialog.show();

            for ( Uri path : filePath ) {

                id_or_proof += 1;

                File thumb_filePath = new File(path.getPath());

                Log.d ( "THUMB FILE PATH", path.getPath() );

                String current_user_id = mCurrentUser.getUid();

                Bitmap thumb_bitmap = new Compressor(this.getActivity())
                        .setMaxWidth(200)
                        .setMaxHeight(200)
                        .setQuality(75)
                        .compressToBitmap(thumb_filePath);

                Log.d (  "BITMAP", String.valueOf(thumb_bitmap));

                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                thumb_bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
                final byte[] thumb_byte = baos.toByteArray();

                StorageReference filepath = mImageStorage.child("profile_images").child(current_user_id + ".jpg");
                final StorageReference thumb_filepath = mImageStorage.child("profile_images").child("thumbs").child(current_user_id + ".jpg");


                filepath.putFile(path).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {

                        if(task.isSuccessful()){

                            final String download_url = task.getResult().getDownloadUrl().toString();

                            UploadTask uploadTask = thumb_filepath.putBytes(thumb_byte);
                            uploadTask.addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
                                @Override
                                public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> thumb_task) {

                                    String thumb_downloadUrl = thumb_task.getResult().getDownloadUrl().toString();

                                    if(thumb_task.isSuccessful()){

                                        if ( id_or_proof == 1 ) {
                                            Map update_hashMap = new HashMap();
                                            update_hashMap.put("id_image", download_url);
                                            update_hashMap.put("thumb_id_image", thumb_downloadUrl);

                                            mUserDatabase.updateChildren(update_hashMap).addOnCompleteListener(new OnCompleteListener<Void>() {
                                                @Override
                                                public void onComplete(@NonNull Task<Void> task) {

                                                    if (task.isSuccessful()) {

                                                        mProgressDialog.dismiss();
                                                        Toast.makeText(getActivity(), "Success Uploading.", Toast.LENGTH_LONG).show();

                                                    }

                                                }
                                            });
                                        }


                                        if ( id_or_proof == 2 ) {
                                            Map update_hashMap = new HashMap();
                                            update_hashMap.put("proof_image", download_url);
                                            update_hashMap.put("thumb_proof_image", thumb_downloadUrl);

                                            mUserDatabase.updateChildren(update_hashMap).addOnCompleteListener(new OnCompleteListener<Void>() {
                                                @Override
                                                public void onComplete(@NonNull Task<Void> task) {

                                                    if (task.isSuccessful()) {

                                                        mProgressDialog.dismiss();
                                                        Toast.makeText(getActivity(), "Success Uploading.", Toast.LENGTH_LONG).show();

                                                    }

                                                }
                                            });
                                        }

                                    } else {

                                        Toast.makeText(getActivity(), "Error in uploading thumbnail.", Toast.LENGTH_LONG).show();
                                        mProgressDialog.dismiss();

                                    }


                                }
                            });



                        } else {

                            Toast.makeText(getActivity(), "Error in uploading.", Toast.LENGTH_LONG).show();
                            mProgressDialog.dismiss();

                        }

                    }
                });

            }// end of for

        }// end of if ()

    } // end of uploadImage()

我需要帮助才能弄清楚为什么我会收到错误,以及我如何解决错误。

非常赞赏。

这里是logcat:

03-14 15:36:57.383 2780-2780/in.tvac.akshaye.lapitchat E/BitmapFactory: Unable to decode stream: java.io.FileNotFoundException: /document/60 (No such file or directory) 03-14 15:36:57.383 2780-2780/in.tvac.akshaye.lapitchat E/BitmapFactory: Unable to decode stream: java.io.FileNotFoundException: /document/60 (No such file or directory) 03-14 15:36:57.383 2780-2780/in.tvac.akshaye.lapitchat D/BITMAP: null 03-14 15:36:57.383 2780-2780/in.tvac.akshaye.lapitchat D/AndroidRuntime: Shutting down VM 03-14 15:36:57.384 2780-2780/in.tvac.akshaye.lapitchat E/AndroidRuntime: FATAL EXCEPTION: main Process: in.tvac.akshaye.lapitchat, PID: 2780 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 in.tvac.akshaye.lapitchat.PersonalInforamtionFragment.uploadImage(PersonalInforamtionFragment.java:649) at in.tvac.akshaye.lapitchat.PersonalInforamtionFragment.access$1900(PersonalInforamtionFragment.java:57) at in.tvac.akshaye.lapitchat.PersonalInforamtionFragment$8.onComplete(PersonalInforamtionFragment.java:767) at com.google.android.gms.tasks.zzc$1.run(Unknown Source:23) at android.os.Handler.handleCallback(Handler.java:790) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:164) at android.app.ActivityThread.main(ActivityThread.java:6494) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)

2 个答案:

答案 0 :(得分:2)

您似乎将错误的Uri传递给新文件,因此找不到您的文件。

从外部存储中获取。

如果您尝试从外部存储中获取文件,则必须添加此权限:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

然后创建如下路径:

String filePath = Environment.getExternalStorageDirectory() + "/document/60";
Uri path = Uri.parse(filePath);

从应用存储中获取

如果您尝试从App Storage获取文件,只需像这样构建您的Uri:

String filePath = getActivity().getFilesDir() + "/document/60";
Uri path = Uri.parse(filePath);

答案 1 :(得分:0)

使用正确的上下文

Bitmap thumb_bitmap = new Compressor(this.getActivity())
                        .setMaxWidth(200)
                        .setMaxHeight(200)
                        .setQuality(75)
                        .compressToBitmap(thumb_filePath);

将其替换为

Bitmap thumb_bitmap = new Compressor(getActivity())
                            .setMaxWidth(200)
                            .setMaxHeight(200)
                            .setQuality(75)
                            .compressToBitmap(thumb_filePath);

路径也应该正确