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:Main.java

public static Matrix rotateImage(Context context, Uri imageUri, File f) {
    Matrix matrix = new Matrix();
    try {//  w w  w .  j  av  a  2 s. co  m
        if (imageUri != null) {
            context.getContentResolver().notifyChange(imageUri, null);
        }
        ExifInterface exif = new ExifInterface(f.getAbsolutePath());
        int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);

        switch (orientation) {
        case ExifInterface.ORIENTATION_ROTATE_270:
            matrix.postRotate(270);
            break;
        case ExifInterface.ORIENTATION_ROTATE_180:
            matrix.postRotate(180);
            break;
        case ExifInterface.ORIENTATION_ROTATE_90:
            matrix.postRotate(90);
            break;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return matrix;
}

From source file:com.pdftron.pdf.utils.ViewerUtils.java

public static Map readImageIntent(Intent data, Context context, Uri outputFileUri)
        throws FileNotFoundException, Exception {
    final boolean isCamera;
    if (data == null || data.getData() == null) {
        isCamera = true;/*from www  .j av  a2  s  . c  om*/
    } else {
        final String action = data.getAction();
        if (action == null) {
            isCamera = false;
        } else {
            isCamera = action.equals(MediaStore.ACTION_IMAGE_CAPTURE);
        }
    }

    Uri imageUri;
    if (isCamera) {
        imageUri = outputFileUri;
        AnalyticsHandlerAdapter.getInstance().sendEvent(AnalyticsHandlerAdapter.CATEGORY_FILEBROWSER,
                "Create new document from camera selected");
    } else {
        imageUri = data.getData();
        AnalyticsHandlerAdapter.getInstance().sendEvent(AnalyticsHandlerAdapter.CATEGORY_FILEBROWSER,
                "Create new document from local image file selected");
    }

    String filePath;
    if (isCamera) {
        filePath = imageUri.getPath();
    } else {
        filePath = Utils.getRealPathFromImageURI(context, imageUri);
        if (Utils.isNullOrEmpty(filePath)) {
            filePath = imageUri.getPath();
        }
    }

    // try to get bitmap
    Bitmap bitmap = Utils.getBitmapFromImageUri(context, imageUri, filePath);

    // if a file is selected, check if it is an image file
    if (!isCamera) {
        // if type is null
        if (context.getContentResolver().getType(imageUri) == null) {
            String extension = MimeTypeMap.getFileExtensionFromUrl(imageUri.getPath());
            final String[] extensions = { "jpeg", "jpg", "tiff", "tif", "gif", "png", "bmp" };

            // if file extension is not an image extension
            if (!Arrays.asList(extensions).contains(extension) && extension != null && !extension.equals("")) {
                throw new FileNotFoundException("file extension is not an image extension");
            }
            // if type is not an image
        } else if (!context.getContentResolver().getType(imageUri).startsWith("image/")) {
            throw new FileNotFoundException("type is not an image");
        }
    }

    //////////////////  Determine if image needs to be rotated   ///////////////////
    File imageFile = new File(imageUri.getPath());
    ExifInterface exif = new ExifInterface(imageFile.getAbsolutePath());
    int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED);

    int imageRotation = 0;
    switch (orientation) {
    case ExifInterface.ORIENTATION_ROTATE_270:
        imageRotation = 270;
        break;
    case ExifInterface.ORIENTATION_ROTATE_180:
        imageRotation = 180;
        break;
    case ExifInterface.ORIENTATION_ROTATE_90:
        imageRotation = 90;
        break;
    }

    // in some devices (mainly Samsung), the EXIF is not saved with the image so look at the content
    // resolver as a second source of the image's rotation
    if (imageRotation == 0) {
        String[] orientationColumn = { MediaStore.Images.Media.ORIENTATION };
        Cursor cur = context.getContentResolver().query(imageUri, orientationColumn, null, null, null);
        orientation = -1;
        if (cur != null && cur.moveToFirst()) {
            orientation = cur.getInt(cur.getColumnIndex(orientationColumn[0]));
        }

        if (orientation > 0) {
            imageRotation = orientation;
        }
    }

    if (imageRotation != 0) {
        Matrix matrix = new Matrix();
        matrix.postRotate(imageRotation);
        bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
    }

    Map<String, Object> output = new HashMap<>();
    output.put("bitmap", bitmap);
    output.put("uri", imageUri);
    output.put("path", filePath);
    output.put("camera", isCamera);
    return output;
}

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;
    }//from w w  w .ja  va  2s. co  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.ruesga.rview.misc.BitmapUtils.java

