Example usage for android.graphics Matrix Matrix

List of usage examples for android.graphics Matrix Matrix

Introduction

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

Prototype

public Matrix() 

Source Link

Document

Create an identity matrix

Usage

From source file:ch.ethz.dcg.jukefox.manager.libraryimport.AndroidAlbumCoverFetcherThread.java

/**
 * Resize a bitmap to targetResxtargetRex pixels
 * //from  w  ww.jav a2 s.c  om
 * @param bm
 *            bitmap to resize
 * @param targetRes
 *            height and width of the new bitmap
 * @return
 */
private Bitmap resizeBitmap(Bitmap bm, int targetRes) {
    // scale the image for opengl
    int width = bm.getWidth();
    int height = bm.getHeight();
    float scaleWidth = (float) targetRes / width;
    float scaleHeight = (float) targetRes / height;

    // scale matrix
    Matrix matrix = new Matrix();
    // resize the bit map
    matrix.postScale(scaleWidth, scaleHeight);

    // recreate the new Bitmap
    Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, true);
    if (resizedBitmap == null) {
        Log.w(TAG, "ResizedBitmap is null");
    }
    return resizedBitmap;
}

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

/**
 * /*ww w .j av a 2 s .  c  om*/
 */
public static Bitmap rotateImage(Bitmap bmp) {

    if (bmp == null)
        return bmp;

    int width = bmp.getWidth();
    int height = bmp.getHeight();
    float aspectRatio = ((float) height) / width;

    if (aspectRatio > 1) {
        // no need to rotate the image
        return bmp;
    }

    Matrix matrix = new Matrix();
    matrix.postRotate(90);
    Bitmap rotatedBitmap = null;
    try {
        rotatedBitmap = Bitmap.createBitmap(bmp, 0, 0, width, height, matrix, false);
    } catch (OutOfMemoryError e) {
    }
    return rotatedBitmap;
}

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  ww.j a v a  2  s. co  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: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;
    }//  ww w .  j a v  a2s .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:biz.varkon.shelvesom.util.ImageUtilities.java

private static Bitmap createScaledBitmap(Bitmap src, int dstWidth, int dstHeight, float offset,
        boolean clipShadow, Paint paint) {
    Matrix m;//w w w . ja va2  s . c o  m
    synchronized (Bitmap.class) {
        m = sScaleMatrix;
        sScaleMatrix = null;
    }

    if (m == null) {
        m = new Matrix();
    }

    final int width = src.getWidth();
    final int height = src.getHeight();
    final float sx = dstWidth / (float) width;
    final float sy = dstHeight / (float) height;
    m.setScale(sx, sy);

    Bitmap b = createBitmap(src, 0, 0, width, height, m, offset, clipShadow, paint);

    synchronized (Bitmap.class) {
        sScaleMatrix = m;
    }

    src.recycle();
    return b;
}

From source file:com.larvalabs.svgandroid.SVGParser.java

private static Matrix parseTransform(String s) {
    //Log.d(TAG, s);
    Matrix matrix = new Matrix();
    while (true) {
        parseTransformItem(s, matrix);/*from   www  .  ja v a  2 s. c  o  m*/
        // Log.i(TAG, "Transformed: (" + s + ") " + matrix);
        int rparen = s.indexOf(")");
        if (rparen > 0 && s.length() > rparen + 1) {
            s = s.substring(rparen + 1).replaceFirst("[\\s,]*", "");
        } else {
            break;
        }
    }
    //Log.d(TAG, matrix.toShortString());
    return matrix;
}

From source file:android.support.transition.ChangeTransform.java

private ObjectAnimator createTransformAnimator(TransitionValues startValues, TransitionValues endValues,
        final boolean handleParentChange) {
    Matrix startMatrix = (Matrix) startValues.values.get(PROPNAME_MATRIX);
    Matrix endMatrix = (Matrix) endValues.values.get(PROPNAME_MATRIX);

    if (startMatrix == null) {
        startMatrix = MatrixUtils.IDENTITY_MATRIX;
    }//w w w  . j av  a  2  s  .  co  m

    if (endMatrix == null) {
        endMatrix = MatrixUtils.IDENTITY_MATRIX;
    }

    if (startMatrix.equals(endMatrix)) {
        return null;
    }

    final Transforms transforms = (Transforms) endValues.values.get(PROPNAME_TRANSFORMS);

    // clear the transform properties so that we can use the animation matrix instead
    final View view = endValues.view;
    setIdentityTransforms(view);

    final float[] startMatrixValues = new float[9];
    startMatrix.getValues(startMatrixValues);
    final float[] endMatrixValues = new float[9];
    endMatrix.getValues(endMatrixValues);
    final PathAnimatorMatrix pathAnimatorMatrix = new PathAnimatorMatrix(view, startMatrixValues);

    PropertyValuesHolder valuesProperty = PropertyValuesHolder.ofObject(NON_TRANSLATIONS_PROPERTY,
            new FloatArrayEvaluator(new float[9]), startMatrixValues, endMatrixValues);
    Path path = getPathMotion().getPath(startMatrixValues[Matrix.MTRANS_X], startMatrixValues[Matrix.MTRANS_Y],
            endMatrixValues[Matrix.MTRANS_X], endMatrixValues[Matrix.MTRANS_Y]);
    PropertyValuesHolder translationProperty = PropertyValuesHolderUtils.ofPointF(TRANSLATIONS_PROPERTY, path);
    ObjectAnimator animator = ObjectAnimator.ofPropertyValuesHolder(pathAnimatorMatrix, valuesProperty,
            translationProperty);

    final Matrix finalEndMatrix = endMatrix;

    AnimatorListenerAdapter listener = new AnimatorListenerAdapter() {
        private boolean mIsCanceled;
        private Matrix mTempMatrix = new Matrix();

        @Override
        public void onAnimationCancel(Animator animation) {
            mIsCanceled = true;
        }

        @Override
        public void onAnimationEnd(Animator animation) {
            if (!mIsCanceled) {
                if (handleParentChange && mUseOverlay) {
                    setCurrentMatrix(finalEndMatrix);
                } else {
                    view.setTag(R.id.transition_transform, null);
                    view.setTag(R.id.parent_matrix, null);
                }
            }
            ViewUtils.setAnimationMatrix(view, null);
            transforms.restore(view);
        }

        @Override
        public void onAnimationPause(Animator animation) {
            Matrix currentMatrix = pathAnimatorMatrix.getMatrix();
            setCurrentMatrix(currentMatrix);
        }

        @Override
        public void onAnimationResume(Animator animation) {
            setIdentityTransforms(view);
        }

        private void setCurrentMatrix(Matrix currentMatrix) {
            mTempMatrix.set(currentMatrix);
            view.setTag(R.id.transition_transform, mTempMatrix);
            transforms.restore(view);
        }
    };

    animator.addListener(listener);
    AnimatorUtils.addPauseListener(animator, listener);
    return animator;
}

