Example usage for android.media ExifInterface ORIENTATION_ROTATE_90

List of usage examples for android.media ExifInterface ORIENTATION_ROTATE_90

Introduction

In this page you can find the example usage for android.media ExifInterface ORIENTATION_ROTATE_90.

Prototype

int ORIENTATION_ROTATE_90

To view the source code for android.media ExifInterface ORIENTATION_ROTATE_90.

Click Source Link

Usage

From source file:com.spoiledmilk.ibikecph.util.Util.java

public static Bitmap bmpDecodeFile(File f, int width_limit, int height_limit, long max_size,
        boolean max_dimensions) {
    if (f == null) {
        return null;
    }/* www .j  a v  a2s. c  o  m*/

    LOG.d("bmpDecodeFile(" + f.getAbsolutePath() + "," + width_limit + "," + height_limit + "," + max_size + ","
            + max_dimensions + ")");

    Bitmap bmp = null;
    boolean shouldReturn = false;

    FileInputStream fin = null;
    int orientation = ExifInterface.ORIENTATION_NORMAL;
    try {
        // Decode image size
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;

        fin = new FileInputStream(f);
        BitmapFactory.decodeStream(fin, null, o);
        try {
            fin.close();
            fin = null;
        } catch (IOException e) {
        }

        // Find the correct scale value. It should be the power of 2.
        int scale = 1;
        if (width_limit != -1 && height_limit != -1) {
            if (max_dimensions) {
                while (o.outWidth / scale > width_limit || o.outHeight / scale > height_limit)
                    scale *= 2;
            } else {
                while (o.outWidth / scale / 2 >= width_limit && o.outHeight / scale / 2 >= height_limit)
                    scale *= 2;
            }
        } else if (max_size != -1)
            while ((o.outWidth * o.outHeight) / (scale * scale) > max_size)
                scale *= 2;

        // Decode with inSampleSize
        o = null;
        if (scale > 1) {
            o = new BitmapFactory.Options();
            o.inSampleSize = scale;
        }
        fin = new FileInputStream(f);
        try {
            bmp = BitmapFactory.decodeStream(fin, null, o);
        } catch (OutOfMemoryError e) {
            // Try to recover from out of memory error - but keep in mind
            // that behavior after this error is
            // undefined,
            // for example more out of memory errors might appear in catch
            // block.
            if (bmp != null)
                bmp.recycle();
            bmp = null;
            System.gc();
            LOG.e("Util.bmpDecodeFile() OutOfMemoryError in decodeStream()! Trying to recover...");
        }

        if (bmp != null) {
            LOG.d("resulting bitmap width : " + bmp.getWidth() + " height : " + bmp.getHeight() + " size : "
                    + (bmp.getRowBytes() * bmp.getHeight()));

            ExifInterface exif = new ExifInterface(f.getPath());
            orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
        }
    } catch (FileNotFoundException e) {
        shouldReturn = true;
    } catch (IOException e) {
        shouldReturn = true; // bitmap is still valid here, just can't be
        // rotated
    } finally {
        if (fin != null)
            try {
                fin.close();
            } catch (IOException e) {
            }
    }

    if (shouldReturn || bmp == null)
        return bmp;

    float rotate = 0;
    switch (orientation) {
    case ExifInterface.ORIENTATION_ROTATE_90:
        rotate = 90;
        break;
    case ExifInterface.ORIENTATION_ROTATE_180:
        rotate = 180;
        break;
    case ExifInterface.ORIENTATION_ROTATE_270:
        rotate = 270;
        break;
    }
    if (rotate > 0) {
        Matrix matrix = new Matrix();
        matrix.postRotate(rotate);
        Bitmap bmpRot = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(), matrix, true);
        matrix = null;
        bmp.recycle();
        bmp = null;
        // System.gc();
        return bmpRot;
    }

    return bmp;
}

From source file:com.example.photoremark.MainActivity.java

/**
 * ?exif?/*w ww  .jav a  2s.  co  m*/
 *
 * @param path 
 * @return
 */