private static Bitmap decodeExifBitmap(File file, Bitmap src) {
    if (src != null) {
        try {//www .  j  av  a  2  s  . co  m
            // Try to load the bitmap as a bitmap file
            ExifInterface exif = new ExifInterface(file.getAbsolutePath());
            int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);
            if (orientation == ExifInterface.ORIENTATION_UNDEFINED
                    || orientation == ExifInterface.ORIENTATION_NORMAL) {
                return src;
            }
            Matrix matrix = new Matrix();
            switch (orientation) {
            case ExifInterface.ORIENTATION_ROTATE_90:
                matrix.postRotate(90);
                break;
            case ExifInterface.ORIENTATION_ROTATE_180:
                matrix.postRotate(180);
                break;
            case ExifInterface.ORIENTATION_ROTATE_270:
                matrix.postRotate(270);
                break;
            case ExifInterface.ORIENTATION_FLIP_HORIZONTAL:
                matrix.setScale(-1, 1);
                matrix.postTranslate(src.getWidth(), 0);
                break;
            case ExifInterface.ORIENTATION_FLIP_VERTICAL:
                matrix.setScale(1, -1);
                matrix.postTranslate(0, src.getHeight());
                break;
            }
            // Rotate the bitmap
            return Bitmap.createBitmap(src, 0, 0, src.getWidth(), src.getHeight(), matrix, true);
        } catch (IOException e) {
            // Ignore
        }
    }
    return src;
}

From source file:com.owncloud.android.utils.BitmapUtils.java

/**
 * Rotate bitmap according to EXIF orientation. 
 * Cf. http://www.daveperrett.com/articles/2012/07/28/exif-orientation-handling-is-a-ghetto/ 
 * @param bitmap Bitmap to be rotated/*from ww  w  .  j  a va2s .  c  om*/
 * @param storagePath Path to source file of bitmap. Needed for EXIF information.
 * @return correctly EXIF-rotated bitmap
 */
public static Bitmap rotateImage(final Bitmap bitmap, final String storagePath) {
    try {
        ExifInterface exifInterface = new ExifInterface(storagePath);
        final int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);

        Matrix matrix = new Matrix();
        // 1: nothing to do

        switch (orientation) {
        case ExifInterface.ORIENTATION_FLIP_HORIZONTAL:
            matrix.postScale(-1.0f, 1.0f);
            break;
        case ExifInterface.ORIENTATION_ROTATE_180:
            matrix.postRotate(180);
            break;
        case ExifInterface.ORIENTATION_FLIP_VERTICAL:
            matrix.postScale(1.0f, -1.0f);
            break;
        case ExifInterface.ORIENTATION_TRANSPOSE:
            matrix.postRotate(-90);
            matrix.postScale(1.0f, -1.0f);
            break;
        case ExifInterface.ORIENTATION_ROTATE_90:
            matrix.postRotate(90);
            break;
        case ExifInterface.ORIENTATION_TRANSVERSE:
            matrix.postRotate(90);
            matrix.postScale(1.0f, -1.0f);
            break;
        case ExifInterface.ORIENTATION_ROTATE_270:
            matrix.postRotate(270);
            break;
        }

        // Rotate the bitmap
        final Bitmap resultBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(),
                matrix, true);
        if (resultBitmap != bitmap) {
            bitmap.recycle();
        }
        return resultBitmap;
    } catch (Exception exception) {
        Log_OC.e("BitmapUtil", "Could not rotate the image: " + storagePath);
        return bitmap;
    }
}

From source file:org.kontalk.util.MediaStorage.java

/**
 * Tries various methods for obtaining the rotation of the image.
 * @return a matrix to rotate the image (if any)
 *//*from  www  .  j  av a 2s.  c o m*/
