1

I follow this to rotate captured image. But I get error.

My Code

@Override

protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    super.onActivityResult(requestCode, resultCode, data);

    if (resultCode == RESULT_OK) {
        if (requestCode == 1) {
            //h=0;
            File f = new File(Environment.getExternalStorageDirectory().toString());
            for (File temp : f.listFiles()) {
                if (temp.getName().equals("temp.jpg")) {
                    f = temp;
                    File photo = new File(Environment.getExternalStorageDirectory(), "temp.jpg");
                    //pic = photo;
                    break;
                }
            }

               try {

                Bitmap bitmap;
                BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
                bitmapOptions.inJustDecodeBounds = false;
                bitmapOptions.inPreferredConfig = Bitmap.Config.RGB_565;
                bitmapOptions.inDither = true;
                bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(), bitmapOptions);
                BitmapFactory.Options opts = new BitmapFactory.Options();
                Bitmap bm = BitmapFactory.decodeFile(f.getAbsolutePath(), opts);
                ExifInterface exif = new ExifInterface(f.getAbsolutePath());
                String orientString = exif.getAttribute(ExifInterface.TAG_ORIENTATION);
                int orientation = orientString != null ? Integer.parseInt(orientString) :  ExifInterface.ORIENTATION_NORMAL;
                int rotationAngle = 0;
                if (orientation == ExifInterface.ORIENTATION_ROTATE_90) rotationAngle = 90;
                if (orientation == ExifInterface.ORIENTATION_ROTATE_180) rotationAngle = 180;
                if (orientation == ExifInterface.ORIENTATION_ROTATE_270) rotationAngle = 270;
                Matrix matrix = new Matrix();
                matrix.setRotate(rotationAngle, (float) bm.getWidth() / 2, (float) bm.getHeight() / 2);
                Bitmap rotatedBitmap = Bitmap.createBitmap(bm, 0, 0, bitmapOptions.outWidth, bitmapOptions.outHeight, matrix, true);

                Global.img = bitmap;

                b.setImageBitmap(bitmap);
                String path = android.os.Environment.getExternalStorageDirectory() + File.separator + "Phoenix" + File.separator + "default";
                //p = path;
                f.delete();
                OutputStream outFile = null;
                File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
                try {

                    outFile = new FileOutputStream(file);
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
                    //pic=file;
                    outFile.flush();
                    outFile.close();


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

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

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

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

            }

        } else if (requestCode == 2) {

            Uri selectedImage = data.getData();
            // h=1;
            //imgui = selectedImage;
            String[] filePath = {MediaStore.Images.Media.DATA};
            Cursor c = getContentResolver().query(selectedImage, filePath, null, null, null);
            c.moveToFirst();
            int columnIndex = c.getColumnIndex(filePath[0]);
            String picturePath = c.getString(columnIndex);
            c.close();
            Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
            Log.w("path of image ******", picturePath + "");
            b.setImageBitmap(thumbnail);
        }


    }
    else
    {
        finish();
    }

}

LogCat error

  Process: com.example.project.project, PID: 13045
    java.lang.OutOfMemoryError
            at android.graphics.Bitmap.nativeCreate(Native Method)
            at android.graphics.Bitmap.createBitmap(Bitmap.java:928)
            at android.graphics.Bitmap.createBitmap(Bitmap.java:901)
            at android.graphics.Bitmap.createBitmap(Bitmap.java:833)
            at com.example.project.project.ImageFitScreen.onActivityResult(ImageFitScreen.java:236)
            at android.app.Activity.dispatchActivityResult(Activity.java:5643)

This is line 236

 Bitmap rotatedBitmap = Bitmap.createBitmap(bm, 0, 0, bitmapOptions.outWidth, bitmapOptions.outHeight, matrix, true);

How can I solve this ? I find many solution from SO but I still don't know how to solve it. Could someone help me solve this? Any help would be great thanks!!

Community
  • 1
  • 1

3 Answers3

1

U should let less bitmap in memory . Recycle bitmap when you will never need them.setImageBitmap is Bad.After store bitmap in file system,just use glide or Universal-Image-Loader to load it.

tiny sunlight
  • 6,231
  • 3
  • 21
  • 42
0

I guessing your application is memory intensive and your camera pics should have at least be 1280x720 in size. I modified your code to create a function called

