Example usage for android.graphics Matrix postRotate

List of usage examples for android.graphics Matrix postRotate

Introduction

In this page you can find the example usage for android.graphics Matrix postRotate.

Prototype

public boolean postRotate(float degrees) 

Source Link

Document

Postconcats the matrix with the specified rotation.

Usage

From source file:org.linphone.ContactEditorFragment.java

private void editContactPicture(final String filePath, final Bitmap image) {
    int SIZE_SMALL = 256;
    int COMPRESSOR_QUALITY = 100;
    Bitmap bitmapUnknown = BitmapFactory.decodeResource(getResources(), R.drawable.avatar);
    Bitmap bm = null;// w ww.  j  a va2 s  . com

    if (filePath != null) {
        int pixelsMax = SIZE_SMALL;
        //Resize image
        bm = BitmapFactory.decodeFile(filePath);
        if (bm != null) {
            if (bm.getWidth() > bm.getHeight() && bm.getWidth() > pixelsMax) {
                bm = Bitmap.createScaledBitmap(bm, 256, 256, false);
            }
        }
    } else if (image != null) {
        bm = image;
    }

    // Rotate the bitmap if possible/needed, using EXIF data
    try {
        if (imageToUploadUri != null && filePath != null) {
            ExifInterface exif = new ExifInterface(filePath);
            int pictureOrientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 0);
            Matrix matrix = new Matrix();
            if (pictureOrientation == 6) {
                matrix.postRotate(90);
            } else if (pictureOrientation == 3) {
                matrix.postRotate(180);
            } else if (pictureOrientation == 8) {
                matrix.postRotate(270);
            }
            bm = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), matrix, true);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    Bitmap bitmapRounded;
    if (bm != null) {
        bitmapRounded = Bitmap.createScaledBitmap(bm, bitmapUnknown.getWidth(), bitmapUnknown.getWidth(),
                false);

        Canvas canvas = new Canvas(bitmapRounded);
        Paint paint = new Paint();
        paint.setAntiAlias(true);
        paint.setShader(new BitmapShader(bitmapRounded, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP));
        canvas.drawCircle(bitmapRounded.getWidth() / 2 + 0.7f, bitmapRounded.getHeight() / 2 + 0.7f,
                bitmapRounded.getWidth() / 2 + 0.1f, paint);
        contactPicture.setImageBitmap(bitmapRounded);

        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.PNG, COMPRESSOR_QUALITY, outStream);
        photoToAdd = outStream.toByteArray();
    }
}

From source file:com.tealeaf.TeaLeaf.java

private Bitmap rotateBitmap(Bitmap bitmap, int rotate) {
    // rotate as needed
    Bitmap bmp;//from   w  w w .j  a  v  a2 s  .c  o m

    //only allow the largest size to be 768 for now, several phones
    //including the galaxy s3 seem to crash with rotating very large 
    //images (out of memory errors) from the gallery
    int w = bitmap.getWidth();
    int h = bitmap.getHeight();
    Bitmap scaled = bitmap;
    if (w > h && w > 768) {
        float ratio = 768.f / (float) w;
        w = 768;
        h = (int) (ratio * h);
        scaled = Bitmap.createScaledBitmap(bitmap, w, h, true);
        if (bitmap != scaled) {
            bitmap.recycle();
        }
    }
    if (h > w && h > 768) {
        float ratio = 768.f / (float) h;
        h = 768;
        w = (int) (ratio * w);
        scaled = Bitmap.createScaledBitmap(bitmap, w, h, true);
        if (bitmap != scaled) {
            bitmap.recycle();
        }
    }

    int newWidth = scaled.getWidth();
    int newHeight = scaled.getHeight();

    int degrees = 0;
    if (rotate == ROTATE_90 || rotate == ROTATE_270) {
        newWidth = scaled.getHeight();
        newHeight = scaled.getWidth();
    }

    Matrix matrix = new Matrix();
    matrix.postRotate(rotate);

    bmp = Bitmap.createBitmap(scaled, 0, 0, scaled.getWidth(), scaled.getHeight(), matrix, true);
    if (scaled != bmp) {
        scaled.recycle();
    }

    return bmp;
}

