Compressor icon indicating copy to clipboard operation
Compressor copied to clipboard

java.lang.NullPointerException: Attempt to invoke virtual method 'int android.graphics.Bitmap.getWidth()' on a null object reference

Open yliang11 opened this issue 8 years ago • 22 comments

When I choose some pictures,it may happen,how can i fix it?

at id.zelory.compressor.ImageUtil.getScaledBitmap(ImageUtil.java:62) actualWidth = bitmap2.getWidth();

java.lang.NullPointerException: Attempt to invoke virtual method 'int android.graphics.Bitmap.getWidth()' on a null object reference

yliang11 avatar Apr 27 '17 08:04 yliang11

I meet the same problem,as well

yuhaodev avatar Jun 14 '17 06:06 yuhaodev

@yliang11,@yuhaodev this error occur because the application does not have permission to access the image. In my case it worked just by asking for permission in runtime !

IgorHorta avatar Jul 04 '17 18:07 IgorHorta

@IgorHorta it's not the problem of permission, not every picture can happen,some picture will happen,but some not.I dont know why

yliang11 avatar Jul 18 '17 03:07 yliang11

I have the same problem. For some pictures it's working but for some I get error. Even when I have permissions when calling compressToFile I get

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.graphics.Bitmap.getWidth()' on a null object reference

Also in logs I see

07-19 20:38:11.210 31609-32413/com.blenge.blenge.debug I/ExifInterface_JNI: Corrupted image.
07-19 20:38:11.296 31609-32413/com.blenge.blenge.debug W/ExifInterface: Invalid image: ExifInterface got an unsupported image format file(ExifInterface supports JPEG and some RAW image formats only) or a corrupted JPEG file to ExifInterface.
                                                                        java.io.EOFException
                                                                            at java.io.DataInputStream.readByte(DataInputStream.java:270)
                                                                            at android.media.ExifInterface.getJpegAttributes(ExifInterface.java:1834)
                                                                            at android.media.ExifInterface.loadAttributes(ExifInterface.java:1475)
                                                                            at android.media.ExifInterface.<init>(ExifInterface.java:1112)
                                                                            at id.zelory.compressor.ImageUtil.decodeSampledBitmapFromFile(ImageUtil.java:60)
                                                                            at id.zelory.compressor.ImageUtil.compressImage(ImageUtil.java:33)
                                                                            at id.zelory.compressor.Compressor.compressToFile(Compressor.java:60)
                                                                            at id.zelory.compressor.Compressor.compressToFile(Compressor.java:56)

Mistic92 avatar Jul 19 '17 18:07 Mistic92

@IgorHorta I also have the same problem.When called setDestinationDirectoryPath() method, I set to my source file path as a result path that is setDestinationDirectoryPath(sourceFilePath) ,so I meet this error.

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.graphics.Bitmap.getWidth()' on a null object reference at id.zelory.compressor.ImageUtil.decodeSampledBitmapFromFile(ImageUtil.java:70) at id.zelory.compressor.ImageUtil.compressImage(ImageUtil.java:33) at id.zelory.compressor.Compressor.compressToFile(Compressor.java:60) at id.zelory.compressor.Compressor.compressToFile(Compressor.java:56)

lilealyh avatar Aug 17 '17 08:08 lilealyh

This happens when you set the destination directory same as that of the original image file. A work-around is to set a different directory for the compressed image.

hkk595 avatar Aug 22 '17 05:08 hkk595

How fix?

zkjmyy avatar Aug 28 '17 07:08 zkjmyy

@hkk565 I want set the same destination directory so that to cover the old image.How to fix this bug?Thanks

lilealyh avatar Aug 31 '17 03:08 lilealyh

@lilealyh I don't recommend you overwriting the original image directly. Because if the compression process somehow fails in the middle, the original image will be destroyed as well. If you have to do this, a work-around is to generate the compressed image file at a different temporary directory first (such as the external cache directory). When it's done, delete the original image file and move the compressed image file to the original directory (using Android I/O APIs).

hkk595 avatar Sep 19 '17 02:09 hkk595

.setDestinationDirectoryPath(Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_PICTURES).getAbsolutePath())
this method save the image into internal storage and Compressor class does not support this format so u have to store as a temporary into internal storage .i hope its useful for u. thank you

vikasgupta4190 avatar Oct 30 '17 05:10 vikasgupta4190

Solution:the reason is that you save your compressed file in the same folder and name with original image, just use compressToFile(File imageFile, String compressedFileName) to set a different name with the original image.

18705320883 avatar Nov 08 '17 01:11 18705320883

I have same issue. I had use "compressToFile(File imageFile, String compressedFileName) to set a different name with the original image." but the error continues

