Example usage for android.graphics Matrix preRotate

List of usage examples for android.graphics Matrix preRotate

Introduction

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

Prototype

public boolean preRotate(float degrees) 

Source Link

Document

Preconcats the matrix with the specified rotation.

Usage

From source file:com.silentcircle.common.util.ViewUtil.java

/**
 * Finds JPEG image rotation flags from exif and returns matrix to be used to rotate image.
 *
 * @param fileName JPEG image file name.
 *
 * @return Matrix to use in image rotate transformation or null if parsing failed.
 *///w w w  . ja v  a  2  s .  c  o m
public static Matrix getRotationMatrixFromExif(final String fileName) {
    Matrix matrix = null;
    try {
        ExifInterface exif = new ExifInterface(fileName);
        int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
        int rotate = 0;

        switch (orientation) {
        case ExifInterface.ORIENTATION_ROTATE_90:
            rotate = ROTATE_90;
            break;

        case ExifInterface.ORIENTATION_ROTATE_180:
            rotate = ROTATE_180;
            break;

        case ExifInterface.ORIENTATION_ROTATE_270:
            rotate = ROTATE_270;
            break;
        }

        if (rotate != 0) {
            matrix = new Matrix();
            matrix.preRotate(rotate);
        }
    } catch (IOException e) {
        Log.i(TAG, "Failed to determine image flags from file " + fileName);
    }
    return matrix;
}

From source file:com.zhongsou.souyue.ui.webview.CustomWebChromeClient.java

private Uri afterOpenCamera() {
    String picPath = null;//from  ww  w. j a va  2  s  . c  om
    if (imageFileUri != null) {
        picPath = Utils.getPicPathFromUri(imageFileUri, mContext);
        int degree = 0;
        if (!StringUtils.isEmpty(picPath))
            degree = ImageUtil.readPictureDegree(picPath);
        Matrix matrix = new Matrix();
        if (degree != 0) {// 
            matrix.preRotate(degree);
        }
        return Uri.fromFile(new File(picPath));
    }
    return null;
}

From source file:com.dastardlylabs.ti.ocrdroid.OcrdroidModule.java

@Kroll.method
@SuppressWarnings("rawtypes")
public String ocr(HashMap _config) {
    assert (_config != null);
    String dataParentPath = getTessDataDirectory().getAbsolutePath(), //= (String) _config.get("dataParent"),
            imagePath = StorageHelper.stripFileUri((String) _config.get("image")),
            language = (String) _config.get("lang");

    try {/*  w  w  w . j av a2s .  c  om*/
        if (!tessDataExists())
            unpackTessData();
    } catch (Exception e) {
        // catch failure and bubble up failure message and options
        // else continue.
    }

    Log.d(LCAT, "ocr called");
    Log.d(LCAT, "Setting parent directory for tessdata as DATAPATH".replace("DATAPATH",
            dataParentPath /*DATA_PATH*/));

    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inSampleSize = 2;
    options.inPreferredConfig = Bitmap.Config.ARGB_8888;

    Bitmap bitmap = BitmapFactory.decodeFile(imagePath, options);
    //bitmap.getConfig()

    try {
        ExifInterface exif = new ExifInterface(imagePath);
        int exifOrientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                ExifInterface.ORIENTATION_NORMAL);

        Log.v(LCAT, "Orient: " + exifOrientation);

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

        Log.v(LCAT, "Rotation: " + rotate);

        if (rotate != 0) {

            // Getting width & height of the given image.
            int w = bitmap.getWidth();
            int h = bitmap.getHeight();

            // Setting pre rotate
            Matrix mtx = new Matrix();
            mtx.preRotate(rotate);

            // Rotating Bitmap
            bitmap = Bitmap.createBitmap(bitmap, 0, 0, w, h, mtx, false);
            // tesseract req. ARGB_8888
            bitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true);
        }

    } catch (IOException e) {
        Log.e(LCAT, "Rotate or coversion failed: " + e.toString());
    }

    //        ImageView iv = (ImageView) findViewById(R.id.image);
    //        iv.setImageBitmap(bitmap);
    //        iv.setVisibility(View.VISIBLE);

    Log.v(LCAT, "Before baseApi");

    TessBaseAPI baseApi = new TessBaseAPI();
    baseApi.setDebug(true);
    baseApi.init(dataParentPath /*DATA_PATH*/, language);
    baseApi.setImage(bitmap);
    //baseApi.get
    String recognizedText = baseApi.getUTF8Text();
    baseApi.end();

    Log.v(LCAT, "OCR Result: " + recognizedText);

    // clean up and show
    if (language.equalsIgnoreCase("eng")) {
        recognizedText = recognizedText.replaceAll("[^a-zA-Z0-9]+", " ");
    }

    return recognizedText.trim();
}