From source file:com.fabernovel.alertevoirie.ReportDetailsActivity.java

private void RotatePicture(ImageView imageView) {
    Bitmap picture = null;// w w  w  .j  av a 2s  . com

    picture = ((BitmapDrawable) (imageView.getDrawable())).getBitmap();

    Matrix m = new Matrix();
    m.postRotate(90);
    picture = Bitmap.createBitmap(picture, 0, 0, picture.getWidth(), picture.getHeight(), m, true);

    imageView.setImageBitmap(picture);

}

From source file:com.fabernovel.alertevoirie.ReportDetailsActivity.java

private void setPictureToImageView(String pictureName, ImageView imageView) {
    Bitmap picture = null;/*from   w  w w.j a va 2s  . c om*/

    try {
        InputStream in = openFileInput(pictureName);
        picture = BitmapFactory.decodeStream(in);
        in.close();

        LayerDrawable d = (LayerDrawable) getResources().getDrawable(R.drawable.editable_picture_frame);
        if (picture.getHeight() > picture.getWidth()) {
            Matrix m = new Matrix();
            m.postRotate(-90);
            picture = Bitmap.createBitmap(picture, 0, 0, picture.getWidth(), picture.getHeight(), m, true);
        }
        picture = Bitmap.createScaledBitmap(picture, d.getIntrinsicWidth(), d.getIntrinsicHeight(), true);

        d.setDrawableByLayerId(R.id.picture, new BitmapDrawable(picture));
        imageView.setImageDrawable(d);

        if (!hasPic)
            hasPic = (imageView.getId() == R.id.ImageView_far);

        // WTF ?
        // if (hasPic && (imageView.getId() == R.id.ImageView_far)) {
        // loadZoom();
        // }

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

From source file:com.netcompss.ffmpeg4android_client.BaseWizard.java

@SuppressWarnings("unused")
private String reporteds(String path) {

    ExifInterface exif = null;/*w  ww.j  av  a 2s  .co  m*/
    try {
        exif = new ExifInterface(path);
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
    Matrix matrix = new Matrix();
    if (orientation == 6) {
        matrix.postRotate(90);
    } else if (orientation == 3) {
        matrix.postRotate(180);
    } else if (orientation == 8) {
        matrix.postRotate(270);
    }

    if (path != null) {

        if (path.contains("http")) {
            try {
                URL url = new URL(path);
                HttpGet httpRequest = null;

                httpRequest = new HttpGet(url.toURI());

                HttpClient httpclient = new DefaultHttpClient();
                HttpResponse response = (HttpResponse) httpclient.execute(httpRequest);

                HttpEntity entity = response.getEntity();
                BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
                InputStream input = bufHttpEntity.getContent();

                Bitmap bitmap = BitmapFactory.decodeStream(input);
                input.close();
                return getPath(bitmap);
            } catch (MalformedURLException e) {
                Log.e("ImageActivity", "bad url", e);
            } catch (Exception e) {
                Log.e("ImageActivity", "io error", e);
            }
        } else {
            Options options = new Options();
            options.inSampleSize = 2;
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeResource(getApplicationContext().getResources(), srcBgId, options);
            options.inJustDecodeBounds = false;
            options.inSampleSize = calculateInSampleSize(options, w, h);
            Bitmap unbgbtmp = BitmapFactory.decodeResource(getApplicationContext().getResources(), srcBgId,
                    options);
            Bitmap unrlbtmp = ScalingUtilities.decodeFile(path, w, h, ScalingLogic.FIT);
            unrlbtmp.recycle();
            Bitmap rlbtmp = null;
            if (unrlbtmp != null) {
                rlbtmp = ScalingUtilities.createScaledBitmap(unrlbtmp, w, h, ScalingLogic.FIT);
            }
            if (unbgbtmp != null && rlbtmp != null) {
                Bitmap bgbtmp = ScalingUtilities.createScaledBitmap(unbgbtmp, w, h, ScalingLogic.FIT);
                Bitmap newscaledBitmap = ProcessingBitmapTwo(bgbtmp, rlbtmp);
                unbgbtmp.recycle();
                return getPath(newscaledBitmap);
            }
        }
    }
    return path;

}

From source file:org.egov.android.view.activity.CreateComplaintActivity.java

public String compressImage(String fromfilepath, String tofilepath) {

    Bitmap scaledBitmap = null;/* w w w.j ava2 s.c o m*/

    BitmapFactory.Options options = new BitmapFactory.Options();

    //      by setting this field as true, the actual bitmap pixels are not loaded in the memory. Just the bounds are loaded. If
    //      you try the use the bitmap here, you will get null.
    options.inJustDecodeBounds = true;
    Bitmap bmp = BitmapFactory.decodeFile(fromfilepath, options);

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

    //      max Height and width values of the compressed image is taken as 816x612

    float maxHeight = 816.0f;
    float maxWidth = 612.0f;
    float imgRatio = actualWidth / actualHeight;
    float maxRatio = maxWidth / maxHeight;

    //      width and height values are set maintaining the aspect ratio of the image

    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;

        }
    }

    //      setting inSampleSize value allows to load a scaled down version of the original image

    options.inSampleSize = calculateInSampleSize(options, actualWidth, actualHeight);

    //      inJustDecodeBounds set to false to load the actual bitmap
    options.inJustDecodeBounds = false;

    //      this options allow android to claim the bitmap memory if it runs low on memory
    options.inPurgeable = true;
    options.inInputShareable = true;
    options.inTempStorage = new byte[16 * 1024];

    try {
        //          load the bitmap from its path
        bmp = BitmapFactory.decodeFile(tofilepath, options);
    } catch (OutOfMemoryError exception) {
        exception.printStackTrace();
    }
    try {
        scaledBitmap = Bitmap.createBitmap(actualWidth, actualHeight, Bitmap.Config.ARGB_8888);
    } catch (OutOfMemoryError exception) {
        exception.printStackTrace();
    }

    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);
    canvas.drawBitmap(bmp, middleX - bmp.getWidth() / 2, middleY - bmp.getHeight() / 2,
            new Paint(Paint.FILTER_BITMAP_FLAG));

    String attrLatitute = null;
    String attrLatituteRef = null;
    String attrLONGITUDE = null;
    String attrLONGITUDEREf = null;

    //      check the rotation of the image and display it properly
    ExifInterface exif;
    try {
        exif = new ExifInterface(fromfilepath);

        int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 0);
        Log.d("EXIF", "Exif: " + orientation);
        Matrix matrix = new Matrix();
        if (orientation == 6) {
            matrix.postRotate(90);
            Log.d("EXIF", "Exif: " + orientation);
        } else if (orientation == 3) {
            matrix.postRotate(180);
            Log.d("EXIF", "Exif: " + orientation);
        } else if (orientation == 8) {
            matrix.postRotate(270);
            Log.d("EXIF", "Exif: " + orientation);
        }

        attrLatitute = exif.getAttribute(ExifInterface.TAG_GPS_LATITUDE);
        attrLatituteRef = exif.getAttribute(ExifInterface.TAG_GPS_LATITUDE_REF);
        attrLONGITUDE = exif.getAttribute(ExifInterface.TAG_GPS_LONGITUDE);
        attrLONGITUDEREf = exif.getAttribute(ExifInterface.TAG_GPS_LONGITUDE_REF);

        scaledBitmap = Bitmap.createBitmap(scaledBitmap, 0, 0, scaledBitmap.getWidth(),
                scaledBitmap.getHeight(), matrix, true);
    } catch (IOException e) {
        e.printStackTrace();
    }

    FileOutputStream out = null;
    try {
        out = new FileOutputStream(tofilepath);

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

        ExifInterface exif2 = new ExifInterface(tofilepath);

        if (attrLatitute != null) {
            exif2.setAttribute(ExifInterface.TAG_GPS_LATITUDE, attrLatitute);
            exif2.setAttribute(ExifInterface.TAG_GPS_LONGITUDE, attrLONGITUDE);
        }

        if (attrLatituteRef != null) {
            exif2.setAttribute(ExifInterface.TAG_GPS_LATITUDE_REF, attrLatituteRef);
            exif2.setAttribute(ExifInterface.TAG_GPS_LONGITUDE_REF, attrLONGITUDEREf);
        }
        exif2.saveAttributes();

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return tofilepath;
}

