web-dev-qa-db-fra.com

Exception de pointeur nul lors d'une tentative de compression de bitmap

Je reçois une exception de pointeur null lorsque j'essaie de compresser une image bitmap afin de l'envoyer à un ByteArrayOutputStream afin d'obtenir un tableau d'octets. J'ai besoin de ce tableau d'octets pour pouvoir télécharger l'image dans ma base de données Parse en tant que fichier Parse. L'erreur de journal est indiquée ci-dessous.

01-11 23:29:41.522 32015-32015/com.example.whhsfbla.fashionnow E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.whhsfbla.fashionnow, PID: 32015
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.example.whhsfbla.fashionnow.PostActivity.uploadPost(PostActivity.Java:140)
    at com.example.whhsfbla.fashionnow.PostActivity.access$100(PostActivity.Java:34)
    at com.example.whhsfbla.fashionnow.PostActivity$2.onClick(PostActivity.Java:92)
    at Android.view.View.performClick(View.Java:5254)
    at Android.view.View$PerformClick.run(View.Java:21179)
    at Android.os.Handler.handleCallback(Handler.Java:739)
    at Android.os.Handler.dispatchMessage(Handler.Java:95)
    at Android.os.Looper.loop(Looper.Java:145)
    at Android.app.ActivityThread.main(ActivityThread.Java:6837)
    at Java.lang.reflect.Method.invoke(Native Method)
    at Java.lang.reflect.Method.invoke(Method.Java:372)
    at com.Android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.Java:1404)
    at com.Android.internal.os.ZygoteInit.main(ZygoteInit.Java:1199)

La ligne qui cause l'erreur est bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);

    public class PostActivity extends Activity {

    private final int SELECT_PHOTO = 1;
    private InputStream imageStream;
    private Uri uploadFileUri;
    private Bitmap bitmap;
    private TextView txtPostTitle;
    private EditText editText;
    private Button btnChoosePic, btnUploadPost;
    private ImageView imgPreview;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_post);

        txtPostTitle = (TextView) findViewById(R.id.txtPostTitle);
        editText = (EditText) findViewById(R.id.editText);
        btnChoosePic = (Button) findViewById(R.id.btnChoosePic);
        btnUploadPost = (Button) findViewById(R.id.btnMakePost);
        imgPreview = (ImageView) findViewById(R.id.imgPreview);

        txtPostTitle.setText("Title:");
        btnChoosePic.setText("Choose Picture");
        btnUploadPost.setText("Create Post");
        btnUploadPost.setEnabled(false);

        /*btnChoosePic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    openImageIntent();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }); */

        btnChoosePic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    openImageIntent();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });

        btnUploadPost.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                uploadPost();
                finish();
            }
        });

    }

    private void openImageIntent() throws IOException {
        final File root = new File(Environment.getExternalStorageDirectory() +
                File.separator + "MyDir" + File.separator);
        root.mkdirs();
        final String fileName = File.createTempFile("tmp", ".txt").getPath();
        final File sdImageMainDirectory = new File(root, fileName);

        uploadFileUri = Uri.fromFile(sdImageMainDirectory);

        //Camera
        final List<Intent> cameraIntents = new ArrayList<Intent>();
        final Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        final PackageManager packageManager = getPackageManager();
        final List<ResolveInfo> resolveInfoList = packageManager.queryIntentActivities(captureIntent, 0);
        for (ResolveInfo res : resolveInfoList) {
            final String packageName = res.activityInfo.packageName;
            final Intent intent = new Intent(captureIntent);
            intent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
            intent.setPackage(packageName);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uploadFileUri);
            cameraIntents.add(intent);
        }

        //Filesystem
        final Intent galleryIntent = new Intent();
        galleryIntent.setType("image/*");
        galleryIntent.setAction(Intent.ACTION_GET_CONTENT);

        final Intent chooserIntent = Intent.createChooser(galleryIntent, "Select Source");

        chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray(new Parcelable[cameraIntents.size()]));

        startActivityForResult(chooserIntent, SELECT_PHOTO);
    }

    private void uploadPost() {
        // Locate the image in res > drawable-hdpi
        bitmap = BitmapFactory.decodeResource(getResources(), R.id.imgPreview);
        // Convert it to byte
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        // Compress image to lower quality scale 1 - 100
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
        byte[] image = stream.toByteArray();

        // Create the ParseFile
        ParseFile file = new ParseFile("image.png",image);
        // Upload the image into ParseCloud
        file.saveInBackground();

        // Create a New Class called "ImageUpload" in Parse
        ParseObject post = new ParseObject("Post");

        // Create a column named "ImageName" and set the string
        post.put("title", editText.getText().toString());

        // Create a column named "ImageFile" and insert the image
        post.put("ImageFile", file);

        post.put("user", User.username);

        // Create the class and the columns
        post.saveInBackground();

        // Show a simple toast message
        Toast.makeText(PostActivity.this, "Post Uploaded",
                Toast.LENGTH_SHORT).show();


    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent imageIntent) {
        super.onActivityResult(requestCode, resultCode, imageIntent);

        if (resultCode == RESULT_OK) {
            if (requestCode == SELECT_PHOTO) {
                //Get the URI
                final boolean isCamera;
                if (imageIntent == null) {
                    isCamera = true;
                } else {
                    final String action = imageIntent.getAction();
                    if (action == null) {
                        isCamera = false;
                    } else {
                        isCamera = action.equals(MediaStore.ACTION_IMAGE_CAPTURE);

                    }
                }

                Uri selectedImageUri;
                if (isCamera) {
                    selectedImageUri = uploadFileUri;
                } else {
                    selectedImageUri = imageIntent == null ? null : imageIntent.getData();
                }

                //Get the Bitmap from the URI, and set it to the ImageView
                try {
                    imageStream = getContentResolver().openInputStream(selectedImageUri);
                    final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
                    imgPreview.setImageBitmap(selectedImage);
                    btnUploadPost.setEnabled(true);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
4

Vous obtenez une exception de pointeur null car bitmap est null. Remplace la ligne qui va

bitmap = BitmapFactory.decodeResource(getResources(), R.id.imgPreview);

avec ça

bitmap = ((BitmapDrawable) imgPreview.getDrawable()).getBitmap();
9
Kartik Prabhu

si vous utilisez le format PNG, votre image ne sera pas compressée, car le format PNG est un format sans perte. utilisez JPEG pour compresser votre image et utilisez 0 au lieu de 100 en qualité.

puis utiliser

Bitmap decoded = BitmapFactory.decodeStream(new ByteArrayInputStream(stream.toByteArray()));
1
garima

Une erreur peut se produire lorsque bitmap est null.

Declare Bitmap bitmap; en tant que variable globale.

Et utilisez l'objet bitmap dans votre méthode onActivityResult .

0
shyam

Essayez d’utiliser Bitmap.createScaledBitmap

Bitmap.createScaledBitmap(Bitmap src, int dstWidth, int dstHeight, boolean filter);

0
Aby Mathew