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:com.cloverstudio.spika.CameraCropActivity.java

protected void onPhotoTaken(String path) {

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

    if (!path.equals(mFilePath)) {
        copy(new File(path), new File(mFilePath));
    }/*from  w w w.  jav  a  2  s  .  co m*/

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

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

                if (params == null)
                    return null;

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

                int angle = 0;

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

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

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

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

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

            return null;
        }

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

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

                matrix = translateMatrix;

            }

        }
    }.execute(mFilePath);

}

From source file:com.MustacheMonitor.MustacheMonitor.StacheCam.java

/**
 * Figure out if the bitmap should be rotated. For instance if the picture was taken in
 * portrait mode/*from w w  w.  ja  v  a 2  s.  com*/
 *
 * @param rotate
 * @param bitmap
 * @return rotated bitmap
 */
private Bitmap getRotatedBitmap(int rotate, Bitmap bitmap, ExifHelper exif) {
    Matrix matrix = new Matrix();
    if (rotate == 180) {
        matrix.setRotate(rotate);
    } else {
        matrix.setRotate(rotate, (float) bitmap.getWidth() / 2, (float) bitmap.getHeight() / 2);
    }
    bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
    exif.resetOrientation();
    return bitmap;
}

From source file:com.grass.caishi.cc.activity.AdAddActivity.java

public void addToListImage(final String path) {
    if (path != null) {
        dialog.setMessage("...");
        dialog.show();//from w w w  .  j a  v  a2  s  .  com
        new Thread(new Runnable() {
            @Override
            public void run() {
                // TODO Auto-generated method stub
                File file = new File(path);
                imageUrl = path;
                FileInputStream fis = null;
                try {
                    int quality = 90;
                    fis = new FileInputStream(file);
                    int size = fis.available() / 1024;
                    if (size > 150) {
                        BitmapFactory.Options opts = new BitmapFactory.Options();
                        opts.inJustDecodeBounds = true;
                        resizeBmp = BitmapFactory.decodeFile(path, opts);

                        int pic_width = opts.outWidth;
                        int pic_height = opts.outHeight;
                        int be = 1;
                        if (pic_height > pic_width && pic_width > 1500) {
                            be = (int) Math.rint(pic_width / 1440.0);
                        } else if (pic_height < pic_width && pic_height > 2600) {
                            be = (int) Math.rint(pic_height / 2560.0);
                        }
                        if (be <= 0)
                            be = 1;
                        opts.inSampleSize = be;// 
                        opts.inJustDecodeBounds = false;
                        resizeBmp = BitmapFactory.decodeFile(path, opts);
                        pic_width = opts.outWidth;
                        pic_height = opts.outHeight;
                        File dirFile = new File(Environment.getExternalStorageDirectory(),
                                Constant.CACHE_DIR_IMAGE);
                        if (!dirFile.exists()) {
                            dirFile.mkdirs();
                        }
                        int drive_width = MetricsUnit.getWidth(AdAddActivity.this);
                        int drive_height = MetricsUnit.getHeight(AdAddActivity.this);

                        float my_width = (float) drive_width;
                        float my_height = (float) drive_height;

                        double doo = 0.0;
                        if (pic_width > my_width) {
                            doo = (double) my_width / (double) pic_width;
                            my_height = (int) (pic_height * doo);
                        }

                        int c_h = 0;

                        if (my_height > drive_height) {
                            c_h = (int) ((pic_height - my_height) / 2);
                            if (c_h < 0) {
                                c_h = 0;
                            }
                        }
                        Matrix matrix = new Matrix();
                        matrix.postScale(my_width / pic_width, my_height / pic_height);

                        resizeBmp = Bitmap.createBitmap(resizeBmp, 0, c_h, pic_width, pic_height, matrix, true);
                        File jpegTrueFile = new File(dirFile, "img_" + System.currentTimeMillis() + ".jpg");
                        FileOutputStream fileOutputStream = new FileOutputStream(jpegTrueFile);

                        resizeBmp.compress(CompressFormat.JPEG, quality, fileOutputStream);
                        imageUrl = jpegTrueFile.getAbsolutePath();
                        // MyApplication.getInstance().setMatchImages(jpegTrueFile.getAbsolutePath());

                        //bit.recycle();

                    } else {
                        resizeBmp = BitmapFactory.decodeStream(fis);
                    }

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            // TODO Auto-generated method stub
                            if (select_type == 1) {
                                path_logo = imageUrl;
                                img_logo.setImageBitmap(resizeBmp);
                            } else if (select_type == 2) {
                                path_price = imageUrl;
                                img_price.setImageBitmap(resizeBmp);
                            } else if (select_type == 3) {
                                MyApplication.getInstance().setMatchImages(imageUrl);
                                adapter.notifyDataSetChanged();
                            }
                            if (dialog.isShowing()) {
                                dialog.dismiss();
                            }
                        }
                    });

                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }).start();
    }
}