public int getPictureDegree(String path) {
    int degree = 0;
    try {
        ExifInterface exifInterface = new ExifInterface(path);
        int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                ExifInterface.ORIENTATION_NORMAL);
        switch (orientation) {
        case ExifInterface.ORIENTATION_ROTATE_90:
            degree = 90;
            break;
        case ExifInterface.ORIENTATION_ROTATE_180:
            degree = 180;
            break;
        case ExifInterface.ORIENTATION_ROTATE_270:
            degree = 270;
            break;
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return degree;
}

From source file:com.soma.daemin.fragment.NewPicUploadTaskFragment.java

private static int exifOrientationToDegrees(int exifOrientation) {
    if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_90) {
        return 90;
    } else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_180) {
        return 180;
    } else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_270) {
        return 270;
    }/*from  ww  w  .  j  ava2  s .  co m*/
    return 0;
}

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

public void saveResultPicture(long sessionID) {
    initSavingPrefs();//w  w w.j av  a 2  s.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);
    }
}

From source file:me.tipi.kiosk.ui.fragments.OCRFragment.java

@Override
public void onMetadataAvailable(Metadata metadata) {
    // This method will be called when metadata becomes available during recognition process.
    // Here, for every metadata type that is allowed through metadata settings,
    // desired actions can be performed.
    // detection metadata contains detection locations
    if (metadata instanceof DetectionMetadata) {
        // detection location is written inside DetectorResult
        DetectorResult detectorResult = ((DetectionMetadata) metadata).getDetectionResult();
        // DetectorResult can be null - this means that detection has failed
        if (detectorResult == null) {
            if (mQvManager != null) {
                // begin quadrilateral animation to its default position
                // (internally displays FAIL status)
                mQvManager.animateQuadToDefaultPosition();
            }/*from  w ww  .j ava2  s  .  co  m*/
            // when points of interested have been detected (e.g. QR code), this will be returned as PointsDetectorResult
        } else if (detectorResult instanceof QuadDetectorResult) {
            // begin quadrilateral animation to detected quadrilateral
            mQvManager.animateQuadToDetectionPosition((QuadDetectorResult) detectorResult);
        }
    } else if (metadata instanceof ImageMetadata) {
        // obtain image
        // Please note that Image's internal buffers are valid only
        // until this method ends. If you want to save image for later,
        // obtained a cloned image with image.clone().

        if (guest.passportPath == null || TextUtils.isEmpty(guest.passportPath) || this.results == null) {
            Image image = ((ImageMetadata) metadata).getImage();

            if (image != null && image.getImageType() == ImageType.SUCCESSFUL_SCAN) {
                Timber.w("Metadata type is successful frame image, we go to save it");
                image.clone();
                Timber.w("Ocr meta data captured");
                final Bitmap bitmap = image.convertToBitmap();
                Timber.w("Metadata converted to bitmap");
                final Uri photoUri = ImageUtility.savePassportPicture(getActivity(), bitmap);
                Timber.w("OCR Uri got back from file helper with path: %s",
                        photoUri != null ? photoUri.getPath() : "NO OCR FILE PATH!!!!!");
                ExifInterface ei = null;
                try {
                    ei = new ExifInterface(photoUri.getPath());
                } catch (IOException e) {
                    e.printStackTrace();
                }

                int orientation = ei != null
                        ? ei.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED)
                        : 0;
                Timber.w("Ocr image orientation angle is: %d", orientation);

                Bitmap rotated = null;

                switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    rotated = rotateImage(bitmap, 90);
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    rotated = rotateImage(bitmap, 180);
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    rotated = rotateImage(bitmap, 270);
                    break;
                case ExifInterface.ORIENTATION_UNDEFINED:
                    rotated = rotateImage(bitmap, 90);
                    break;
                case ExifInterface.ORIENTATION_NORMAL:
                default:
                    break;
                }

                final Uri rotatedUri = ImageUtility.savePassportPicture(getActivity(), rotated);
                Timber.w("OCR ROTATED Uri got back from file helper with path: %s",
                        rotatedUri != null ? rotatedUri.getPath() : "NO OCR FILE PATH!!!!!");
                guest.passportPath = rotatedUri.getPath();
                Timber.w("Ocr path saved with path: %s", rotatedUri.getPath());
            }
        } else {
            Timber.w("We have ocr path and it's : %s", guest.passportPath);
        }
        // to convert the image to Bitmap, call image.convertToBitmap()

        // after this line, image gets disposed. If you want to save it
        // for later, you need to clone it with image.clone()
    }
}