private File compressImageAnotherLibrary(int width, int height, int quality, File file) {

      try {
          return new Compressor(mContext)
                  .setQuality(quality)
                  .setMaxWidth(width)
                  .setDestinationDirectoryPath(new FileOperations().createMediaFile(Message.messageType.image.toString(), imageExtension, false).getAbsolutePath())
                  .setMaxHeight(height)
                  .setCompressFormat(Bitmap.CompressFormat.JPEG)
                  .compressToFile(file);

      } catch (IOException e) {
          Mylog.printStackTrace(TAG + "compressImageAnotherLibrary error ", e);

          return null;
      }
  }

Please help me!!

gelbertgel avatar Nov 29 '17 11:11 gelbertgel

I have this error! how can i fix it?

tellfa avatar Jun 12 '18 09:06 tellfa

How con I fix this error? I don't know how to continue with the compressor

java.lang.NullPointerException: Attempt to invoke virtual method 'int android.graphics.Bitmap.getWidth()' on a null object reference at id.zelory.compressor.ImageUtil.decodeSampledBitmapFromFile(ImageUtil.java:70) at id.zelory.compressor.ImageUtil.compressImage(ImageUtil.java:33) at id.zelory.compressor.Compressor.compressToFile(Compressor.java:60) at id.zelory.compressor.Compressor.compressToFile(Compressor.java:56)

Thank you!

mpardalm avatar Jun 26 '18 07:06 mpardalm

