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 Bitmap makeSquare(File file, int cameraID) {
    int width;/*from   ww w  . j  a  v  a2s .  c  om*/
    int height;
    Matrix matrix = new Matrix();
    Camera.CameraInfo info = new Camera.CameraInfo();
    Camera.getCameraInfo(cameraID, info);
    // Convert ByteArray to Bitmap

    Bitmap bitPic = decodeSampledBitmapFromFile(destinationFile.getAbsolutePath(), 800, 800);//BitmapFactory.decodeByteArray(data, 0, data.length);
    width = bitPic.getWidth();
    height = bitPic.getHeight();

    // Perform matrix rotations/mirrors depending on camera that took the photo
    if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
        float[] mirrorY = { -1, 0, 0, 0, 1, 0, 0, 0, 1 };
        Matrix matrixMirrorY = new Matrix();
        matrixMirrorY.setValues(mirrorY);

        matrix.postConcat(matrixMirrorY);
    }

    matrix.postRotate(90);

    // Create new Bitmap out of the old one
    Bitmap bitPicFinal = Bitmap.createBitmap(bitPic, 0, 0, width, height, matrix, true);
    bitPic.recycle();
    int desWidth;
    int desHeight;
    desWidth = bitPicFinal.getWidth();
    desHeight = desWidth;
    Bitmap croppedBitmap = Bitmap.createBitmap(bitPicFinal, 0,
            bitPicFinal.getHeight() / 2 - bitPicFinal.getWidth() / 2, desWidth, desHeight);
    croppedBitmap = Bitmap.createScaledBitmap(croppedBitmap, 528, 528, true);
    return croppedBitmap;
}

From source file:com.mobantica.DriverItRide.activities.ActivityProfile.java

public static Bitmap rotateImage(Bitmap source, float angle) {
    Bitmap retVal;//  w w  w .  j  av a2 s  .  c  o  m
    Matrix matrix = new Matrix();
    matrix.postRotate(angle);
    retVal = Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), matrix, true);
    return retVal;
}

From source file:org.matrix.androidsdk.db.MXMediaWorkerTask.java

/**
 * Search a cached bitmap from an url.//from  w ww.j  av a 2s  .  c o m
 * rotationAngle is set to Integer.MAX_VALUE when undefined : the EXIF metadata must be checked.
 *
 * @param baseFile the base file
 * @param url the media url
 * @param rotation the bitmap rotation
 * @param mimeType the mime type
 * @return the cached bitmap or null it does not exist
 */