decodeBitmap

  private Bitmap decodeBitmap(String filePath, int reqWidth, int reqHeight, int scale) throws IOException, Exception {
    if (scale > 3)
        throw new Exception("scale size cannot be greater than 3");
    BitmapFactory.Options bmOptions = new BitmapFactory.Options();
    bmOptions.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(filePath, bmOptions);
    int photoW = bmOptions.outWidth;
    int photoH = bmOptions.outHeight;

    // Determine how much to scale down the image
    bmOptions.inSampleSize = scale + Math.min(photoW / reqWidth, photoH / reqHeight);
    bmOptions.inJustDecodeBounds = false;
    try {
        Bitmap bm = BitmapFactory.decodeFile(filePath, bmOptions);
        ExifInterface exif = new ExifInterface(filePath);
        String orientString = exif.getAttribute(ExifInterface.TAG_ORIENTATION);
        int orientation = orientString != null ? Integer.parseInt(orientString) : ExifInterface.ORIENTATION_NORMAL;

        int rotationAngle = 0;
        if (orientation == ExifInterface.ORIENTATION_ROTATE_90) rotationAngle = 90;
        if (orientation == ExifInterface.ORIENTATION_ROTATE_180) rotationAngle = 180;
        if (orientation == ExifInterface.ORIENTATION_ROTATE_270) rotationAngle = 270;

        Matrix matrix = new Matrix();
        matrix.setRotate(rotationAngle, (float) bm.getWidth() / 2, (float) bm.getHeight() / 2);
        return Bitmap.createBitmap(bm, 0, 0, photoW, photoH, matrix, true);
    } catch (OutOfMemoryError exception) {
        exception.printStackTrace();
        return decodeBitmap(filePath, reqWidth, reqHeight, scale + 1);
    }
}

onActivityResult

  try {
        mImageView.setImageBitmap(decodeBitmap(mCurrentPhotoPath,1024,1024,0));
    } catch (Exception e) {
        e.printStackTrace();
    }

Let me warn you, this function works by reducing some of the image quality. Hope it helps you...