private static Matrix getRotation(Context context, Uri media) throws IOException {
    // method 1: query the media storage
    Cursor cursor = context.getContentResolver().query(media,
            new String[] { MediaStore.Images.ImageColumns.ORIENTATION }, null, null, null);

    if (cursor != null) {
        cursor.moveToFirst();
        int orientation = cursor.getInt(0);
        cursor.close();

        if (orientation != 0) {
            Matrix m = new Matrix();
            m.postRotate(orientation);

            return m;
        }
    }

    // method 2: write media contents to a temporary file and run ExifInterface
    InputStream in = context.getContentResolver().openInputStream(media);
    OutputStream out = null;
    File tmp = null;
    try {
        tmp = File.createTempFile("rotation", null, context.getCacheDir());
        out = new FileOutputStream(tmp);

        SystemUtils.copy(in, out);
        // flush the file
        out.close();

        ExifInterface exif = new ExifInterface(tmp.toString());
        int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);
        Matrix matrix = new Matrix();
        switch (orientation) {
        case ExifInterface.ORIENTATION_ROTATE_90:
            matrix.postRotate(90);
            break;
        case ExifInterface.ORIENTATION_ROTATE_180:
            matrix.postRotate(180);
            break;
        case ExifInterface.ORIENTATION_ROTATE_270:
            matrix.postRotate(270);
            break;
        default:
            return null;
        }

        return matrix;
    } finally {
        if (tmp != null)
            tmp.delete();
        SystemUtils.closeStream(in);
        SystemUtils.closeStream(out);
    }
}

From source file:eu.nubomedia.nubomedia_kurento_health_communicator_android.kc_and_communicator.util.FileUtils.java

public static Bitmap decodeSampledBitmapFromPath(String path, int reqWidth, int reqHeight) {
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;//from  w w  w .j  a  v  a  2 s.com
    BitmapFactory.decodeFile(path, options);
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
    options.inJustDecodeBounds = false;

    Bitmap b = BitmapFactory.decodeFile(path, options);

    ExifInterface exif;
    try {
        exif = new ExifInterface(path);
    } catch (IOException e) {
        return null;
    }
    int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);
    Matrix matrix = new Matrix();
    if (orientation == 6)
        matrix.postRotate(90);
    else if (orientation == 3)
        matrix.postRotate(180);
    else if (orientation == 8)
        matrix.postRotate(270);

    return Bitmap.createBitmap(b, 0, 0, b.getWidth(), b.getHeight(), matrix, true);
}

From source file:com.ultramegasoft.flavordex2.util.PhotoUtils.java

/**
 * Rotate an image according to its EXIF data.
 *
 * @param context The Context/*from   w  w  w .java  2 s .  com*/
 * @param uri     The Uri to the image file
 * @param bitmap  The Bitmap to rotate
 * @return The rotated Bitmap
 */
@NonNull
private static Bitmap rotatePhoto(@NonNull Context context, @NonNull Uri uri, @NonNull Bitmap bitmap) {
    uri = getImageUri(context, uri);
    int rotation = 0;

    if ("file".equals(uri.getScheme())) {
        try {
            final ExifInterface exif = new ExifInterface(uri.getPath());
            switch (exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 0)) {
            case ExifInterface.ORIENTATION_ROTATE_90:
                rotation = 90;
                break;
            case ExifInterface.ORIENTATION_ROTATE_180:
                rotation = 180;
                break;
            case ExifInterface.ORIENTATION_ROTATE_270:
                rotation = 270;
            }
        } catch (IOException e) {
            Log.e(TAG, "Failed to read EXIF data for " + uri.toString(), e);
        }
    } else {
        final ContentResolver cr = context.getContentResolver();
        final String[] projection = new String[] { MediaStore.Images.ImageColumns.ORIENTATION };
        final Cursor cursor = cr.query(uri, projection, null, null, null);
        if (cursor != null) {
            try {
                if (cursor.moveToFirst() && cursor.getColumnCount() > 0) {
                    rotation = cursor.getInt(0);
                }
            } finally {
                cursor.close();
            }
        }
    }

    if (rotation != 0) {
        final Matrix matrix = new Matrix();
        matrix.postRotate(rotation);
        return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
    }

    return bitmap;
}

From source file:com.example.android.camera.CameraActivity.java