From source file:com.annanovas.bestprice.DashBoardEditActivity.java

private Bitmap imageProcess(Bitmap imageBitmap) {
    int width = imageBitmap.getWidth();
    int height = imageBitmap.getHeight();
    int newWidth = 1000;
    int newHeight = 1000;
    if (width > 1000) {
        double x = (double) width / 1000d;
        newHeight = (int) (height / x);
        newWidth = 1000;//www .  ja  v a 2s  .c o  m
    } else if (height > 1000) {
        double x = (double) height / 1000d;
        newWidth = (int) (width / x);
        newHeight = 1000;
    }
    // calculate the scale - in this case = 0.4f
    ExifInterface exif = null;
    int rotationAngle = 0;
    try {
        exif = new ExifInterface(imageUri);
        String orientString = exif.getAttribute(ExifInterface.TAG_ORIENTATION);
        // showLog("orientString:" + orientString + " DateTime:" + exif.getAttribute(ExifInterface.TAG_IMAGE_WIDTH));
        int orientation = orientString != null ? Integer.parseInt(orientString)
                : ExifInterface.ORIENTATION_NORMAL;
        if (orientation == ExifInterface.ORIENTATION_ROTATE_90)
            rotationAngle = 90;
        if (orientation == ExifInterface.ORIENTATION_ROTATE_180)
            rotationAngle = 180;
        if (orientation == ExifInterface.ORIENTATION_ROTATE_270)
            rotationAngle = 270;
        //  showLog("Rotation Angle:" + rotationAngle);
    } catch (IOException e) {
        // showLog("ExifInterface Failed!");
        e.printStackTrace();
    }
    float scaleWidth = ((float) newWidth) / width;
    float scaleHeight = ((float) newHeight) / height;
    Matrix matrix = new Matrix();
    matrix.postScale(scaleWidth, scaleHeight);
    matrix.postRotate(rotationAngle);
    return Bitmap.createBitmap(imageBitmap, 0, 0, width, height, matrix, true);
}

