How Do I Save Image File on SDK 27?


Ask A Question





Login To post a question

I want to save the captured bitmap. My minSDK is 19 and targetSDK is 27.

So, I want it to work for both SDK<23 and SDK>=23

I keep getting this error :

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.afm.testitall/com.afm.testitall.ViewEditExtractedText}:

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

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method

'int android.graphics.Bitmap.getWidth()' on a null object reference

Here is my Code :

Added camera & storage permission for SDK<23 in Manifest :

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

Capturing the photo in onCreate Method :

capture.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                        requestPermissions(new String[]{Manifest.permission.CAMERA}, cameraPermissionCode);
                    } else {    
                        Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);        
                        startActivityForResult(cameraIntent, cameraRequestCode);
                    }
                }
            }
        });

Calling the function in onActivityResult method :

Bitmap photo = (Bitmap) data.getExtras().get("data");
saveToInternalStorage(photo);

Body of function :

private String saveToInternalStorage(Bitmap bitmap) {

    ContextWrapper cw = new ContextWrapper(getApplicationContext());

    File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);

    File imageFilePath = new File(directory,"temp.jpg");

    FileOutputStream fileOutputStream = null;

    try {

      fileOutputStream = new FileOutputStream(imageFilePath);
      bitmap.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            fileOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return directory.getAbsolutePath();
}

And I am using this Code to Open the file :

private void loadImageFromStorage(String path) {

    try {
        File imageFile = new File(path, "profile.jpg");
        Bitmap bitmap = BitmapFactory.decodeStream(new FileInputStream(imageFile));
        selectedImage.setImageBitmap(bitmap);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
}

For more info please click herehttps://stackoverflow.com/q/51846423



Have a question or need a custom quote?
info@smartinfocare.com