0

I have the camera up and running, and saving the picture to my phone, but I now want to display it in an ImageView that I have set up, and then once more every time the app is launched after that. Any suggestions on how I can expand upon what I already have to achieve this?

My camera code is as follows:

private void takePic() {
    Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
    File pictureDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
    String pictureName = "Avatar.jpg";
    File imageFile = new File(pictureDirectory, pictureName);
    Uri pictureUri = Uri.fromFile(imageFile);
    cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, pictureUri);
    startActivityForResult(cameraIntent, CAMERA_REQUEST);
}

And I have a button that simply calls on takePic(). I had an onActivityResult() before that looked like this:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
        Bitmap photo = (Bitmap) data.getExtras().get("data");
        AvatarMe.setImageBitmap(photo);
    }
}

I used this to simply display the thumbnail in my ImageView, but when I modified the code to save the picture I had to remove it, otherwise the app would crash. It seems Android won't let me do both, so I need some help to figure out how I can do that.

So basically I want to take a picture, display it in my ImageView, and save it so that if the app is killed after the picture has been taken I can just fill the ImageView with the saved picture.

PQuix
  • 83
  • 2
  • 10

4 Answers4

0

You can do it with picasso library.

Murat Güç
  • 377
  • 4
  • 9
0

In your onActivityResult() data is coming from intent but you have to save into internal storage and show in imageview, have look.

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)
{
if (resultCode == Activity.RESULT_OK)
{
    Bitmap bmp = (Bitmap)data.getExtras().get("data");
    ByteArrayOutputStream stream = new ByteArrayOutputStream();

    bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
    byte[] byteArray = stream.toByteArray();

    //saving image into internal storage

    File myfile = new File(Environment.getExternalStorageDirectory(),"yourfilename.jpg");

    FileOutputStream fo;
    try {
        myfile.createNewFile();
        fo = new FileOutputStream(myfile);
        fo.write(byteArray);
        fo.flush();
        fo.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    // convert byte array to Bitmap

    Bitmap bitmap = BitmapFactory.decodeByteArray(byteArray, 0,
            byteArray.length);

    imageView.setImageBitmap(bitmap);

}
}
}

Happy coding!!

Hemant Parmar
  • 3,924
  • 7
  • 25
  • 49
0