From source file:com.plugin.camera.ForegroundCameraLauncher.java

/**
 * Called when the camera view exits.//  w ww  . ja v  a  2  s . c  om
 *
 * @param requestCode
 *            The request code originally supplied to
 *            startActivityForResult(), allowing you to identify who this
 *            result came from.
 * @param resultCode
 *            The integer result code returned by the child activity through
 *            its setResult().
 * @param intent
 *            An Intent, which can return result data to the caller (various
 *            data can be attached to Intent "extras").
 */
public void onActivityResult(int requestCode, int resultCode, Intent intent) {

    // If image available
    if (resultCode == Activity.RESULT_OK) {
        try {
            // Create an ExifHelper to save the exif data that is lost
            // during compression
            ExifHelper exif = new ExifHelper();
            exif.createInFile(
                    getTempDirectoryPath(this.cordova.getActivity().getApplicationContext()) + "/Pic.jpg");
            exif.readExifData();

            // Read in bitmap of captured image
            Bitmap bitmap;
            try {
                bitmap = android.provider.MediaStore.Images.Media
                        .getBitmap(this.cordova.getActivity().getContentResolver(), imageUri);
            } catch (FileNotFoundException e) {
                Uri uri = intent.getData();
                android.content.ContentResolver resolver = this.cordova.getActivity().getContentResolver();
                bitmap = android.graphics.BitmapFactory.decodeStream(resolver.openInputStream(uri));
            }

            bitmap = scaleBitmap(bitmap);

            // Create entry in media store for image
            // (Don't use insertImage() because it uses default compression
            // setting of 50 - no way to change it)
            ContentValues values = new ContentValues();
            values.put(android.provider.MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
            Uri uri = null;
            try {
                uri = this.cordova.getActivity().getContentResolver()
                        .insert(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            } catch (UnsupportedOperationException e) {
                LOG.d(LOG_TAG, "Can't write to external media storage.");
                try {
                    uri = this.cordova.getActivity().getContentResolver()
                            .insert(android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI, values);
                } catch (UnsupportedOperationException ex) {
                    LOG.d(LOG_TAG, "Can't write to internal media storage.");
                    this.failPicture("Error capturing image - no media storage found.");
                    return;
                }
            }
            //This if block is added to the plugin to solve the issue which was saving portrait images in landscape with -90 degree rotetion
            if (intent.getBooleanExtra("portrait", false)) {
                Matrix matrix = new Matrix();
                matrix.preRotate(90);
                try {
                    bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix,
                            true);
                } catch (Exception e) {
                    bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth() / 2, bitmap.getHeight() / 2,
                            matrix, true);
                    e.printStackTrace();
                }
            }

            // Add compressed version of captured image to returned media
            // store Uri
            OutputStream os = this.cordova.getActivity().getContentResolver().openOutputStream(uri);
            bitmap.compress(Bitmap.CompressFormat.JPEG, this.mQuality, os);
            os.close();

            // Restore exif data to file
            exif.createOutFile(getRealPathFromURI(uri, this.cordova));
            exif.writeExifData();

            // Send Uri back to JavaScript for viewing image
            this.callbackContext.success(getRealPathFromURI(uri, this.cordova));

            bitmap.recycle();
            bitmap = null;
            System.gc();

            checkForDuplicateImage();
        } catch (IOException e) {
            e.printStackTrace();
            this.failPicture("Error capturing image.");
        }
    }

    // If cancelled
    else if (resultCode == Activity.RESULT_CANCELED) {
        this.failPicture("Camera cancelled.");
    }

    // If something else
    else {
        this.failPicture("Did not complete!");
    }
}