From source file:com.cordova.photo.CameraLauncher.java

/**
     * Applies all needed transformation to the image received from the gallery.
     */* ww w  .  ja v  a  2  s.  c o  m*/
     * @param destType          In which form should we return the image
     * @param intent            An Intent, which can return result data to the caller (various data can be attached to Intent "extras").
     */
private void processResultFromGallery(int destType, Intent intent) {
    Uri uri = intent.getData();
    if (uri == null) {
        if (croppedUri != null) {
            uri = croppedUri;
        } else {
            this.failPicture("null data from photo library");
            return;
        }
    }
    int rotate = 0;

    // If you ask for video or all media type you will automatically get back a file URI
    // and there will be no attempt to resize any returned data
    if (this.mediaType != PICTURE) {
        this.callbackContext.success(uri.toString());
    } else {
        // This is a special case to just return the path as no scaling,
        // rotating, nor compressing needs to be done
        if (this.targetHeight == -1 && this.targetWidth == -1
                && (destType == FILE_URI || destType == NATIVE_URI) && !this.correctOrientation) {
            this.callbackContext.success(uri.toString());
        } else {
            String uriString = uri.toString();
            // Get the path to the image. Makes loading so much easier.
            String mimeType = FileHelper.getMimeType(uriString, this.activity);
            // If we don't have a valid image so quit.
            if (!("image/jpeg".equalsIgnoreCase(mimeType) || "image/png".equalsIgnoreCase(mimeType))) {
                Log.d(LOG_TAG, "I either have a null image path or bitmap");
                this.failPicture("Unable to retrieve path to picture!");
                return;
            }
            Bitmap bitmap = null;
            try {
                bitmap = getScaledBitmap(uriString);
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (bitmap == null) {
                Log.d(LOG_TAG, "I either have a null image path or bitmap");
                this.failPicture("Unable to create bitmap!");
                return;
            }

            if (this.correctOrientation) {
                rotate = getImageOrientation(uri);
                if (rotate != 0) {
                    Matrix matrix = new Matrix();
                    matrix.setRotate(rotate);
                    try {
                        bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(),
                                matrix, true);
                        this.orientationCorrected = true;
                    } catch (OutOfMemoryError oom) {
                        this.orientationCorrected = false;
                    }
                }
            }

            // If sending base64 image back
            if (destType == DATA_URL) {
                this.processPicture(bitmap);
            }

            // If sending filename back
            else if (destType == FILE_URI || destType == NATIVE_URI) {
                // Did we modify the image?
                if ((this.targetHeight > 0 && this.targetWidth > 0)
                        || (this.correctOrientation && this.orientationCorrected)) {
                    try {
                        String modifiedPath = this.ouputModifiedBitmap(bitmap, uri);
                        // The modified image is cached by the app in order to get around this and not have to delete you
                        // application cache I'm adding the current system time to the end of the file url.
                        this.callbackContext
                                .success("file://" + modifiedPath + "?" + System.currentTimeMillis());
                    } catch (Exception e) {
                        e.printStackTrace();
                        this.failPicture("Error retrieving image.");
                    }
                } else {
                    this.callbackContext.success(uri.toString());
                }
            }
            if (bitmap != null) {
                bitmap.recycle();
                bitmap = null;
            }
            System.gc();
        }
    }
}

From source file:bluetoothchat.BluetoothChatFragment.java

/**
 * overllay a tick on the underlaying sticker image
 * @param bmp1 sticker image/* ww  w  .  j a v  a 2s.c o  m*/
 * @return
 */
private Bitmap bitmapOverlay(Bitmap bmp1) {
    Bitmap bmp2 = BitmapFactory.decodeResource(getResources(), R.drawable.accept2);
    Bitmap bmOverlay = Bitmap.createBitmap(bmp1.getWidth(), bmp1.getHeight(), bmp1.getConfig());
    Canvas canvas = new Canvas(bmOverlay);
    canvas.drawBitmap(bmp1, new Matrix(), null);
    canvas.drawBitmap(bmp2, new Matrix(), null);
    return bmOverlay;
}