From source file:mobisocial.bento.todo.ui.TodoListFragment.java

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (DEBUG)/*from   w w  w.j a  v a2  s .c  o  m*/
        Log.d(TAG, "requestCode: " + requestCode + ", resultCode: " + resultCode);
    if (resultCode == Activity.RESULT_OK) {
        try {
            File imageFile = null;

            if (requestCode == REQUEST_IMAGE_CAPTURE) {

                imageFile = JpgFileHelper.getTmpFile();

            } else if (requestCode == REQUEST_GALLERY) {
                Uri uri = data.getData();
                if (uri == null || uri.toString().length() == 0) {
                    return;
                }

                if (DEBUG)
                    Log.d(TAG, "data URI: " + uri.toString());

                ContentResolver cr = getActivity().getContentResolver();
                String[] columns = { MediaColumns.DATA, MediaColumns.DISPLAY_NAME };
                Cursor c = cr.query(uri, columns, null, null, null);

                if (c != null && c.moveToFirst()) {
                    if (c.getString(0) != null) {
                        //regular processing for gallery files
                        imageFile = new File(c.getString(0));
                    } else {
                        final InputStream is = getActivity().getContentResolver().openInputStream(uri);
                        imageFile = JpgFileHelper.saveTmpFile(is);
                        is.close();
                    }
                } else if (uri.toString().startsWith("content://com.android.gallery3d.provider")) {
                    // motorola xoom doesn't work for contentresolver even if the image comes from picasa.
                    // So just adds the condition of startsWith...
                    // See in detail : http://dimitar.me/how-to-get-picasa-images-using-the-image-picker-on-android-devices-running-any-os-version/
                    uri = Uri.parse(
                            uri.toString().replace("com.android.gallery3d", "com.google.android.gallery3d"));
                    final InputStream is = getActivity().getContentResolver().openInputStream(uri);
                    imageFile = JpgFileHelper.saveTmpFile(is);
                    is.close();
                } else {
                    // http or https
                    HttpURLConnection http = null;
                    URL url = new URL(uri.toString());
                    http = (HttpURLConnection) url.openConnection();
                    http.setRequestMethod("GET");
                    http.connect();

                    final InputStream is = http.getInputStream();
                    imageFile = JpgFileHelper.saveTmpFile(is);
                    is.close();
                    if (http != null)
                        http.disconnect();
                }
            }

            if (imageFile.exists() && imageFile.length() > 0) {
                if (DEBUG)
                    Log.d(TAG, "imageFile exists=" + imageFile.exists() + " length=" + imageFile.length()
                            + " path=" + imageFile.getPath());

                float degrees = 0;
                try {
                    ExifInterface exif = new ExifInterface(imageFile.getPath());
                    switch (exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                            ExifInterface.ORIENTATION_NORMAL)) {
                    case ExifInterface.ORIENTATION_ROTATE_90:
                        degrees = 90;
                        break;
                    case ExifInterface.ORIENTATION_ROTATE_180:
                        degrees = 180;
                        break;
                    case ExifInterface.ORIENTATION_ROTATE_270:
                        degrees = 270;
                        break;
                    default:
                        degrees = 0;
                        break;
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }

                Bitmap bitmap = BitmapHelper.getResizedBitmap(imageFile, BitmapHelper.MAX_IMAGE_WIDTH,
                        BitmapHelper.MAX_IMAGE_HEIGHT, degrees);

                TodoListItem item = new TodoListItem();
                item.uuid = UUID.randomUUID().toString();
                item.title = "";
                item.description = "";
                item.bDone = false;
                item.hasImage = true;
                item.creDateMillis = System.currentTimeMillis();
                item.modDateMillis = System.currentTimeMillis();
                item.creContactId = mManager.getLocalContactId();
                item.modContactId = mManager.getLocalContactId();

                StringBuilder msg = new StringBuilder(
                        getString(R.string.feed_msg_added_photo, mManager.getLocalName()));
                String plainMsg = UIUtils.getPlainString(mManager.getBentoListItem().bento.name,
                        msg.toString());

                mManager.addTodo(item, bitmap, plainMsg);

                refreshView();

                JpgFileHelper.deleteTmpFile();
            }

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

From source file:com.klinker.android.twitter.activities.compose.Compose.java

public static Bitmap rotateBitmap(Bitmap bitmap, int orientation) {

    Log.v("talon_composing_image", "rotation: " + orientation);

    try {//from   ww  w.j a  va 2  s . c o  m
        Matrix matrix = new Matrix();
        switch (orientation) {
        case ExifInterface.ORIENTATION_NORMAL:
            return bitmap;
        case ExifInterface.ORIENTATION_FLIP_HORIZONTAL:
            matrix.setScale(-1, 1);
            break;
        case ExifInterface.ORIENTATION_ROTATE_180:
            matrix.setRotate(180);
            break;
        case ExifInterface.ORIENTATION_FLIP_VERTICAL:
            matrix.setRotate(180);
            matrix.postScale(-1, 1);
            break;
        case ExifInterface.ORIENTATION_TRANSPOSE:
            matrix.setRotate(90);
            matrix.postScale(-1, 1);
            break;
        case ExifInterface.ORIENTATION_ROTATE_90:
            matrix.setRotate(90);
            break;
        case ExifInterface.ORIENTATION_TRANSVERSE:
            matrix.setRotate(-90);
            matrix.postScale(-1, 1);
            break;
        case ExifInterface.ORIENTATION_ROTATE_270:
            matrix.setRotate(-90);
            break;
        default:
            return bitmap;
        }
        try {
            Bitmap bmRotated = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix,
                    true);
            bitmap.recycle();
            return bmRotated;
        } catch (OutOfMemoryError e) {
            e.printStackTrace();
            return null;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return bitmap;
}

From source file:com.cloverstudio.spika.CameraCropActivity.java

protected void onPhotoTaken(String path) {

    String fileName = Uri.parse(path).getLastPathSegment();
    mFilePath = CameraCropActivity.this.getExternalCacheDir() + "/" + fileName;

    if (!path.equals(mFilePath)) {
        copy(new File(path), new File(mFilePath));
    }/* w  ww .  ja  va2  s  .c o  m*/

    new AsyncTask<String, Void, byte[]>() {
        boolean loadingFailed = false;

        @Override
        protected byte[] doInBackground(String... params) {
            try {

                if (params == null)
                    return null;

                File f = new File(params[0]);
                ExifInterface exif = new ExifInterface(f.getPath());
                int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                        ExifInterface.ORIENTATION_NORMAL);

                int angle = 0;

                if (orientation == ExifInterface.ORIENTATION_ROTATE_90) {
                    angle = 90;
                } else if (orientation == ExifInterface.ORIENTATION_ROTATE_180) {
                    angle = 180;
                } else if (orientation == ExifInterface.ORIENTATION_ROTATE_270) {
                    angle = 270;
                }

                Matrix mat = new Matrix();
                mat.postRotate(angle);

                BitmapFactory.Options optionsMeta = new BitmapFactory.Options();
                optionsMeta.inJustDecodeBounds = true;
                BitmapFactory.decodeFile(f.getAbsolutePath(), optionsMeta);

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

                options.inSampleSize = BitmapManagement.calculateInSampleSize(optionsMeta, 640, 640);
                options.inPurgeable = true;
                options.inInputShareable = true;
                mBitmap = BitmapFactory.decodeStream(new FileInputStream(f), null, options);
                mBitmap = Bitmap.createBitmap(mBitmap, 0, 0, mBitmap.getWidth(), mBitmap.getHeight(), mat,
                        true);
                _scaleBitmap();
                return null;
            } catch (Exception ex) {
                loadingFailed = true;
                finish();
            }

            return null;
        }

        @Override
        protected void onPostExecute(byte[] result) {
            super.onPostExecute(result);

            if (null != mBitmap) {
                mImageView.setImageBitmap(mBitmap);
                mImageView.setScaleType(ScaleType.MATRIX);
                translateMatrix.setTranslate(-(mBitmap.getWidth() - crop_container_size) / 2f,
                        -(mBitmap.getHeight() - crop_container_size) / 2f);
                mImageView.setImageMatrix(translateMatrix);

                matrix = translateMatrix;

            }

        }
    }.execute(mFilePath);

}

From source file:mobisocial.bento.ebento.ui.EditFragment.java

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (DEBUG)/*from   ww w .  j av  a  2  s .  co  m*/
        Log.d(TAG, "requestCode: " + requestCode + ", resultCode: " + resultCode);
    if (resultCode == Activity.RESULT_OK) {
        try {
            File imageFile = null;

            if (requestCode == REQUEST_IMAGE_CAPTURE) {

                imageFile = JpgFileHelper.getTmpFile();

            } else if (requestCode == REQUEST_GALLERY) {
                Uri uri = data.getData();
                if (uri == null || uri.toString().length() == 0) {
                    return;
                }
                if (DEBUG)
                    Log.d(TAG, "data URI: " + uri.toString());

                ContentResolver cr = getActivity().getContentResolver();
                String[] columns = { MediaColumns.DATA, MediaColumns.DISPLAY_NAME };
                Cursor c = cr.query(uri, columns, null, null, null);

                if (c != null && c.moveToFirst()) {
                    if (c.getString(0) != null) {
                        //regular processing for gallery files
                        imageFile = new File(c.getString(0));
                    } else {
                        final InputStream is = getActivity().getContentResolver().openInputStream(uri);
                        imageFile = JpgFileHelper.saveTmpFile(is);
                        is.close();
                    }
                } else if (uri.toString().startsWith("content://com.android.gallery3d.provider")) {
                    // motorola xoom doesn't work for contentresolver even if the image comes from picasa.
                    // So just adds the condition of startsWith...
                    // See in detail : http://dimitar.me/how-to-get-picasa-images-using-the-image-picker-on-android-devices-running-any-os-version/
                    uri = Uri.parse(
                            uri.toString().replace("com.android.gallery3d", "com.google.android.gallery3d"));
                    final InputStream is = getActivity().getContentResolver().openInputStream(uri);
                    imageFile = JpgFileHelper.saveTmpFile(is);
                    is.close();
                } else {
                    // http or https
                    HttpURLConnection http = null;
                    URL url = new URL(uri.toString());
                    http = (HttpURLConnection) url.openConnection();
                    http.setRequestMethod("GET");
                    http.connect();

                    final InputStream is = http.getInputStream();
                    imageFile = JpgFileHelper.saveTmpFile(is);
                    is.close();
                    if (http != null)
                        http.disconnect();
                }
            }

            if (imageFile.exists() && imageFile.length() > 0) {
                if (DEBUG)
                    Log.d(TAG, "imageFile exists=" + imageFile.exists() + " length=" + imageFile.length()
                            + " path=" + imageFile.getPath());

                float degrees = 0;
                try {
                    ExifInterface exif = new ExifInterface(imageFile.getPath());
                    switch (exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                            ExifInterface.ORIENTATION_NORMAL)) {
                    case ExifInterface.ORIENTATION_ROTATE_90:
                        degrees = 90;
                        break;
                    case ExifInterface.ORIENTATION_ROTATE_180:
                        degrees = 180;
                        break;
                    case ExifInterface.ORIENTATION_ROTATE_270:
                        degrees = 270;
                        break;
                    default:
                        degrees = 0;
                        break;
                    }
                    Log.d(TAG, exif.getAttribute(ExifInterface.TAG_ORIENTATION));
                } catch (IOException e) {
                    e.printStackTrace();
                }

                sImageOrg = BitmapHelper.getResizedBitmap(imageFile, BitmapHelper.MAX_IMAGE_WIDTH,
                        BitmapHelper.MAX_IMAGE_HEIGHT, degrees);
                mbImageChanged = true;

                // ImageView
                mImageView.setImageBitmap(
                        BitmapHelper.getResizedBitmap(sImageOrg, mTargetWidth, mTargetHeight, 0));
                mImageView.setVisibility(View.VISIBLE);
                mRootView.invalidate();

                imageFile.delete();
                JpgFileHelper.deleteTmpFile();
            }

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

From source file:org.openmrs.mobile.activities.addeditpatient.AddEditPatientFragment.java

private Bitmap getPortraitImage(String imagePath) {
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inSampleSize = 4;//from ww w  . j a va 2s  . c o  m
    Bitmap photo = BitmapFactory.decodeFile(output.getPath(), options);
    float rotateAngle;
    try {
        ExifInterface exifInterface = new ExifInterface(imagePath);
        int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                ExifInterface.ORIENTATION_UNDEFINED);
        switch (orientation) {
        case ExifInterface.ORIENTATION_ROTATE_270:
            rotateAngle = 270;
            break;
        case ExifInterface.ORIENTATION_ROTATE_180:
            rotateAngle = 180;
            break;
        case ExifInterface.ORIENTATION_ROTATE_90:
            rotateAngle = 90;
            break;
        default:
            rotateAngle = 0;
            break;
        }
        return rotateImage(photo, rotateAngle);
    } catch (IOException e) {
        logger.e(e.getMessage());
        return photo;
    }
}