From source file:com.liwn.zzl.markbit.DrawOptionsMenuActivity.java

private Uri rotateNormal(Uri uri) throws IOException {
    ExifInterface exif = new ExifInterface(uri.getPath());
    int rotation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
    int rotationInDegrees = exifToDegrees(rotation);
    Matrix matrix = new Matrix();
    if (rotation != 0) {
        matrix.preRotate(rotationInDegrees);
    }/*from  w w w .j  a  v  a2s.c o m*/
    Bitmap srcBitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
    Bitmap adjustedBitmap = Bitmap.createBitmap(srcBitmap, 0, 0, MarkBitApplication.BIT_LCD_WIDTH,
            MarkBitApplication.BIT_LCD_HEIGHT, matrix, true);
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    adjustedBitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
    String path = MediaStore.Images.Media.insertImage(this.getContentResolver(), adjustedBitmap, "Title", null);
    return Uri.parse(path);
}

From source file:edu.stanford.mobisocial.dungbeetle.ImageViewerActivity.java

@Override
public void onResume() {
    super.onResume();
    if (mIntent.hasExtra("image_url")) {
        String url = mIntent.getStringExtra("image_url");
        ((App) getApplication()).objectImages.lazyLoadImage(url.hashCode(), Uri.parse(url), im);
        bitmap = mgr.getBitmap(url.hashCode(), url);
    } else if (mIntent.hasExtra("b64Bytes")) {
        String b64Bytes = mIntent.getStringExtra("b64Bytes");
        ((App) getApplication()).objectImages.lazyLoadImage(b64Bytes.hashCode(), b64Bytes, im);
        bitmap = mgr.getBitmapB64(b64Bytes.hashCode(), b64Bytes);
    } else if (mIntent.hasExtra("bytes")) {
        byte[] bytes = mIntent.getByteArrayExtra("bytes");
        ((App) getApplication()).objectImages.lazyLoadImage(bytes.hashCode(), bytes, im);
        bitmap = mgr.getBitmap(bytes.hashCode(), bytes);
    } else if (mIntent.hasExtra("obj")) {
        try {/* www  .ja v a  2s  .  c  om*/
            final JSONObject content = new JSONObject(mIntent.getStringExtra("obj"));
            byte[] bytes = FastBase64.decode(content.optString(PictureObj.DATA));
            ((App) getApplication()).objectImages.lazyLoadImage(bytes.hashCode(), bytes, im);
            bitmap = mgr.getBitmap(bytes.hashCode(), bytes);
        } catch (JSONException e) {
        }
    }

    if (mIntent.hasExtra("objHash")) {
        if (!ContentCorral.CONTENT_CORRAL_ENABLED) {
            return;
        }

        long objHash = mIntent.getLongExtra("objHash", -1);
        final DbObj obj = App.instance().getMusubi().objForHash(objHash);
        final JSONObject json = obj.getJson();
        if (json.has(CorralClient.OBJ_LOCAL_URI)) {
            // TODO: this is a proof-of-concept.
            new Thread() {
                public void run() {
                    try {
                        if (!mCorralClient.fileAvailableLocally(obj)) {
                            //toast("Trying to go HD...");
                        }
                        // Log.d(TAG, "Trying to go HD...");
                        final Uri fileUri = mCorralClient.fetchContent(obj);
                        if (fileUri == null) {
                            try {
                                Log.d(TAG, "Failed to go HD for " + json.getString(CorralClient.OBJ_LOCAL_URI));
                            } catch (JSONException e) {
                                Log.d(TAG, "Failed to go HD for " + json);
                            }
                            return;
                        }
                        // Log.d(TAG, "Opening HD file " + fileUri);

                        InputStream is = getContentResolver().openInputStream(fileUri);
                        BitmapFactory.Options options = new BitmapFactory.Options();
                        options.inSampleSize = 4;

                        Matrix matrix = new Matrix();
                        float rotation = PhotoTaker.rotationForImage(ImageViewerActivity.this, fileUri);
                        if (rotation != 0f) {
                            matrix.preRotate(rotation);
                        }
                        bitmap = BitmapFactory.decodeStream(is, null, options);

                        int width = bitmap.getWidth();
                        int height = bitmap.getHeight();
                        bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                im.setImageBitmap(bitmap);
                            }
                        });
                    } catch (IOException e) {
                        // toast("Failed to go HD");
                        Log.e(TAG, "Failed to get hd content", e);
                        // continue
                    }
                };
            }.start();
        }
    }
}