public static Bitmap bitmapForURL(Context context, File baseFile, String url, int rotation, String mimeType) {
    Bitmap bitmap = null;

    // sanity check
    if (null != url) {

        if (null == sMemoryCache) {
            int lruSize = Math.min(20 * 1024 * 1024, (int) Runtime.getRuntime().maxMemory() / 8);

            Log.d(LOG_TAG, "bitmapForURL  lruSize : " + lruSize);

            sMemoryCache = new LruCache<String, Bitmap>(lruSize) {
                @Override
                protected int sizeOf(String key, Bitmap bitmap) {
                    return bitmap.getRowBytes() * bitmap.getHeight(); // size in bytes
                }
            };
        }

        // the image is downloading in background
        if (null != mediaWorkerTaskForUrl(url)) {
            return null;
        }

        synchronized (sMemoryCache) {
            bitmap = sMemoryCache.get(url);
        }

        if (null == bitmap) {
            // if some medias are not found
            // do not try to reload them until the next application launch.
            synchronized (mFileNotFoundUrlsList) {
                if (mFileNotFoundUrlsList.indexOf(url) >= 0) {
                    bitmap = BitmapFactory.decodeResource(context.getResources(),
                            android.R.drawable.ic_menu_gallery);
                }
            }
        }

        // check if the image has not been saved in file system
        if ((null == bitmap) && (null != baseFile)) {
            String filename = null;

            // the url is a file one
            if (url.startsWith("file:")) {
                // try to parse it
                try {
                    Uri uri = Uri.parse(url);
                    filename = uri.getPath();

                } catch (Exception e) {
                }

                // cannot extract the filename -> sorry
                if (null == filename) {
                    return null;
                }
            }

            // not a valid file name
            if (null == filename) {
                filename = buildFileName(url, mimeType);
            }

            try {
                File file = filename.startsWith(File.separator) ? new File(filename)
                        : new File(baseFile, filename);

                if (!file.exists()) {
                    Log.d(LOG_TAG, "bitmapForURL() : " + filename + " does not exist");
                    return null;
                }

                FileInputStream fis = new FileInputStream(file);

                // read the metadata
                if (Integer.MAX_VALUE == rotation) {
                    rotation = ImageUtils.getRotationAngleForBitmap(context, Uri.fromFile(file));
                }

                if (null != fis) {
                    BitmapFactory.Options options = new BitmapFactory.Options();
                    options.inPreferredConfig = Bitmap.Config.ARGB_8888;

                    try {
                        bitmap = BitmapFactory.decodeStream(fis, null, options);
                    } catch (OutOfMemoryError error) {
                        System.gc();
                        Log.e(LOG_TAG, "bitmapForURL() : Out of memory 1 " + error);
                    }

                    //  try again
                    if (null == bitmap) {
                        try {
                            bitmap = BitmapFactory.decodeStream(fis, null, options);
                        } catch (OutOfMemoryError error) {
                            Log.e(LOG_TAG, "bitmapForURL() Out of memory 2" + error);
                        }
                    }

                    if (null != bitmap) {
                        synchronized (sMemoryCache) {
                            if (0 != rotation) {
                                try {
                                    android.graphics.Matrix bitmapMatrix = new android.graphics.Matrix();
                                    bitmapMatrix.postRotate(rotation);

                                    Bitmap transformedBitmap = Bitmap.createBitmap(bitmap, 0, 0,
                                            bitmap.getWidth(), bitmap.getHeight(), bitmapMatrix, false);
                                    bitmap.recycle();
                                    bitmap = transformedBitmap;
                                } catch (OutOfMemoryError ex) {
                                }
                            }

                            // cache only small images
                            // caching large images does not make sense
                            // it would replace small ones.
                            // let assume that the application must be faster when showing the chat history.
                            if ((bitmap.getWidth() < 1000) && (bitmap.getHeight() < 1000)) {
                                sMemoryCache.put(url, bitmap);
                            }
                        }
                    }

                    fis.close();
                }

            } catch (FileNotFoundException e) {
                Log.d(LOG_TAG, "bitmapForURL() : " + filename + " does not exist");
            } catch (Exception e) {
                Log.e(LOG_TAG, "bitmapForURL() " + e);

            }
        }
    }

    return bitmap;
}

From source file:com.stfalcon.contentmanager.ContentManager.java

public static Bitmap rotate(Bitmap bitmap, int degree) {
    int w = bitmap.getWidth();
    int h = bitmap.getHeight();

    Matrix mtx = new Matrix();
    mtx.postRotate(degree);

    return Bitmap.createBitmap(bitmap, 0, 0, w, h, mtx, true);
}

From source file:Main.java

public static Bitmap createCorrectlyRotatedBitmapIfNeeded(Bitmap bitmap, String jpegPath, float scale) {
    // Rotate the image if necessary; all images are shot in LANDSCAPE mode
    try {//from www .  j a  va 2  s. c  o m
        ExifInterface exif = new ExifInterface(jpegPath);

        int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);
        Log.d("CashLensUtils", "image has orientation " + Integer.toString(orientation) + ", width "
                + Integer.toString(bitmap.getWidth()) + ", height " + Integer.toString(bitmap.getHeight()));

        Matrix matrix = new Matrix();

        if (scale != 1.0f)
            matrix.preScale(scale, scale);

        // From http://sylvana.net/jpegcrop/exif_orientation.html
        // For convenience, here is what the letter F would look like if it were tagged correctly 
        // and displayed by a program that ignores the orientation tag (thus showing the stored image):
        //   (1)       2      (3)      4         5          (6)          7         (8)
        //
        //   888888  888888      88  88      8888888888  88                  88  8888888888
        //   88          88      88  88      88  88      88  88          88  88      88  88
        //   8888      8888    8888  8888    88          8888888888  8888888888          88
        //   88          88      88  88
        //   88          88  888888  888888

        if (orientation == 3)
            matrix.postRotate(180);
        else if (orientation == 6)
            matrix.postRotate(90);
        else if (orientation == 8)
            matrix.postRotate(-90);

        if (orientation != 1 || scale != 1.0f) {
            // Create a new image with the correct (maybe rotated) width/height
            Bitmap newImage = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix,
                    true);

            Log.d("CashLensUtils", "created a new image with width " + Integer.toString(newImage.getWidth())
                    + ", height " + Integer.toString(newImage.getHeight()));

            // Replace original image
            return newImage;
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    return bitmap;
}

From source file:Main.java