From source file:com.larvalabs.svgandroid.SVGParser.java

private static Matrix parseTransformItem(String s, Matrix matrix) {
    if (s.startsWith("matrix(")) {
        NumberParse np = parseNumbers(s.substring("matrix(".length()));
        if (np.numbers.size() == 6) {
            Matrix mat = new Matrix();
            mat.setValues(new float[] {
                    // Row 1
                    np.numbers.get(0), np.numbers.get(2), np.numbers.get(4),
                    // Row 2
                    np.numbers.get(1), np.numbers.get(3), np.numbers.get(5),
                    // Row 3
                    0, 0, 1, });//ww w .j  a  v  a2  s  . c om
            matrix.preConcat(mat);
        }
    } else if (s.startsWith("translate(")) {
        NumberParse np = parseNumbers(s.substring("translate(".length()));
        if (np.numbers.size() > 0) {
            float tx = np.numbers.get(0);
            float ty = 0;
            if (np.numbers.size() > 1) {
                ty = np.numbers.get(1);
            }
            matrix.preTranslate(tx, ty);
        }
    } else if (s.startsWith("scale(")) {
        NumberParse np = parseNumbers(s.substring("scale(".length()));
        if (np.numbers.size() > 0) {
            float sx = np.numbers.get(0);
            float sy = sx;
            if (np.numbers.size() > 1) {
                sy = np.numbers.get(1);
            }
            matrix.preScale(sx, sy);
        }
    } else if (s.startsWith("skewX(")) {
        NumberParse np = parseNumbers(s.substring("skewX(".length()));
        if (np.numbers.size() > 0) {
            float angle = np.numbers.get(0);
            matrix.preSkew((float) Math.tan(angle), 0);
        }
    } else if (s.startsWith("skewY(")) {
        NumberParse np = parseNumbers(s.substring("skewY(".length()));
        if (np.numbers.size() > 0) {
            float angle = np.numbers.get(0);
            matrix.preSkew(0, (float) Math.tan(angle));
        }
    } else if (s.startsWith("rotate(")) {
        NumberParse np = parseNumbers(s.substring("rotate(".length()));
        if (np.numbers.size() > 0) {
            float angle = np.numbers.get(0);
            float cx = 0;
            float cy = 0;
            if (np.numbers.size() > 2) {
                cx = np.numbers.get(1);
                cy = np.numbers.get(2);
            }
            matrix.preTranslate(cx, cy);
            matrix.preRotate(angle);
            matrix.preTranslate(-cx, -cy);
        }
    } else {
        Log.i(TAG, "Invalid transform (" + s + ")");
    }
    return matrix;
}

From source file:com.ezartech.ezar.videooverlay.ezAR.java

private void startPreview(final CameraDirection cameraDir, final double zoom,
        final CallbackContext callbackContext) {

    Log.d(TAG, "start Preview");

    if (activity == null || activity.isFinishing()) {
        return;/*from ww  w  .  j a va  2 s.  c  o  m*/
    }

    if (isPreviewing()) {
        if (cameraId != getCameraId(cameraDir)) {
            stopPreview(null, false);
        }
    }

    matrix = new Matrix();
    cameraId = getCameraId(cameraDir);
    cameraDirection = cameraDir;

    if (cameraId != UNDEFINED) {
        camera = Camera.open(cameraId);
    }

    if (camera == null) {
        if (callbackContext != null)
            callbackContext.error("No camera available");
        return;
    }

    initCamera(camera);

    cordova.getActivity().runOnUiThread(new Runnable() {
        @Override
        public void run() {
            try {
                setIsPreviewing(true);
                updateCameraDisplayOrientation();

                //configure scaled CVG size & preview matrix
                updateCordovaViewContainerSize();
                camera.startPreview();
                webViewView.setBackgroundColor(Color.TRANSPARENT);

                setZoom(zoom, null);

                sendFlashlightEvent(STARTED, cameraDirection, cameraId, camera);
                sendFaceDetectorEvent(STARTED, cameraDirection, cameraId, camera);

                if (callbackContext != null) {
                    callbackContext.success();
                }

            } catch (Exception e) {
                Log.e(TAG, "Error during preview create", e);
                if (callbackContext != null)
                    callbackContext.error(TAG + ": " + e.getMessage());
            }

        }

    });
}