From source file:mobisocial.musubi.util.UriImage.java

/**
 * Returns the bytes for this UriImage. If the uri for the image is remote,
 * then this code must not be run on the main thread.
 *///from   w w  w. j  a v a  2 s  .c  o  m
public byte[] getResizedImageData(int widthLimit, int heightLimit, int byteLimit, boolean square)
        throws IOException {
    if (!mDecodedBounds) {
        decodeBoundsInfo();
        mDecodedBounds = true;
    }
    InputStream input = null;
    try {
        int inDensity = 0;
        int targetDensity = 0;
        BitmapFactory.Options read_options = new BitmapFactory.Options();
        read_options.inJustDecodeBounds = true;
        input = openInputStream(mUri);
        BitmapFactory.decodeStream(input, null, read_options);
        if (read_options.outWidth > widthLimit || read_options.outHeight > heightLimit) {
            //we need to scale
            if (read_options.outWidth / widthLimit > read_options.outHeight / heightLimit) {
                //width is the large edge
                if (read_options.outWidth * heightLimit > widthLimit * read_options.outHeight) {
                    //incoming image is wider than target
                    inDensity = read_options.outWidth;
                    targetDensity = widthLimit;
                } else {
                    //incoming image is taller than target
                    inDensity = read_options.outHeight;
                    targetDensity = heightLimit;

                }
            } else {
                //height is the long edge, swap the limits
                if (read_options.outWidth * widthLimit > heightLimit * read_options.outHeight) {
                    //incoming image is wider than target
                    inDensity = read_options.outWidth;
                    targetDensity = heightLimit;
                } else {
                    //incoming image is taller than target
                    inDensity = read_options.outHeight;
                    targetDensity = widthLimit;

                }
            }
        } else {
            //no scale
            if (read_options.outWidth > read_options.outHeight) {
                inDensity = targetDensity = read_options.outWidth;
            } else {
                inDensity = targetDensity = read_options.outHeight;
            }
        }

        if (Log.isLoggable(TAG, Log.VERBOSE)) {
            Log.v(TAG,
                    "getResizedImageData: wlimit=" + widthLimit + ", hlimit=" + heightLimit + ", sizeLimit="
                            + byteLimit + ", mWidth=" + mWidth + ", mHeight=" + mHeight + ", initialRatio="
                            + targetDensity + "/" + inDensity);
        }

        ByteArrayOutputStream os = null;
        int attempts = 1;

        int lowMemoryReduce = 1;
        do {
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inDensity = inDensity;
            options.inSampleSize = lowMemoryReduce;
            options.inScaled = lowMemoryReduce == 1;
            options.inTargetDensity = targetDensity;
            //no purgeable because we are only trying to resave this
            if (input != null)
                input.close();
            input = openInputStream(mUri);
            int quality = IMAGE_COMPRESSION_QUALITY;
            try {
                Bitmap b = BitmapFactory.decodeStream(input, null, options);
                if (b == null) {
                    return null;
                }
                if (options.outWidth > widthLimit + 1 || options.outHeight > heightLimit + 1) {
                    // The decoder does not support the inSampleSize option.
                    // Scale the bitmap using Bitmap library.
                    int scaledWidth;
                    int scaledHeight;
                    scaledWidth = options.outWidth * targetDensity / inDensity;
                    scaledHeight = options.outHeight * targetDensity / inDensity;

                    if (Log.isLoggable(TAG, Log.VERBOSE)) {
                        Log.v(TAG, "getResizedImageData: retry scaling using " + "Bitmap.createScaledBitmap: w="
                                + scaledWidth + ", h=" + scaledHeight);
                    }

                    if (square) {
                        int w = b.getWidth();
                        int h = b.getHeight();
                        int dim = Math.min(w, h);
                        b = Bitmap.createBitmap(b, (w - dim) / 2, (h - dim) / 2, dim, dim);
                        scaledWidth = dim;
                        scaledHeight = dim;
                    }
                    Bitmap b2 = Bitmap.createScaledBitmap(b, scaledWidth, scaledHeight, false);
                    b.recycle();
                    b = b2;
                    if (b == null) {
                        return null;
                    }
                }

                Matrix matrix = new Matrix();
                if (mRotation != 0f) {
                    matrix.preRotate(mRotation);
                }

                Bitmap old = b;
                b = Bitmap.createBitmap(old, 0, 0, old.getWidth(), old.getHeight(), matrix, true);

                // Compress the image into a JPG. Start with MessageUtils.IMAGE_COMPRESSION_QUALITY.
                // In case that the image byte size is still too large reduce the quality in
                // proportion to the desired byte size. Should the quality fall below
                // MINIMUM_IMAGE_COMPRESSION_QUALITY skip a compression attempt and we will enter
                // the next round with a smaller image to start with.
                os = new ByteArrayOutputStream();
                b.compress(CompressFormat.JPEG, quality, os);
                int jpgFileSize = os.size();
                if (jpgFileSize > byteLimit) {
                    int reducedQuality = quality * byteLimit / jpgFileSize;
                    //always try to squish it before computing the new size
                    if (reducedQuality < MINIMUM_IMAGE_COMPRESSION_QUALITY) {
                        reducedQuality = MINIMUM_IMAGE_COMPRESSION_QUALITY;
                    }
                    quality = reducedQuality;

                    if (Log.isLoggable(TAG, Log.VERBOSE)) {
                        Log.v(TAG, "getResizedImageData: compress(2) w/ quality=" + quality);
                    }

                    os = new ByteArrayOutputStream();
                    b.compress(CompressFormat.JPEG, quality, os);
                }
                b.recycle(); // done with the bitmap, release the memory
            } catch (java.lang.OutOfMemoryError e) {
                Log.w(TAG, "getResizedImageData - image too big (OutOfMemoryError), will try "
                        + " with smaller scale factor, cur scale factor", e);
                lowMemoryReduce *= 2;
                // fall through and keep trying with a smaller scale factor.
            }
            if (true || Log.isLoggable(TAG, Log.VERBOSE)) {
                Log.v(TAG,
                        "attempt=" + attempts + " size=" + (os == null ? 0 : os.size()) + " width="
                                + options.outWidth + " height=" + options.outHeight + " Ratio=" + targetDensity
                                + "/" + inDensity + " quality=" + quality);
            }
            //move halfway to the target
            targetDensity = (os == null) ? (int) (targetDensity * .8)
                    : (targetDensity * byteLimit / os.size() + targetDensity) / 2;
            attempts++;
        } while ((os == null || os.size() > byteLimit) && attempts < NUMBER_OF_RESIZE_ATTEMPTS);

        return os == null ? null : os.toByteArray();
    } catch (Throwable t) {
        Log.e(TAG, t.getMessage(), t);
        return null;
    } finally {
        if (input != null) {
            try {
                input.close();
            } catch (IOException e) {
                Log.e(TAG, e.getMessage(), e);
            }
        }
    }
}