you can use picasso library or you can my approach that i use that compress tha image and this ImageCompression class `

private Context context;
float maxHeight;
float maxWidth;
boolean wantSave;

public ImageCompression(Context context) {
    this.context = context;
}

public ImageCompression(Context context, float maxHeight, float maxWidth, boolean wantSave) {
    this.context = context;
    this.maxHeight = maxHeight;
    this.maxWidth = maxWidth;
    this.wantSave = wantSave;
}

@Override
protected Bitmap doInBackground(String... strings) {
    if (strings.length == 0 || strings[0] == null)
        return null;

    return compressImage(strings[0]);
}

protected void onPostExecute(Bitmap imagePath) {
    // imagePath is path of new compressed image.
}


public Bitmap compressImage(String imagePath) {
    // to check if image is exist or not
    File checkFile = new File(imagePath);
    if (!checkFile.exists()) {
        return null;
    }

    Bitmap scaledBitmap = null;
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    Bitmap bmp = BitmapFactory.decodeFile(imagePath, options);

    int actualHeight = options.outHeight;
    int actualWidth = options.outWidth;

    float imgRatio = (float) actualWidth / (float) actualHeight;
    float maxRatio = maxWidth / maxHeight;

    if (actualHeight > maxHeight || actualWidth > maxWidth) {
        if (imgRatio < maxRatio) {
            imgRatio = maxHeight / actualHeight;
            actualWidth = (int) (imgRatio * actualWidth);
            actualHeight = (int) maxHeight;
        } else if (imgRatio > maxRatio) {
            imgRatio = maxWidth / actualWidth;
            actualHeight = (int) (imgRatio * actualHeight);
            actualWidth = (int) maxWidth;
        } else {
            actualHeight = (int) maxHeight;
            actualWidth = (int) maxWidth;

        }
    }

    options.inSampleSize = calculateInSampleSize(options, actualWidth, actualHeight);
    options.inJustDecodeBounds = false;
    options.inDither = false;
    options.inPurgeable = true;
    options.inInputShareable = true;
    options.inTempStorage = new byte[16 * 1024];

    try {
        bmp = BitmapFactory.decodeFile(imagePath, options);
        scaledBitmap = Bitmap.createBitmap(actualWidth, actualHeight, Bitmap.Config.RGB_565);

        float ratioX = actualWidth / (float) options.outWidth;
        float ratioY = actualHeight / (float) options.outHeight;
        float middleX = actualWidth / 2.0f;
        float middleY = actualHeight / 2.0f;

        Matrix scaleMatrix = new Matrix();
        scaleMatrix.setScale(ratioX, ratioY, middleX, middleY);

        Canvas canvas = new Canvas(scaledBitmap);
        canvas.setMatrix(scaleMatrix);

        if (bmp != null) {
            canvas.drawBitmap(bmp, middleX - bmp.getWidth() / 2, middleY - bmp.getHeight() / 2, new Paint(Paint.FILTER_BITMAP_FLAG));
            bmp.recycle();
        }

        ExifInterface exif;
        try {
            exif = new ExifInterface(imagePath);
            int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 0);
            Matrix matrix = new Matrix();
            if (orientation == 6) {
                matrix.postRotate(90);
            } else if (orientation == 3) {
                matrix.postRotate(180);
            } else if (orientation == 8) {
                matrix.postRotate(270);
            }
            scaledBitmap = Bitmap.createBitmap(scaledBitmap, 0, 0, scaledBitmap.getWidth(), scaledBitmap.getHeight(), matrix, true);
        } catch (IOException e) {
            e.printStackTrace();
        }

        // these lines from 144 to 157 for save the new photo
        if (wantSave) {
            FileOutputStream out = null;
            String filepath = imagePath;
            try {
                out = new FileOutputStream(filepath);

                //write the compressed bitmap at the destination specified by filename.
                scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 80, out);

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

        return scaledBitmap;

    } catch (OutOfMemoryError exception) {
        exception.printStackTrace();
    }
    return null;
}

public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;

    if (height > reqHeight || width > reqWidth) {
        final int heightRatio = Math.round((float) height / (float) reqHeight);
        final int widthRatio = Math.round((float) width / (float) reqWidth);
        inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
    }
    final float totalPixels = width * height;
    final float totalReqPixelsCap = reqWidth * reqHeight * 2;

    while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) {
        inSampleSize++;
    }
    return inSampleSize;
}

}

then in onActivityResult call

 ImageCompression imageCompression = new ImageCompression(context, imageHeight, imageHeight, false) {
        @Override
        protected void onPostExecute(Bitmap bitmab) {
            super.onPostExecute(bitmab);
                try {
                    if (imagePath != null) {
                        mCropImageView.setImageBitmap(bitmab);
                    }
                } catch (OutOfMemoryError error) {
                    Toast.makeText(CropImageActivity.this, "OutOfMemory, no space", Toast.LENGTH_SHORT).show();
                }
        }
    };
    imageCompression.execute(imagePath);

i hope this will help

Mosa
  • 353
  • 2
  • 16
0

The "data" from the camera intent is null in this case. You can check this answer.

To solve this problem, you will have to make the uri you passed to the camera intent global.

//make this a global variable
Uri pictureUri = Uri.fromFile(imageFile);

then you can access the bitmap like this

void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK)
        {
            Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), pictureUri);
            AvatarMe.setImageBitmap(bitmap);
        }
    }

You can also store the pictureUri using a db or shared preference and reuse it later.

sauvik
  • 2,224
  • 1
  • 17
  • 25
  • After wrapping a try/catch around `bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), pictureUri); ` and a Toast in the catch, but it seems something goes wrong, as the Toast triggers. I tried putting Uri as a global variable, as you said, by defining it as `Uri pictureUri;` and then `pictureUri = uri.fromFile(imageFile);` in the method. – PQuix Nov 08 '17 at 13:51
  • Print the error in the catch block and let me know.. May be I'll be able to help you – sauvik Nov 08 '17 at 15:32
  • you probably have to take care of run time permissions as well https://stackoverflow.com/questions/39693082/filenotfoundexception-open-failed-eacces-permission-denied – sauvik Nov 08 '17 at 20:10