From source file:com.remobile.camera.CameraLauncher.java

/**
 * Applies all needed transformation to the image received from the gallery.
 *
 * @param destType In which form should we return the image
 * @param intent   An Intent, which can return result data to the caller (various data can be attached to Intent "extras").
 *//*from ww  w. j a v  a 2 s. c  om*/
private void processResultFromGallery(int destType, Intent intent) {
    Uri uri = intent.getData();
    if (uri == null) {
        if (croppedUri != null) {
            uri = croppedUri;
        } else {
            this.failPicture("null data from photo library");
            return;
        }
    }
    int rotate = 0;

    // If you ask for video or all media type you will automatically get back a file URI
    // and there will be no attempt to resize any returned data
    if (this.mediaType != PICTURE) {
        this.callbackContext.success(uri.toString());
    } else {
        // This is a special case to just return the path as no scaling,
        // rotating, nor compressing needs to be done
        if (this.targetHeight == -1 && this.targetWidth == -1
                && (destType == FILE_URI || destType == NATIVE_URI) && !this.correctOrientation) {
            this.callbackContext.success(uri.toString());
        } else {
            String uriString = uri.toString();
            // Get the path to the image. Makes loading so much easier.
            String mimeType = FileHelper.getMimeType(uriString, this.cordova);
            // If we don't have a valid image so quit.
            if (!("image/jpeg".equalsIgnoreCase(mimeType) || "image/png".equalsIgnoreCase(mimeType))) {
                Log.d(LOG_TAG, "I either have a null image path or bitmap");
                this.failPicture("Unable to retrieve path to picture!");
                return;
            }
            Bitmap bitmap = null;
            try {
                bitmap = getScaledBitmap(uriString);
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (bitmap == null) {
                Log.d(LOG_TAG, "I either have a null image path or bitmap");
                this.failPicture("Unable to create bitmap!");
                return;
            }

            if (this.correctOrientation) {
                rotate = getImageOrientation(uri);
                if (rotate != 0) {
                    Matrix matrix = new Matrix();
                    matrix.setRotate(rotate);
                    try {
                        bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(),
                                matrix, true);
                        this.orientationCorrected = true;
                    } catch (OutOfMemoryError oom) {
                        this.orientationCorrected = false;
                    }
                }
            }

            // If sending base64 image back
            if (destType == DATA_URL) {
                this.processPicture(bitmap);
            }

            // If sending filename back
            else if (destType == FILE_URI || destType == NATIVE_URI) {
                // Did we modify the image?
                if ((this.targetHeight > 0 && this.targetWidth > 0)
                        || (this.correctOrientation && this.orientationCorrected)) {
                    try {
                        String modifiedPath = this.ouputModifiedBitmap(bitmap, uri);
                        // The modified image is cached by the app in order to get around this and not have to delete you
                        // application cache I'm adding the current system time to the end of the file url.
                        this.callbackContext
                                .success("file://" + modifiedPath + "?" + System.currentTimeMillis());
                    } catch (Exception e) {
                        e.printStackTrace();
                        this.failPicture("Error retrieving image.");
                    }
                } else {
                    this.callbackContext.success(uri.toString());
                }
            }
            if (bitmap != null) {
                bitmap.recycle();
                bitmap = null;
            }
            System.gc();
        }
    }
}

From source file:com.almalence.util.Util.java

public static void initializeMeteringMatrix() {
    Matrix matrix = new Matrix();
    Util.prepareMatrix(matrix, CameraController.isFrontCamera(), 0, ApplicationScreen.getPreviewWidth(),
            ApplicationScreen.getPreviewHeight());
    matrix.invert(mMeteringMatrix);//from  ww w. j ava2  s  . c  om
}

From source file:com.snappy.CameraCropActivity.java

protected void onPhotoTaken(final String path) {

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

    if (!path.equals(mFilePath)) {
        copy(new File(path), new File(mFilePath));
    }//from  w  ww. j  a va  2s  .  c  om

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

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

                if (!path.equals(mFilePath)) {
                    copy(new File(path), new File(mFilePath));
                }

                if (params == null)
                    return null;

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

                int angle = 0;

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

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

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

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

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

            return null;
        }

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

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

                matrix = translateMatrix;

            }

        }
    }.execute(mFilePath);

}

From source file:com.polyvi.xface.extension.camera.XCameraExt.java