private static Bitmap turnPic(final String path, Bitmap bitmap) {

    ExifInterface exif;//from   w w  w .  j  a va2s.co  m
    final int ninetyDegrees = 90;
    int rotationAngle = 0;
    Matrix matrix = new Matrix();

    if (path != null) {
        try {
            exif = new ExifInterface(path);
            int exifOrientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                    ExifInterface.ORIENTATION_NORMAL);
            switch (exifOrientation) {
            case ExifInterface.ORIENTATION_ROTATE_90:
                rotationAngle = ninetyDegrees;
                break;
            case ExifInterface.ORIENTATION_ROTATE_180:
                rotationAngle = ninetyDegrees * 2;
                break;
            case ExifInterface.ORIENTATION_ROTATE_270:
                rotationAngle = ninetyDegrees * 3;
                break;
            case ExifInterface.ORIENTATION_NORMAL:
            default:
                break;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return bitmap;
        }
        if (rotationAngle != 0) {
            matrix.postRotate(rotationAngle);
        }
        bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
    }
    return bitmap;
}

From source file:org.matrix.androidsdk.db.MXMediaDownloadWorkerTask.java

/**
 * Search a cached bitmap from an url./*from w  ww .j a va2s  .co  m*/
 * rotationAngle is set to Integer.MAX_VALUE when undefined : the EXIF metadata must be checked.
 *
 * @param baseFile the base file
 * @param url the media url
 * @param rotation the bitmap rotation
 * @param mimeType the mime type
 * @return the cached bitmap
 */
public static Bitmap bitmapForURL(Context context, File baseFile, String url, int rotation, String mimeType) {
    Bitmap bitmap = null;

    // sanity check
    if (null != url) {

        if (null == mBitmapByUrlCache) {
            int lruSize = Math.min(20 * 1024 * 1024, (int) Runtime.getRuntime().maxMemory() / 8);

            Log.d(LOG_TAG, "bitmapForURL  lruSize : " + lruSize);

            mBitmapByUrlCache = new LruCache<String, Bitmap>(lruSize) {
                @Override
                protected int sizeOf(String key, Bitmap bitmap) {
                    return bitmap.getRowBytes() * bitmap.getHeight(); // size in bytes
                }
            };
        }

        // the image is downloading in background
        if (null != getMediaDownloadWorkerTask(url)) {
            return null;
        }

        // the url is invalid
        if (isMediaUrlUnreachable(url)) {
            return null;
        }

        synchronized (mSyncObject) {
            bitmap = mBitmapByUrlCache.get(url);
        }

        // check if the image has not been saved in file system
        if ((null == bitmap) && (null != baseFile)) {
            String filename = null;

            // the url is a file one
            if (url.startsWith("file:")) {
                // try to parse it
                try {
                    Uri uri = Uri.parse(url);
                    filename = uri.getPath();

                } catch (Exception e) {
                    Log.e(LOG_TAG, "bitmapForURL #1 : " + e.getLocalizedMessage());
                }

                // cannot extract the filename -> sorry
                if (null == filename) {
                    return null;
                }
            }

            // not a valid file name
            if (null == filename) {
                filename = buildFileName(url, mimeType);
            }

            try {
                File file = filename.startsWith(File.separator) ? new File(filename)
                        : new File(baseFile, filename);

                if (!file.exists()) {
                    Log.d(LOG_TAG, "bitmapForURL() : " + filename + " does not exist");
                    return null;
                }

                InputStream fis = new FileInputStream(file);

                // read the metadata
                if (Integer.MAX_VALUE == rotation) {
                    rotation = ImageUtils.getRotationAngleForBitmap(context, Uri.fromFile(file));
                }

                if (null != fis) {
                    BitmapFactory.Options options = new BitmapFactory.Options();
                    options.inPreferredConfig = Bitmap.Config.ARGB_8888;

                    try {
                        bitmap = BitmapFactory.decodeStream(fis, null, options);
                    } catch (OutOfMemoryError error) {
                        System.gc();
                        Log.e(LOG_TAG, "bitmapForURL() : Out of memory 1 " + error);
                    }

                    //  try again
                    if (null == bitmap) {
                        try {
                            bitmap = BitmapFactory.decodeStream(fis, null, options);
                        } catch (OutOfMemoryError error) {
                            Log.e(LOG_TAG, "bitmapForURL() Out of memory 2" + error);
                        }
                    }

                    if (null != bitmap) {
                        synchronized (mSyncObject) {
                            if (0 != rotation) {
                                try {
                                    android.graphics.Matrix bitmapMatrix = new android.graphics.Matrix();
                                    bitmapMatrix.postRotate(rotation);

                                    Bitmap transformedBitmap = Bitmap.createBitmap(bitmap, 0, 0,
                                            bitmap.getWidth(), bitmap.getHeight(), bitmapMatrix, false);
                                    bitmap.recycle();
                                    bitmap = transformedBitmap;
                                } catch (OutOfMemoryError ex) {
                                    Log.e(LOG_TAG, "bitmapForURL rotation error : " + ex.getLocalizedMessage());
                                }
                            }

                            // cache only small images
                            // caching large images does not make sense
                            // it would replace small ones.
                            // let assume that the application must be faster when showing the chat history.
                            if ((bitmap.getWidth() < 1000) && (bitmap.getHeight() < 1000)) {
                                mBitmapByUrlCache.put(url, bitmap);
                            }
                        }
                    }

                    fis.close();
                }

            } catch (FileNotFoundException e) {
                Log.d(LOG_TAG, "bitmapForURL() : " + filename + " does not exist");
            } catch (Exception e) {
                Log.e(LOG_TAG, "bitmapForURL() " + e);

            }
        }
    }

    return bitmap;
}