From source file:ir.rasen.charsoo.controller.image_loader.core.decode.BaseImageDecoder.java

protected Bitmap considerExactScaleAndOrientatiton(Bitmap subsampledBitmap, ImageDecodingInfo decodingInfo,
        int rotation, boolean flipHorizontal) {
    Matrix m = new Matrix();
    // Scale to exact size if need
    ImageScaleType scaleType = decodingInfo.getImageScaleType();
    if (scaleType == ImageScaleType.EXACTLY || scaleType == ImageScaleType.EXACTLY_STRETCHED) {
        ImageSize srcSize = new ImageSize(subsampledBitmap.getWidth(), subsampledBitmap.getHeight(), rotation);
        float scale = ImageSizeUtils.computeImageScale(srcSize, decodingInfo.getTargetSize(),
                decodingInfo.getViewScaleType(), scaleType == ImageScaleType.EXACTLY_STRETCHED);
        if (Float.compare(scale, 1f) != 0) {
            m.setScale(scale, scale);//  w w  w  .  j  av  a  2s .c  o  m

            if (loggingEnabled) {
                L.d(LOG_SCALE_IMAGE, srcSize, srcSize.scale(scale), scale, decodingInfo.getImageKey());
            }
        }
    }
    // Flip bitmap if need
    if (flipHorizontal) {
        m.postScale(-1, 1);

        if (loggingEnabled)
            L.d(LOG_FLIP_IMAGE, decodingInfo.getImageKey());
    }
    // Rotate bitmap if need
    if (rotation != 0) {
        m.postRotate(rotation);

        if (loggingEnabled)
            L.d(LOG_ROTATE_IMAGE, rotation, decodingInfo.getImageKey());
    }

    Bitmap finalBitmap = Bitmap.createBitmap(subsampledBitmap, 0, 0, subsampledBitmap.getWidth(),
            subsampledBitmap.getHeight(), m, true);
    if (finalBitmap != subsampledBitmap) {
        subsampledBitmap.recycle();
    }
    return finalBitmap;
}