Fabin Paul
  • 1,701
  • 1
  • 16
  • 18
  • If I not rotating the captured image, it allows me to capture again and again without crash. After I add the rotate function it only crashed. why would it happen? –  Nov 06 '15 at 04:23
  • you can see my original post at [here](http://stackoverflow.com/questions/33558132/captured-image-always-shows-landscape-and-setrotate-cannot-be-resolved/33559248?noredirect=1#comment54897820_33559248) –  Nov 06 '15 at 04:25
  • after adding code for rotation, you are holding 2 instance of Bitmap in memory and a single camera image is more than what android's memory can hold(especially the newer photos with higher resolution). That is why your app crashed after adding rotation code.. – Fabin Paul Nov 06 '15 at 04:27
0

Try to this way for the camera image capture up to 6 Times.

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // TODO Auto-generated method stub
    super.onActivityResult(requestCode, resultCode, data);
    // if the result is capturing Image
    // int count = 1, countsix = 6;

    if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
        if (resultCode == this.RESULT_OK) {

            Log.e("in the On Activity Result", ":::: " + count);
            if (count != countFix) {

                Log.e("in the From Camera if con ", "Count Increment :: "
                        + count);
                count++;
                if (count == 1) {
                    first = mediaFile.toString();
                    cameraAndGalaryPicture();

                    Log.e("in the Count ", "::: 1 " + first);
                    // getBitmapFromURL(first);

                    int targetW = 450;
                    int targetH = 800;
                    BitmapFactory.Options bmOptions = new BitmapFactory.Options();
                    bmOptions.inJustDecodeBounds = true;
                    BitmapFactory.decodeFile(first, bmOptions);
                    int photoW = bmOptions.outWidth;
                    int photoH = bmOptions.outHeight;
                    // Determine how much to scale down the image
                    int scaleFactor = Math.min(photoW / targetW, photoH
                            / targetH);

                    // Decode the image file into a Bitmap sized to fill the
                    // View

                    // imgHome.setImageBitmap(bitmap);

                    bmOptions.inJustDecodeBounds = false;
                    bmOptions.inSampleSize = scaleFactor << 1;
                    bmOptions.inPurgeable = true;
                    Bitmap bitmap = BitmapFactory.decodeFile(first,
                            bmOptions);

                    ByteArrayOutputStream stream = new ByteArrayOutputStream();
                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
                    byte[] img1 = stream.toByteArray();
                    String timeStamp = new SimpleDateFormat(
                            "yyyyMMdd_HHmmss", Locale.getDefault())
                            .format(new Date());
                    Parseimagecam1 = new ParseFile("IMG_" + timeStamp
                            + ".jpg", img1);
                    Parseimagecam1.saveInBackground();

                    parseFileCamera.add(0, Parseimagecam1);

                    image_Photo1.setImageBitmap(bitmap);
                    StorePath = first + "," + second + "," + thrid + ","
                            + four + "," + five + "," + six;
                } else if (count == 2) {
                    second = mediaFile.toString();
                    cameraAndGalaryPicture();
                    Log.e("in the Count ", "::: 2 " + second);

                    // getBitmapFromURL(second);

                    int targetW = 450;
                    int targetH = 800;
                    BitmapFactory.Options bmOptions = new BitmapFactory.Options();
                    bmOptions.inJustDecodeBounds = true;
                    BitmapFactory.decodeFile(second, bmOptions);
                    int photoW = bmOptions.outWidth;
                    int photoH = bmOptions.outHeight;
                    // Determine how much to scale down the image
                    int scaleFactor = Math.min(photoW / targetW, photoH
                            / targetH);

                    // Decode the image file into a Bitmap sized to fill the
                    // View
                    bmOptions.inJustDecodeBounds = false;
                    bmOptions.inSampleSize = scaleFactor << 1;
                    bmOptions.inPurgeable = true;
                    Bitmap bitmap = BitmapFactory.decodeFile(second,
                            bmOptions);

                    ByteArrayOutputStream stream = new ByteArrayOutputStream();
                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
                    byte[] img2 = stream.toByteArray();
                    String timeStamp = new SimpleDateFormat(
                            "yyyyMMdd_HHmmss", Locale.getDefault())
                            .format(new Date());
                    Parseimagecam2 = new ParseFile("IMG_" + timeStamp
                            + ".jpg", img2);
                    Parseimagecam2.saveInBackground();

                    parseFileCamera.add(1, Parseimagecam2);
                    Log.e("PARSE IMAGE CAMERA 2", ":::: : "
                            + Parseimagecam2);
                    StorePath = first + "," + second + "," + thrid + ","
                            + four + "," + five + "," + six;
                } else if (count == 3) {
                    thrid = mediaFile.toString();
                    cameraAndGalaryPicture();
                    Log.e("in the Count ", "::: 3 " + thrid);

                    int targetW = 450;
                    int targetH = 800;
                    BitmapFactory.Options bmOptions = new BitmapFactory.Options();
                    bmOptions.inJustDecodeBounds = true;
                    BitmapFactory.decodeFile(thrid, bmOptions);
                    int photoW = bmOptions.outWidth;
                    int photoH = bmOptions.outHeight;
                    // Determine how much to scale down the image
                    int scaleFactor = Math.min(photoW / targetW, photoH
                            / targetH);

                    // Decode the image file into a Bitmap sized to fill the
                    // View
                    bmOptions.inJustDecodeBounds = false;
                    bmOptions.inSampleSize = scaleFactor << 1;
                    bmOptions.inPurgeable = true;
                    Bitmap bitmap = BitmapFactory.decodeFile(thrid,
                            bmOptions);

                    ByteArrayOutputStream stream = new ByteArrayOutputStream();
                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
                    byte[] img3 = stream.toByteArray();
                    String timeStamp = new SimpleDateFormat(
                            "yyyyMMdd_HHmmss", Locale.getDefault())
                            .format(new Date());
                    Parseimagecam3 = new ParseFile("IMG_" + timeStamp
                            + ".jpg", img3);
                    Parseimagecam3.saveInBackground();

                    // parseFileCamera.add(2, Parseimagecam3);

                    StorePath = first + "," + second + "," + thrid + ","
                            + four + "," + five + "," + six;
                } else if (count == 4) {
                    four = mediaFile.toString();
                    cameraAndGalaryPicture();
                    Log.e("in the Count ", "::: 4 " + four);

                    int targetW = 450;
                    int targetH = 800;
                    BitmapFactory.Options bmOptions = new BitmapFactory.Options();
                    bmOptions.inJustDecodeBounds = true;
                    BitmapFactory.decodeFile(four, bmOptions);
                    int photoW = bmOptions.outWidth;
                    int photoH = bmOptions.outHeight;
                    // Determine how much to scale down the image
                    int scaleFactor = Math.min(photoW / targetW, photoH
                            / targetH);

                    // Decode the image file into a Bitmap sized to fill the
                    // View
                    bmOptions.inJustDecodeBounds = false;
                    bmOptions.inSampleSize = scaleFactor << 1;
                    bmOptions.inPurgeable = true;
                    Bitmap bitmap = BitmapFactory.decodeFile(four,
                            bmOptions);

                    ByteArrayOutputStream stream = new ByteArrayOutputStream();
                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
                    byte[] img4 = stream.toByteArray();
                    String timeStamp = new SimpleDateFormat(
                            "yyyyMMdd_HHmmss", Locale.getDefault())
                            .format(new Date());
                    Parseimagecam4 = new ParseFile("IMG_" + timeStamp
                            + ".jpg", img4);
                    Parseimagecam4.saveInBackground();

                    // parseFileCamera.add(3, Parseimagecam4);

                    StorePath = first + "," + second + "," + thrid + ","
                            + four + "," + five + "," + six;
                } else if (count == 5) {
                    five = mediaFile.toString();
                    cameraAndGalaryPicture();
                    Log.e("in the Count ", "::: 5 " + five);

                    int targetW = 450;
                    int targetH = 800;
                    BitmapFactory.Options bmOptions = new BitmapFactory.Options();
                    bmOptions.inJustDecodeBounds = true;
                    BitmapFactory.decodeFile(five, bmOptions);
                    int photoW = bmOptions.outWidth;
                    int photoH = bmOptions.outHeight;
                    // Determine how much to scale down the image
                    int scaleFactor = Math.min(photoW / targetW, photoH
                            / targetH);

                    // Decode the image file into a Bitmap sized to fill the
                    // View
                    bmOptions.inJustDecodeBounds = false;
                    bmOptions.inSampleSize = scaleFactor << 1;
                    bmOptions.inPurgeable = true;
                    Bitmap bitmap = BitmapFactory.decodeFile(five,
                            bmOptions);

                    ByteArrayOutputStream stream = new ByteArrayOutputStream();
                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
                    byte[] img5 = stream.toByteArray();
                    String timeStamp = new SimpleDateFormat(
                            "yyyyMMdd_HHmmss", Locale.getDefault())
                            .format(new Date());
                    Parseimagecam5 = new ParseFile("IMG_", img5);
                    // Parseimagecam5.saveInBackground();

                    parseFileCamera.add(4, Parseimagecam5);

                    StorePath = first + "," + second + "," + thrid + ","
                            + four + "," + five + "," + six;
                } else if (count == 6) {
                    six = mediaFile.toString();
                    // cameraAndGalaryPicture();
                    Log.e("in the Count ", "::: 6 " + six);

                    int targetW = 450;
                    int targetH = 800;
                    BitmapFactory.Options bmOptions = new BitmapFactory.Options();
                    bmOptions.inJustDecodeBounds = true;
                    BitmapFactory.decodeFile(six, bmOptions);
                    int photoW = bmOptions.outWidth;
                    int photoH = bmOptions.outHeight;
                    // Determine how much to scale down the image
                    int scaleFactor = Math.min(photoW / targetW, photoH
                            / targetH);

                    // Decode the image file into a Bitmap sized to fill the
                    // View
                    bmOptions.inJustDecodeBounds = false;
                    bmOptions.inSampleSize = scaleFactor << 1;
                    bmOptions.inPurgeable = true;
                    Bitmap bitmap = BitmapFactory
                            .decodeFile(six, bmOptions);

                    ByteArrayOutputStream stream = new ByteArrayOutputStream();
                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
                    byte[] img6 = stream.toByteArray();
                    String timeStamp = new SimpleDateFormat(
                            "yyyyMMdd_HHmmss", Locale.getDefault())
                            .format(new Date());
                    Parseimagecam6 = new ParseFile("IMG_" + timeStamp
                            + ".jpg", img6);
                    Parseimagecam6.saveInBackground();

                    parseFileCamera.add(5, Parseimagecam6);

                    StorePath = first + "," + second + "," + thrid + ","
                            + four + "," + five + "," + six;

                }
                Log.e("Store Path ", ":: : " + StorePath);
                Log.e("parseFileCamera",
                        ":: : Size " + parseFileCamera.toString());

                Log.e("Boolean Value Chaeck", ":: : Tru or fls  "
                        + ImageCamera);

                for (int i = 0; i < parseFileCamera.size(); i++) {
                    ParseFile image = (ParseFile) parseFileCamera.get(i);

                    Log.e("in the for loop ", ":::: " + image.getUrl());
                }
            } else {

            }
        } else if (resultCode == this.RESULT_CANCELED) {
            // user cancelled Image capture
            Toast.makeText(getApplicationContext(),
                    "User cancelled image capture", Toast.LENGTH_SHORT)
                    .show();
        } else {
            // failed to capture image
            Toast.makeText(getApplicationContext(),
                    "Sorry! Failed to capture image", Toast.LENGTH_SHORT)
                    .show();
        }

    }
}

cameraAndGalaryPicture() this is method for the open Camera Capture Method. countFix this variable for the its Fix 6. parseFileCamera this is Parse Array. Parseimagecam5 this is Parse file object

i use this in parse database. also u will take Byte array other wise Bitmap Array to store more then image.

Hardik Parmar
  • 712
  • 2
  • 13
  • 28