From source file:com.grarak.kerneladiutor.views.recyclerview.overallstatistics.FrequencyButtonView.java

@Override
public void onCreateView(View view) {
    AppCompatImageButton refresh = (AppCompatImageButton) view.findViewById(R.id.frequency_refresh);
    AppCompatImageButton reset = (AppCompatImageButton) view.findViewById(R.id.frequency_reset);
    AppCompatImageButton restore = (AppCompatImageButton) view.findViewById(R.id.frequency_restore);

    if (mRefreshImage == null) {
        mRefreshImage = ViewUtils//from   w w w  .j ava  2 s .  c o m
                .drawableToBitmap(ContextCompat.getDrawable(view.getContext(), R.drawable.ic_refresh));
    }
    refresh.setImageBitmap(mRefreshImage);

    if (mResetImage == null) {
        Matrix matrix = new Matrix();
        matrix.postRotate(180);
        matrix.preScale(-1.0f, 1.0f);
        mResetImage = Bitmap.createBitmap(mRefreshImage, 0, 0, mRefreshImage.getWidth(),
                mRefreshImage.getHeight(), matrix, true);
    }
    reset.setImageBitmap(mResetImage);

    refresh.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            rotate(v, false);
            if (mRefreshListener != null) {
                mRefreshListener.onClick(v);
            }
        }
    });
    reset.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            rotate(v, true);
            if (mResetListener != null) {
                mResetListener.onClick(v);
            }
        }
    });
    restore.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            rotate(v, true);
            if (mRestoreListener != null) {
                mRestoreListener.onClick(v);
            }
        }
    });

    setFullSpan(true);
    super.onCreateView(view);
}

From source file:com.socialize.util.ImageUtils.java

public byte[] scaleImage(Context context, Uri photoUri) throws IOException {

    BitmapFactory.Options dbo = new BitmapFactory.Options();
    dbo.inJustDecodeBounds = true;//from w  ww .j av  a 2s .  c  o m
    InputStream is = getStreamToUri(context, photoUri);
    BitmapFactory.decodeStream(is, null, dbo);
    is.close();

    int rotatedWidth, rotatedHeight;
    int orientation = getOrientation(context, photoUri);

    if (orientation == 90 || orientation == 270) {
        rotatedWidth = dbo.outHeight;
        rotatedHeight = dbo.outWidth;
    } else {
        rotatedWidth = dbo.outWidth;
        rotatedHeight = dbo.outHeight;
    }

    Bitmap bitmap;
    is = getStreamToUri(context, photoUri);
    if (rotatedWidth > MAX_IMAGE_DIMENSION || rotatedHeight > MAX_IMAGE_DIMENSION) {
        float widthRatio = ((float) rotatedWidth) / ((float) MAX_IMAGE_DIMENSION);
        float heightRatio = ((float) rotatedHeight) / ((float) MAX_IMAGE_DIMENSION);
        float maxRatio = Math.max(widthRatio, heightRatio);

        // Create the bitmap from file
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inSampleSize = (int) maxRatio;
        bitmap = BitmapFactory.decodeStream(is, null, options);
    } else {
        bitmap = BitmapFactory.decodeStream(is);
    }
    is.close();

    /*
     * if the orientation is not 0 (or -1, which means we don't know), we
     * have to do a rotation.
     */
    if (orientation > 0) {
        Matrix matrix = new Matrix();
        matrix.postRotate(orientation);

        bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
    }

    String type = "image/png";
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    if (type.equals("image/png")) {
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
    } else if (type.equals("image/jpg") || type.equals("image/jpeg")) {
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
    }
    byte[] bMapArray = baos.toByteArray();
    baos.close();
    return bMapArray;
}