From source file:openscience.crowdsource.video.experiments.MainActivity.java

private void rotateImageAccoridingToOrientation(String takenPictureFilPath) {
    Bitmap bmp = BitmapFactory.decodeFile(takenPictureFilPath);
    Matrix rotationMatrix = new Matrix();
    rotationMatrix.postRotate(getImageDegree(takenPictureFilPath));

    int startX = 0;
    int startY = 0;
    int width = bmp.getWidth();
    int endX = width;
    int height = bmp.getHeight();
    int endY = height;

    if (height > width) {
        startY = Math.round((height - width) / 2);
        endY = startY + width;//from   w  w w. j a va  2s  . c  o  m
    }
    if (height < width) {
        startX = Math.round((width - height) / 2);
        endX = startX + height;
    }
    Bitmap rbmp = Bitmap.createBitmap(bmp, startX, startY, endX, endY, rotationMatrix, true);

    FileOutputStream out = null;
    try {
        out = new FileOutputStream(takenPictureFilPath);
        rbmp.compress(Bitmap.CompressFormat.JPEG, 60, out); // bmp is your Bitmap instance
        // PNG is a lossless format, the compression factor (100) is ignored
    } catch (Exception e) {
        e.printStackTrace();
        AppLogger.logMessage("Error on picture taking " + e.getLocalizedMessage());
    } finally {
        try {
            if (out != null) {
                out.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
            AppLogger.logMessage("Error on picture taking " + e.getLocalizedMessage());
        }
    }
}

From source file:com.almalence.opencam.SavingService.java

public void saveResultPicture(long sessionID) {
    initSavingPrefs();//www.  j a  va 2s. c om
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    // save fused result
    try {
        File saveDir = getSaveDir(false);

        Calendar d = Calendar.getInstance();

        int imagesAmount = Integer
                .parseInt(getFromSharedMem("amountofresultframes" + Long.toString(sessionID)));

        if (imagesAmount == 0)
            imagesAmount = 1;

        int imageIndex = 0;
        String sImageIndex = getFromSharedMem("resultframeindex" + Long.toString(sessionID));
        if (sImageIndex != null)
            imageIndex = Integer.parseInt(getFromSharedMem("resultframeindex" + Long.toString(sessionID)));

        if (imageIndex != 0)
            imagesAmount = 1;

        ContentValues values = null;

        boolean hasDNGResult = false;
        for (int i = 1; i <= imagesAmount; i++) {
            hasDNGResult = false;
            String format = getFromSharedMem("resultframeformat" + i + Long.toString(sessionID));

            if (format != null && format.equalsIgnoreCase("dng"))
                hasDNGResult = true;

            String idx = "";

            if (imagesAmount != 1)
                idx += "_" + ((format != null && !format.equalsIgnoreCase("dng") && hasDNGResult)
                        ? i - imagesAmount / 2
                        : i);

            String modeName = getFromSharedMem("modeSaveName" + Long.toString(sessionID));
            // define file name format. from settings!
            String fileFormat = getExportFileName(modeName);
            fileFormat += idx + ((format != null && format.equalsIgnoreCase("dng")) ? ".dng" : ".jpg");

            File file;
            if (ApplicationScreen.getForceFilename() == null) {
                file = new File(saveDir, fileFormat);
            } else {
                file = ApplicationScreen.getForceFilename();
            }

            OutputStream os = null;
            if (ApplicationScreen.getForceFilename() != null) {
                os = getApplicationContext().getContentResolver()
                        .openOutputStream(ApplicationScreen.getForceFilenameURI());
            } else {
                try {
                    os = new FileOutputStream(file);
                } catch (Exception e) {
                    // save always if not working saving to sdcard
                    e.printStackTrace();
                    saveDir = getSaveDir(true);
                    if (ApplicationScreen.getForceFilename() == null) {
                        file = new File(saveDir, fileFormat);
                    } else {
                        file = ApplicationScreen.getForceFilename();
                    }
                    os = new FileOutputStream(file);
                }
            }

            // Take only one result frame from several results
            // Used for PreShot plugin that may decide which result to save
            if (imagesAmount == 1 && imageIndex != 0)
                i = imageIndex;

            String resultOrientation = getFromSharedMem(
                    "resultframeorientation" + i + Long.toString(sessionID));
            int orientation = 0;
            if (resultOrientation != null)
                orientation = Integer.parseInt(resultOrientation);

            String resultMirrored = getFromSharedMem("resultframemirrored" + i + Long.toString(sessionID));
            Boolean cameraMirrored = false;
            if (resultMirrored != null)
                cameraMirrored = Boolean.parseBoolean(resultMirrored);

            int x = Integer.parseInt(getFromSharedMem("saveImageHeight" + Long.toString(sessionID)));
            int y = Integer.parseInt(getFromSharedMem("saveImageWidth" + Long.toString(sessionID)));
            if (orientation == 0 || orientation == 180 || (format != null && format.equalsIgnoreCase("dng"))) {
                x = Integer.valueOf(getFromSharedMem("saveImageWidth" + Long.toString(sessionID)));
                y = Integer.valueOf(getFromSharedMem("saveImageHeight" + Long.toString(sessionID)));
            }

            Boolean writeOrientationTag = true;
            String writeOrientTag = getFromSharedMem("writeorientationtag" + Long.toString(sessionID));
            if (writeOrientTag != null)
                writeOrientationTag = Boolean.parseBoolean(writeOrientTag);

            if (format != null && format.equalsIgnoreCase("jpeg")) {// if result in jpeg format

                if (os != null) {
                    byte[] frame = SwapHeap.SwapFromHeap(
                            Integer.parseInt(getFromSharedMem("resultframe" + i + Long.toString(sessionID))),
                            Integer.parseInt(
                                    getFromSharedMem("resultframelen" + i + Long.toString(sessionID))));
                    os.write(frame);
                    try {
                        os.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            } else if (format != null && format.equalsIgnoreCase("dng")) {
                saveDNGPicture(i, sessionID, os, x, y, orientation, cameraMirrored);
            } else {// if result in nv21 format
                int yuv = Integer.parseInt(getFromSharedMem("resultframe" + i + Long.toString(sessionID)));
                com.almalence.YuvImage out = new com.almalence.YuvImage(yuv, ImageFormat.NV21, x, y, null);
                Rect r;

                String res = getFromSharedMem("resultfromshared" + Long.toString(sessionID));
                if ((null == res) || "".equals(res) || "true".equals(res)) {
                    // to avoid problems with SKIA
                    int cropHeight = out.getHeight() - out.getHeight() % 16;
                    r = new Rect(0, 0, out.getWidth(), cropHeight);
                } else {
                    if (null == getFromSharedMem("resultcrop0" + Long.toString(sessionID))) {
                        // to avoid problems with SKIA
                        int cropHeight = out.getHeight() - out.getHeight() % 16;
                        r = new Rect(0, 0, out.getWidth(), cropHeight);
                    } else {
                        int crop0 = Integer
                                .parseInt(getFromSharedMem("resultcrop0" + Long.toString(sessionID)));
                        int crop1 = Integer
                                .parseInt(getFromSharedMem("resultcrop1" + Long.toString(sessionID)));
                        int crop2 = Integer
                                .parseInt(getFromSharedMem("resultcrop2" + Long.toString(sessionID)));
                        int crop3 = Integer
                                .parseInt(getFromSharedMem("resultcrop3" + Long.toString(sessionID)));

                        r = new Rect(crop0, crop1, crop0 + crop2, crop1 + crop3);

                    }
                }

                jpegQuality = Integer.parseInt(prefs.getString(ApplicationScreen.sJPEGQualityPref, "95"));
                if (!out.compressToJpeg(r, jpegQuality, os)) {
                    if (ApplicationScreen.instance != null && ApplicationScreen.getMessageHandler() != null) {
                        ApplicationScreen.getMessageHandler()
                                .sendEmptyMessage(ApplicationInterface.MSG_EXPORT_FINISHED_IOEXCEPTION);
                    }
                    return;
                }
                SwapHeap.FreeFromHeap(yuv);
            }

            String orientation_tag = String.valueOf(0);
            //            int sensorOrientation = CameraController.getSensorOrientation();
            //            int displayOrientation = CameraController.getDisplayOrientation();
            //            sensorOrientation = (360 + sensorOrientation + (cameraMirrored ? -displayOrientation
            //                  : displayOrientation)) % 360;

            //            if (CameraController.isFlippedSensorDevice() && cameraMirrored)
            //               orientation = (orientation + 180) % 360;

            switch (orientation) {
            default:
            case 0:
                orientation_tag = String.valueOf(0);
                break;
            case 90:
                orientation_tag = cameraMirrored ? String.valueOf(270) : String.valueOf(90);
                break;
            case 180:
                orientation_tag = String.valueOf(180);
                break;
            case 270:
                orientation_tag = cameraMirrored ? String.valueOf(90) : String.valueOf(270);
                break;
            }

            int exif_orientation = ExifInterface.ORIENTATION_NORMAL;
            if (writeOrientationTag) {
                switch ((orientation + 360) % 360) {
                default:
                case 0:
                    exif_orientation = ExifInterface.ORIENTATION_NORMAL;
                    break;
                case 90:
                    exif_orientation = cameraMirrored ? ExifInterface.ORIENTATION_ROTATE_270
                            : ExifInterface.ORIENTATION_ROTATE_90;
                    break;
                case 180:
                    exif_orientation = ExifInterface.ORIENTATION_ROTATE_180;
                    break;
                case 270:
                    exif_orientation = cameraMirrored ? ExifInterface.ORIENTATION_ROTATE_90
                            : ExifInterface.ORIENTATION_ROTATE_270;
                    break;
                }
            } else {
                switch ((additionalRotationValue + 360) % 360) {
                default:
                case 0:
                    exif_orientation = ExifInterface.ORIENTATION_NORMAL;
                    break;
                case 90:
                    exif_orientation = cameraMirrored ? ExifInterface.ORIENTATION_ROTATE_270
                            : ExifInterface.ORIENTATION_ROTATE_90;
                    break;
                case 180:
                    exif_orientation = ExifInterface.ORIENTATION_ROTATE_180;
                    break;
                case 270:
                    exif_orientation = cameraMirrored ? ExifInterface.ORIENTATION_ROTATE_90
                            : ExifInterface.ORIENTATION_ROTATE_270;
                    break;
                }
            }

            if (!enableExifTagOrientation)
                exif_orientation = ExifInterface.ORIENTATION_NORMAL;

            File parent = file.getParentFile();
            String path = parent.toString().toLowerCase();
            String name = parent.getName().toLowerCase();

            values = new ContentValues();
            values.put(ImageColumns.TITLE,
                    file.getName().substring(0,
                            file.getName().lastIndexOf(".") >= 0 ? file.getName().lastIndexOf(".")
                                    : file.getName().length()));
            values.put(ImageColumns.DISPLAY_NAME, file.getName());
            values.put(ImageColumns.DATE_TAKEN, System.currentTimeMillis());
            values.put(ImageColumns.MIME_TYPE, "image/jpeg");

            if (enableExifTagOrientation) {
                if (writeOrientationTag) {
                    values.put(ImageColumns.ORIENTATION, String.valueOf(
                            (Integer.parseInt(orientation_tag) + additionalRotationValue + 360) % 360));
                } else {
                    values.put(ImageColumns.ORIENTATION, String.valueOf((additionalRotationValue + 360) % 360));
                }
            } else {
                values.put(ImageColumns.ORIENTATION, String.valueOf(0));
            }

            values.put(ImageColumns.BUCKET_ID, path.hashCode());
            values.put(ImageColumns.BUCKET_DISPLAY_NAME, name);
            values.put(ImageColumns.DATA, file.getAbsolutePath());

            File tmpFile;
            if (ApplicationScreen.getForceFilename() == null) {
                tmpFile = file;
            } else {
                tmpFile = new File(getApplicationContext().getFilesDir(), "buffer.jpeg");
                tmpFile.createNewFile();
                copyFromForceFileName(tmpFile);
            }

            if (!enableExifTagOrientation) {
                Matrix matrix = new Matrix();
                if (writeOrientationTag && (orientation + additionalRotationValue) != 0) {
                    matrix.postRotate((orientation + additionalRotationValue + 360) % 360);
                    rotateImage(tmpFile, matrix);
                } else if (!writeOrientationTag && additionalRotationValue != 0) {
                    matrix.postRotate((additionalRotationValue + 360) % 360);
                    rotateImage(tmpFile, matrix);
                }
            }

            if (useGeoTaggingPrefExport) {
                Location l = MLocation.getLocation(getApplicationContext());
                if (l != null) {
                    double lat = l.getLatitude();
                    double lon = l.getLongitude();
                    boolean hasLatLon = (lat != 0.0d) || (lon != 0.0d);
                    if (hasLatLon) {
                        values.put(ImageColumns.LATITUDE, l.getLatitude());
                        values.put(ImageColumns.LONGITUDE, l.getLongitude());
                    }
                }
            }

            File modifiedFile = saveExifTags(tmpFile, sessionID, i, x, y, exif_orientation,
                    useGeoTaggingPrefExport, enableExifTagOrientation);
            if (ApplicationScreen.getForceFilename() == null) {
                file.delete();
                modifiedFile.renameTo(file);
            } else {
                copyToForceFileName(modifiedFile);
                tmpFile.delete();
                modifiedFile.delete();
            }

            Uri uri = getApplicationContext().getContentResolver().insert(Images.Media.EXTERNAL_CONTENT_URI,
                    values);
            broadcastNewPicture(uri);
        }

        ApplicationScreen.getMessageHandler().sendEmptyMessage(ApplicationInterface.MSG_EXPORT_FINISHED);
    } catch (IOException e) {
        e.printStackTrace();
        ApplicationScreen.getMessageHandler()
                .sendEmptyMessage(ApplicationInterface.MSG_EXPORT_FINISHED_IOEXCEPTION);
        return;
    } catch (Exception e) {
        e.printStackTrace();
        ApplicationScreen.getMessageHandler().sendEmptyMessage(ApplicationInterface.MSG_EXPORT_FINISHED);
    } finally {
        ApplicationScreen.setForceFilename(null);
    }
}