if (actualImage == null) { showError("Please choose an image!"); } else {

        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inPreferredConfig = Bitmap.Config.ARGB_8888;
        Bitmap bitmap =

BitmapFactory.decodeFile(actualImage.getAbsolutePath(), options);

        if(!(bitmap.getWidth() == 0 && bitmap.getHeight() == 0)) {
            // Compress image in main thread using custom Compressor
            compressedImage = new Compressor.Builder(this)
                    .setMaxWidth(1376)
                    .setMaxHeight(756)
                    .setQuality(90)
                    .setCompressFormat(Bitmap.CompressFormat.JPEG)

.setDestinationDirectoryPath(Environment.getExternalStoragePublicDirectory(

Environment.DIRECTORY_PICTURES+"/engcomm").getAbsolutePath()) .build() .compressToFile(actualImage); setCompressedImage();

        }

On Wed, Nov 29, 2017 at 4:48 PM, gelbertgel [email protected] wrote:

I have same issue. Please help me.


private File compressImageAnotherLibrary(int width, int height, int
quality, File file) {

    try {
        return new Compressor(mContext)
                .setQuality(quality)
                .setMaxWidth(width)
                .setDestinationDirectoryPath(new FileOperations().createMediaFile(Message.messageType.image.toString(), imageExtension, false).getAbsolutePath())
                .setMaxHeight(height)
                .setCompressFormat(Bitmap.CompressFormat.JPEG)
                .compressToFile(file);

    } catch (IOException e) {
        Mylog.printStackTrace(TAG + "compressImageAnotherLibrary error ", e);

        return null;
    }
}

—
You are receiving this because you commented.
Reply to this email directly, view it on GitHub
<https://github.com/zetbaitsu/Compressor/issues/49#issuecomment-347830404>,
or mute the thread
<https://github.com/notifications/unsubscribe-auth/AQfbER3fvl-EVNd75AWmqLFuqiaSRjtZks5s7T2agaJpZM4NJ4Ca>
.

vikasgupta4190 avatar Jun 28 '18 16:06 vikasgupta4190

if (actualImage == null) { showError("Please choose an image!"); } else {

BitmapFactory.Options options = new BitmapFactory.Options(); options.inPreferredConfig = Bitmap.Config.ARGB_8888; Bitmap bitmap = BitmapFactory.decodeFile(actualImage.getAbsolutePath(), options);

if(!(bitmap.getWidth() == 0 && bitmap.getHeight() == 0)) { // Compress image in main thread using custom Compressor compressedImage = new Compressor.Builder(this) .setMaxWidth(1376) .setMaxHeight(756) .setQuality(90) .setCompressFormat(Bitmap.CompressFormat.JPEG) .setDestinationDirectoryPath(Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_PICTURES+"/engcomm").getAbsolutePath()) .build() .compressToFile(actualImage); setCompressedImage();

}

On Tue, Jun 26, 2018 at 1:15 PM, Miguel Pardal [email protected] wrote:

How con I fix this error? I don't know how to continue with the compressor

java.lang.NullPointerException: Attempt to invoke virtual method 'int android.graphics.Bitmap.getWidth()' on a null object reference at id.zelory.compressor.ImageUtil.decodeSampledBitmapFromFile( ImageUtil.java:70) at id.zelory.compressor.ImageUtil.compressImage(ImageUtil.java:33) at id.zelory.compressor.Compressor.compressToFile(Compressor.java:60) at id.zelory.compressor.Compressor.compressToFile(Compressor.java:56)

Thank you!

— You are receiving this because you commented. Reply to this email directly, view it on GitHub https://github.com/zetbaitsu/Compressor/issues/49#issuecomment-400212902, or mute the thread https://github.com/notifications/unsubscribe-auth/AQfbEcMGYLZ2Z7WclVnB9V4jLgK7w-O_ks5uAeargaJpZM4NJ4Ca .

vikasgupta4190 avatar Jun 28 '18 16:06 vikasgupta4190

if (actualImage == null) { showError("Please choose an image!"); } else {

BitmapFactory.Options options = new BitmapFactory.Options(); options.inPreferredConfig = Bitmap.Config.ARGB_8888; Bitmap bitmap = BitmapFactory.decodeFile(actualImage.getAbsolutePath(), options);

if(!(bitmap.getWidth() == 0 && bitmap.getHeight() == 0)) { // Compress image in main thread using custom Compressor compressedImage = new Compressor.Builder(this) .setMaxWidth(1376) .setMaxHeight(756) .setQuality(90) .setCompressFormat(Bitmap.CompressFormat.JPEG) .setDestinationDirectoryPath(Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_PICTURES+"/engcomm").getAbsolutePath()) .build() .compressToFile(actualImage); setCompressedImage();

}

On Tue, Jun 12, 2018 at 2:44 PM, Mohammad [email protected] wrote:

I have this error! how can i fix it?

— You are receiving this because you commented. Reply to this email directly, view it on GitHub https://github.com/zetbaitsu/Compressor/issues/49#issuecomment-396522578, or mute the thread https://github.com/notifications/unsubscribe-auth/AQfbEcmIBTJhHVXt27EWFea-Zm5JhZZWks5t74aRgaJpZM4NJ4Ca .

vikasgupta4190 avatar Jun 28 '18 16:06 vikasgupta4190

If it helps anyone else, I get the error when I try to compress an empty file. My solution was to check the file size before invoking the compression library (and also investigate why I my app has empty files in the first place):

if(photoFile != null && photoFile.length() > 0){
    File compressed = new Compressor(this).compressToFile(photoFile);
}

mbosecke avatar Sep 10 '18 16:09 mbosecke

Using the same directory between original and compressed was my cause of this error. Would be nice to see a proper error instead of this one that doesn't really help.

Thank you for the people that mentioned that option!

jlubeck avatar May 29 '19 20:05 jlubeck

Choiced the output image to compress was my cause of this error. I resolve this problem with delete the output image after using it.

codwb avatar Aug 16 '19 08:08 codwb

Hi Guys add image temp file storage it's working fine

private void openCamera() throws IOException { Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); photoFile = createImageFile(); photoURI = FileProvider.getUriForFile(getActivity(), getActivity().getPackageName() + ".provider", photoFile); intent.putExtra(MediaStore.EXTRA_OUTPUT, FileProvider.getUriForFile(getActivity(), getActivity().getPackageName() + ".provider", photoFile)); startActivityForResult(intent, IMAGE_CAPTURE_CODE); } private File createImageFile() throws IOException { // Create an image file name File storageDir = getActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES); image = File.createTempFile( "temp", /* prefix / ".jpg", / suffix / storageDir / directory */ ); // Log.e(TAG, "createImageFile: "+image.getAbsolutePath() ); mImageFileLocation = image.getAbsolutePath(); if (image.exists()) { image.delete(); } return image; }

BitmapFactory.Options bmOptions = new BitmapFactory.Options(); bmOptions.inJustDecodeBounds = true; BitmapFactory.decodeFile(mImageFileLocation, bmOptions); int cameraImageWidth = bmOptions.outWidth; int cameraImageHeight = bmOptions.outHeight;

        int scaleFactor = Math.min(cameraImageWidth / targetImageViewWidth, cameraImageHeight / targetImageViewHeight);
        bmOptions.inSampleSize = scaleFactor;
        bmOptions.inJustDecodeBounds = false;
        Bitmap photoReducedSizeBitmp = BitmapFactory.decodeFile(mImageFileLocation, bmOptions);

       /* BitmapFactory.Options options = new BitmapFactory.Options();
        options.inPreferredConfig = Bitmap.Config.ARGB_8888;
        Bitmap photoReducedSizeBitmp = BitmapFactory.decodeFile(mImageFileLocation, options);

*/

        try {
            compressedImageFile = new Compressor(Objects.requireNonNull(getActivity())).compressToFile(new File(mImageFileLocation));

        } catch (IOException e) {
            e.printStackTrace();
        }

Sainathhiwale avatar Feb 29 '20 19:02 Sainathhiwale

我的方式

1.    compileOnly "androidx.exifinterface:exifinterface:1.3.2"
2.    replace `android.media.ExifInterface` with `androidx.exifinterface.media.ExifInterface`

javakam avatar Dec 10 '20 08:12 javakam