From source file:mobisocial.noteshere.util.UriImage.java

/**
 * Returns the bytes for this UriImage. If the uri for the image is remote,
 * then this code must not be run on the main thread.
 *//*w  w  w  . j a v  a2 s .  c o m*/
public byte[] getResizedImageData(int widthLimit, int heightLimit, int byteLimit, boolean square)
        throws IOException {
    if (!mDecodedBounds) {
        decodeBoundsInfo();
        mDecodedBounds = true;
    }
    InputStream input = null;
    try {
        int inDensity = 0;
        int targetDensity = 0;
        BitmapFactory.Options read_options = new BitmapFactory.Options();
        read_options.inJustDecodeBounds = true;
        input = openInputStream(mUri);
        BitmapFactory.decodeStream(input, null, read_options);
        if (read_options.outWidth > widthLimit || read_options.outHeight > heightLimit) {
            //we need to scale
            if (read_options.outWidth / widthLimit > read_options.outHeight / heightLimit) {
                //width is the large edge
                if (read_options.outWidth * heightLimit > widthLimit * read_options.outHeight) {
                    //incoming image is wider than target
                    inDensity = read_options.outWidth;
                    targetDensity = widthLimit;
                } else {
                    //incoming image is taller than target
                    inDensity = read_options.outHeight;
                    targetDensity = heightLimit;

                }
            } else {
                //height is the long edge, swap the limits
                if (read_options.outWidth * widthLimit > heightLimit * read_options.outHeight) {
                    //incoming image is wider than target
                    inDensity = read_options.outWidth;
                    targetDensity = heightLimit;
                } else {
                    //incoming image is taller than target
                    inDensity = read_options.outHeight;
                    targetDensity = widthLimit;

                }
            }
        } else {
            //no scale
            if (read_options.outWidth > read_options.outHeight) {
                inDensity = targetDensity = read_options.outWidth;
            } else {
                inDensity = targetDensity = read_options.outHeight;
            }
        }

        if (Log.isLoggable(TAG, Log.VERBOSE)) {
            Log.v(TAG,
                    "getResizedImageData: wlimit=" + widthLimit + ", hlimit=" + heightLimit + ", sizeLimit="
                            + byteLimit + ", mWidth=" + mWidth + ", mHeight=" + mHeight + ", initialRatio="
                            + targetDensity + "/" + inDensity);
        }

        ByteArrayOutputStream os = null;
        int attempts = 1;

        int lowMemoryReduce = 1;
        do {
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inDensity = inDensity;
            options.inSampleSize = lowMemoryReduce;
            options.inScaled = lowMemoryReduce == 1;
            options.inTargetDensity = targetDensity;
            //no purgeable because we are only trying to resave this
            if (input != null)
                input.close();
            input = openInputStream(mUri);
            int quality = IMAGE_COMPRESSION_QUALITY;
            try {
                Bitmap b = BitmapFactory.decodeStream(input, null, options);
                if (b == null) {
                    return null;
                }
                if (options.outWidth > widthLimit + 1 || options.outHeight > heightLimit + 1) {
                    // The decoder does not support the inSampleSize option.
                    // Scale the bitmap using Bitmap library.
                    int scaledWidth;
                    int scaledHeight;
                    scaledWidth = options.outWidth * targetDensity / inDensity;
                    scaledHeight = options.outHeight * targetDensity / inDensity;

                    if (Log.isLoggable(TAG, Log.VERBOSE)) {
                        Log.v(TAG, "getResizedImageData: retry scaling using " + "Bitmap.createScaledBitmap: w="
                                + scaledWidth + ", h=" + scaledHeight);
                    }

                    if (square) {
                        int w = b.getWidth();
                        int h = b.getHeight();
                        int dim = Math.min(w, h);
                        b = Bitmap.createBitmap(b, (w - dim) / 2, (h - dim) / 2, dim, dim);
                        scaledWidth = dim;
                        scaledHeight = dim;
                    }
                    Bitmap b2 = Bitmap.createScaledBitmap(b, scaledWidth, scaledHeight, false);
                    b.recycle();
                    b = b2;
                    if (b == null) {
                        return null;
                    }
                }

                Matrix matrix = new Matrix();
                if (mRotation != 0f) {
                    matrix.preRotate(mRotation);
                }

                Bitmap old = b;
                b = Bitmap.createBitmap(old, 0, 0, old.getWidth(), old.getHeight(), matrix, true);

                // Compress the image into a JPG. Start with MessageUtils.IMAGE_COMPRESSION_QUALITY.
                // In case that the image byte size is still too large reduce the quality in
                // proportion to the desired byte size. Should the quality fall below
                // MINIMUM_IMAGE_COMPRESSION_QUALITY skip a compression attempt and we will enter
                // the next round with a smaller image to start with.
                os = new ByteArrayOutputStream();
                b.compress(CompressFormat.JPEG, quality, os);
                int jpgFileSize = os.size();
                if (jpgFileSize > byteLimit) {
                    int reducedQuality = quality * byteLimit / jpgFileSize;
                    //always try to squish it before computing the new size
                    if (reducedQuality < MINIMUM_IMAGE_COMPRESSION_QUALITY) {
                        reducedQuality = MINIMUM_IMAGE_COMPRESSION_QUALITY;
                    }
                    quality = reducedQuality;

                    if (Log.isLoggable(TAG, Log.VERBOSE)) {
                        Log.v(TAG, "getResizedImageData: compress(2) w/ quality=" + quality);
                    }

                    os = new ByteArrayOutputStream();
                    b.compress(CompressFormat.JPEG, quality, os);
                }
                b.recycle(); // done with the bitmap, release the memory
            } catch (java.lang.OutOfMemoryError e) {
                Log.w(TAG, "getResizedImageData - image too big (OutOfMemoryError), will try "
                        + " with smaller scale factor, cur scale factor", e);
                lowMemoryReduce *= 2;
                // fall through and keep trying with a smaller scale factor.
            }
            Log.v(TAG,
                    "attempt=" + attempts + " size=" + (os == null ? 0 : os.size()) + " width="
                            + options.outWidth + " height=" + options.outHeight + " Ratio=" + targetDensity
                            + "/" + inDensity + " quality=" + quality);
            //move halfway to the target
            targetDensity = (os == null) ? (int) (targetDensity * .8)
                    : (targetDensity * byteLimit / os.size() + targetDensity) / 2;
            attempts++;
        } while ((os == null || os.size() > byteLimit) && attempts < NUMBER_OF_RESIZE_ATTEMPTS);

        return os == null ? null : os.toByteArray();
    } catch (Throwable t) {
        Log.e(TAG, t.getMessage(), t);
        return null;
    } finally {
        if (input != null) {
            try {
                input.close();
            } catch (IOException e) {
                Log.e(TAG, e.getMessage(), e);
            }
        }
    }
}