public static void prepareMatrix(Matrix matrix, int displayOrientation, int viewWidth, int viewHeight) {

    Log.d("face CameraPreview", "Width: " + viewWidth + " Height: " + viewHeight);

    // This is the value for android.hardware.Camera.setDisplayOrientation.
    matrix.postRotate(displayOrientation);

    // Camera driver coordinates range from (-1000, -1000) to (1000, 1000).
    // UI coordinates range from (0, 0) to (width, height).
    // Log.d("face View", "Width: " + viewWidth + " x Height: " + viewHeight);
    matrix.postScale(viewWidth / 2000f, viewHeight / 2000f);
    //        matrix.postTranslate(viewWidth / 2f, viewHeight / 2f);
    matrix.setTranslate(viewWidth / 2f, viewHeight / 2f);
}

From source file:com.appsimobile.appsii.module.weather.WeatherLoadingService.java

/**
 * Downloads the header images for the given woeid and weather-data. Failure is considered
 * non-fatal./* w  w w .j  a v  a2 s  .  co m*/
 *
 * @throws VolleyError
 */
public static void downloadWeatherImages(Context context, BitmapUtils bitmapUtils, String woeid,
        WeatherData weatherData, String timezone) throws VolleyError {

    WindowManager windowManager = AppInjector.provideWindowManager();

    // first we need to determine if it is day or night.
    // TODO: this needs the timezone

    if (timezone == null) {
        timezone = TimeZone.getDefault().getID();
    }

    WeatherUtils weatherUtils = AppInjector.provideWeatherUtils();
    boolean isDay = weatherUtils.isDay(timezone, weatherData);
    ImageDownloadHelper downloadHelper = ImageDownloadHelper.getInstance(context);

    // call into the download-helper this will return a json object with
    // city photos matching the current weather condition.
    JSONObject photos = downloadHelper.searchCityWeatherPhotos(woeid, weatherData.nowConditionCode, isDay);

    // Now we need the screen dimension to know which photos have a usable size.
    int dimen = getMaxScreenDimension(windowManager);

    // determine the photos that can be used.
    List<ImageDownloadHelper.PhotoInfo> result = new ArrayList<>();
    ImageDownloadHelper.getEligiblePhotosFromResponse(photos, result, dimen);

    // when no usable photos have been found try photos at the city level with
    // no weather condition info.
    if (result.isEmpty()) {
        photos = downloadHelper.searchCityImage(woeid);
        ImageDownloadHelper.getEligiblePhotosFromResponse(photos, result, dimen);
        // when still no photo was found, clear the existing photos and return
        if (result.isEmpty()) {
            weatherUtils.clearCityPhotos(context, woeid, 0);
            return;
        }
    }

    // Now determine the amount of photos we should download
    int N = Math.min(MAX_PHOTO_COUNT, result.size());
    // idx keeps the index of the actually downloaded photo count
    int idx = 0;
    // note the idx < N instead of i < N.
    // this loop must continue until the amount is satisfied.
    for (int i = 0; idx < N; i++) {
        // quit when the end of the list is reached
        if (i >= result.size())
            break;

        // try to download the photo details from the webservice.
        ImageDownloadHelper.PhotoInfo info = result.get(i);
        JSONObject photoInfo = downloadHelper.loadPhotoInfo(context, info.id);
        if (photoInfo != null) {

            // we need to know if the photo is rotated. If so, we need to apply this
            // rotation after download.
            int rotation = ImageDownloadHelper.getRotationFromJson(photoInfo);
            if (downloadFile(context, info, woeid, idx)) {
                // Apply rotation when non zero
                if (rotation != 0) {
                    File cacheDir = weatherUtils.getWeatherPhotoCacheDir(context);
                    String fileName = weatherUtils.createPhotoFileName(woeid, idx);
                    File photoImage = new File(cacheDir, fileName);
                    Bitmap bitmap = bitmapUtils.decodeSampledBitmapFromFile(photoImage, dimen, dimen);
                    if (bitmap == null) {
                        Log.wtf("WeatherLoadingService", "error decoding bitmap");
                        continue;
                    }

                    Matrix matrix = new Matrix();
                    matrix.postRotate(rotation);
                    bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix,
                            false);
                    weatherUtils.saveBitmap(context, bitmap, woeid, idx);
                }
                // success, handle the next one.
                idx++;
            }
        }
    }
    // remove photos at higher indexes than the amount downloaded.
    weatherUtils.clearCityPhotos(context, woeid, idx + 1);

}