private void photoSucess(Intent intent) {
    //URI????URI?URI??
    //???try-catch???
    Uri uri = intent.getData();/*from   w  w w  .  j ava  2 s. com*/
    if (null == uri) {
        uri = mImageUri;
    }
    ContentResolver resolver = getContext().getContentResolver();
    XPathResolver pathResolver = new XPathResolver(null == uri ? null : uri.toString(), "", getContext());
    Bitmap bitmap = null;
    try {
        if (!mAllowEdit) {
            String path = pathResolver.resolve();
            if (!XStringUtils.isEmptyString(path)) {
                bitmap = XUtils.decodeBitmap(path);
            }
        } else {
            //??????Android???
            bitmap = intent.getExtras().getParcelable("data");

            //?????URI
            if (bitmap == null) {
                bitmap = getCroppedBitmap(intent);
            }
        }
    } catch (OutOfMemoryError e) {
        mCallbackCtx.error("OutOfMemoryError when decode image.");
        return;
    }
    if (mDestType == DATA_URL) {
        int rotate = 0;
        String[] cols = { MediaStore.Images.Media.ORIENTATION };
        Cursor cursor = resolver.query(uri, cols, null, null, null);
        if (null != cursor) {
            cursor.moveToPosition(0);
            rotate = cursor.getInt(0);
            cursor.close();
        }
        if (0 != rotate) {
            Matrix matrix = new Matrix();
            matrix.setRotate(rotate);
            bitmap = bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
        }
        bitmap = scaleBitmap(bitmap);
        processPicture(bitmap);
        bitmap.recycle();
        bitmap = null;
        System.gc();
    } else if (mTargetHeight > 0 && mTargetWidth > 0) {
        try {
            Bitmap scaleBitmap = scaleBitmap(bitmap);

            String fileName = XConfiguration.getInstance().getWorkDirectory() + RESIZED_PIC_NAME;
            OutputStream os = new FileOutputStream(fileName);
            scaleBitmap.compress(Bitmap.CompressFormat.JPEG, mQuality, os);
            os.close();

            bitmap.recycle();
            bitmap = null;
            scaleBitmap.recycle();
            scaleBitmap = null;

            mCallbackCtx.success("file://" + fileName + "?" + System.currentTimeMillis());
            System.gc();
        } catch (Exception e) {
            mCallbackCtx.error("Error retrieving image.");
            return;
        }
    } else {
        mCallbackCtx.success(XConstant.FILE_SCHEME + pathResolver.resolve());
    }
}

From source file:cw.kop.autobackground.files.DownloadThread.java

private void writeToFileWithThumbnail(Bitmap image, String saveData, String dir, File file, long time) {

    if (file.isFile()) {
        file.delete();/*from   w  ww .  j ava  2 s  . c  om*/
    }

    FileOutputStream out = null;
    FileOutputStream thumbnailOut = null;
    try {
        int bitWidth = image.getWidth();
        int bitHeight = image.getHeight();

        float thumbnailSize = (float) AppSettings.getThumbnailSize();

        Bitmap thumbnail;

        if (thumbnailSize < bitWidth && thumbnailSize < bitHeight) {
            Matrix matrix = new Matrix();
            if (bitWidth > bitHeight) {
                matrix.postScale(thumbnailSize / bitWidth, thumbnailSize / bitWidth);
            } else {
                matrix.postScale(thumbnailSize / bitHeight, thumbnailSize / bitHeight);
            }
            thumbnail = Bitmap.createBitmap(image, 0, 0, bitWidth, bitHeight, matrix, false);
        } else {
            thumbnail = image;
        }

        out = new FileOutputStream(file);
        image.compress(Bitmap.CompressFormat.PNG, 90, out);

        File thumbnailCache = new File(dir + "/HistoryCache");

        if (!thumbnailCache.exists() || (thumbnailCache.exists() && !thumbnailCache.isDirectory())) {
            thumbnailCache.mkdir();
        }

        File thumbnailFile = new File(thumbnailCache.getAbsolutePath() + "/" + time + ".png");

        thumbnailOut = new FileOutputStream(thumbnailFile);

        thumbnail.compress(Bitmap.CompressFormat.PNG, 90, thumbnailOut);

        Log.i(TAG, "Thumbnail written: " + thumbnailFile.getAbsolutePath());

        AppSettings.setUrl(file.getName(), saveData);
        Log.i(TAG, file.getName() + " " + saveData);
        thumbnail.recycle();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } finally {
        try {
            if (out != null) {
                out.close();
            }
            if (thumbnailOut != null) {
                thumbnailOut.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    image.recycle();
}