From source file:de.tlabs.ssr.g1.client.SourcesView.java

private void recalculateViewportTransformation(Matrix dstMatrix, float centerRotation, float scaling,
        float[] translation) {
    dstMatrix.reset();//from w  ww  .j av a  2s  . c  o  m
    // translate to center
    dstMatrix.preTranslate((float) getWidth() / 2.0f, (float) getHeight() / 2.0f);
    // rotate around center
    dstMatrix.preRotate(-centerRotation); // negative rotation, because y axis not yet inverted
    // translate
    dstMatrix.preTranslate(translation[0], translation[1]);
    // scale and invert y axis
    dstMatrix.preScale(scaling, -scaling);
    // rotate to look north always (instead of east)
    dstMatrix.preRotate(90.0f);
}

From source file:com.ferdi2005.secondgram.AndroidUtilities.java

public static void setRectToRect(Matrix matrix, RectF src, RectF dst, int rotation, Matrix.ScaleToFit align) {
    float tx, sx;
    float ty, sy;
    if (rotation == 90 || rotation == 270) {
        sx = dst.height() / src.width();
        sy = dst.width() / src.height();
    } else {/* w  w  w .j  a  v a  2 s  . c om*/
        sx = dst.width() / src.width();
        sy = dst.height() / src.height();
    }
    if (align != Matrix.ScaleToFit.FILL) {
        if (sx > sy) {
            sx = sy;
        } else {
            sy = sx;
        }
    }
    tx = -src.left * sx;
    ty = -src.top * sy;

    matrix.setTranslate(dst.left, dst.top);
    if (rotation == 90) {
        matrix.preRotate(90);
        matrix.preTranslate(0, -dst.width());
    } else if (rotation == 180) {
        matrix.preRotate(180);
        matrix.preTranslate(-dst.width(), -dst.height());
    } else if (rotation == 270) {
        matrix.preRotate(270);
        matrix.preTranslate(-dst.height(), 0);
    }

    matrix.preScale(sx, sy);
    matrix.preTranslate(tx, ty);
}