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.MustacheMonitor.MustacheMonitor.StacheCam.java

/**
 * Called when the camera view exits.// ww  w .j ava 2  s  .  com
 *
 * @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) {

    // Get src and dest types from request code
    int srcType = (requestCode / 16) - 1;
    int destType = (requestCode % 16) - 1;
    int rotate = 0;

    // If CAMERA
    if (srcType == CAMERA) {
        // 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();
                try {
                    if (this.encodingType == JPEG) {
                        exif.createInFile(DirectoryManager.getTempDirectoryPath(this.cordova.getActivity())
                                + "/.Pic.jpg");
                        exif.readExifData();
                        rotate = exif.getOrientation();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }

                Bitmap bitmap = null;
                Uri uri = null;

                // If sending base64 image back
                if (destType == DATA_URL) {
                    bitmap = getScaledBitmap(FileUtils.stripFileProtocol(imageUri.toString()));

                    if (rotate != 0 && this.correctOrientation) {
                        bitmap = getRotatedBitmap(rotate, bitmap, exif);
                    }

                    this.processPicture(bitmap);
                    checkForDuplicateImage(DATA_URL);
                }

                // If sending filename back
                else if (destType == FILE_URI) {
                    if (!this.saveToPhotoAlbum) {
                        uri = Uri.fromFile(
                                new File(DirectoryManager.getTempDirectoryPath(this.cordova.getActivity()),
                                        System.currentTimeMillis() + ".jpg"));
                    } else {
                        uri = getUriFromMediaStore();
                    }

                    if (uri == null) {
                        this.failPicture("Error capturing image - no media storage found.");
                    }

                    // If all this is true we shouldn't compress the image.
                    if (this.targetHeight == -1 && this.targetWidth == -1 && this.mQuality == 100
                            && rotate == 0) {
                        writeUncompressedImage(uri);

                        this.success(new PluginResult(PluginResult.Status.OK, uri.toString()), this.callbackId);
                    } else {
                        bitmap = getScaledBitmap(FileUtils.stripFileProtocol(imageUri.toString()));

                        if (rotate != 0 && this.correctOrientation) {
                            bitmap = getRotatedBitmap(rotate, bitmap, exif);
                        }

                        // 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
                        if (this.encodingType == JPEG) {
                            String exifPath;
                            if (this.saveToPhotoAlbum) {
                                exifPath = FileUtils.getRealPathFromURI(uri, this.cordova);
                            } else {
                                exifPath = uri.getPath();
                            }
                            exif.createOutFile(exifPath);
                            exif.writeExifData();
                        }

                    }
                    // Send Uri back to JavaScript for viewing image
                    this.success(new PluginResult(PluginResult.Status.OK, uri.toString()), this.callbackId);
                }

                this.cleanup(FILE_URI, this.imageUri, uri, bitmap);
                bitmap = null;

            } 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!");
        }
    }

    // If retrieving photo from library
    else if ((srcType == PHOTOLIBRARY) || (srcType == SAVEDPHOTOALBUM)) {
        if (resultCode == Activity.RESULT_OK) {
            Uri uri = intent.getData();

            // 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.success(new PluginResult(PluginResult.Status.OK, uri.toString()), this.callbackId);
            } else {
                // This is a special case to just return the path as no scaling,
                // rotating or compression needs to be done
                if (this.targetHeight == -1 && this.targetWidth == -1 && this.mQuality == 100
                        && destType == FILE_URI && !this.correctOrientation) {
                    this.success(new PluginResult(PluginResult.Status.OK, uri.toString()), this.callbackId);
                } else {
                    // Get the path to the image. Makes loading so much easier.
                    String imagePath = FileUtils.getRealPathFromURI(uri, this.cordova);
                    Log.d(LOG_TAG, "Real path = " + imagePath);
                    // If we don't have a valid image so quit.
                    if (imagePath == null) {
                        Log.d(LOG_TAG, "I either have a null image path or bitmap");
                        this.failPicture("Unable to retreive path to picture!");
                        return;
                    }
                    Bitmap bitmap = getScaledBitmap(imagePath);
                    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) {
                        String[] cols = { MediaStore.Images.Media.ORIENTATION };
                        Cursor cursor = this.cordova.getActivity().getContentResolver().query(intent.getData(),
                                cols, null, null, null);
                        if (cursor != null) {
                            cursor.moveToPosition(0);
                            rotate = cursor.getInt(0);
                            cursor.close();
                        }
                        if (rotate != 0) {
                            Matrix matrix = new Matrix();
                            matrix.setRotate(rotate);
                            bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(),
                                    matrix, true);
                        }
                    }

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

                    // If sending filename back
                    else if (destType == FILE_URI) {
                        // Do we need to scale the returned file
                        if (this.targetHeight > 0 && this.targetWidth > 0) {
                            try {
                                // Create an ExifHelper to save the exif data that is lost during compression
                                String resizePath = DirectoryManager
                                        .getTempDirectoryPath(this.cordova.getActivity()) + "/resize.jpg";
                                ExifHelper exif = new ExifHelper();
                                try {
                                    if (this.encodingType == JPEG) {
                                        exif.createInFile(resizePath);
                                        exif.readExifData();
                                        rotate = exif.getOrientation();
                                    }
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }

                                OutputStream os = new FileOutputStream(resizePath);
                                bitmap.compress(Bitmap.CompressFormat.JPEG, this.mQuality, os);
                                os.close();

                                // Restore exif data to file
                                if (this.encodingType == JPEG) {
                                    exif.createOutFile(FileUtils.getRealPathFromURI(uri, this.cordova));
                                    exif.writeExifData();
                                }

                                // The resized 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.success(
                                        new PluginResult(PluginResult.Status.OK,
                                                ("file://" + resizePath + "?" + System.currentTimeMillis())),
                                        this.callbackId);
                            } catch (Exception e) {
                                e.printStackTrace();
                                this.failPicture("Error retrieving image.");
                            }
                        } else {
                            this.success(new PluginResult(PluginResult.Status.OK, uri.toString()),
                                    this.callbackId);
                        }
                    }
                    if (bitmap != null) {
                        bitmap.recycle();
                        bitmap = null;
                    }
                    System.gc();
                }
            }
        } else if (resultCode == Activity.RESULT_CANCELED) {
            this.failPicture("Selection cancelled.");
        } else {
            this.failPicture("Selection did not complete!");
        }
    }
}

From source file:com.prt.thirdeye.CamManager.java

/**
 * Returns the last frame of the preview surface
 * /*from   www  .  j a  va  2 s.c om*/
 * @return Bitmap
 */
public Bitmap getLastPreviewFrame() {
    // Decode the last frame bytes
    byte[] data = mPreview.getLastFrameBytes();
    Camera.Parameters params = getParameters();

    if (params == null) {
        return null;
    }

    Camera.Size previewSize = params.getPreviewSize();
    if (previewSize == null) {
        return null;
    }

    int previewWidth = previewSize.width;
    int previewHeight = previewSize.height;

    // Convert YUV420SP preview data to RGB
    try {
        if (data != null && data.length > 8) {
            Bitmap bitmap = Util.decodeYUV420SP(mContext, data, previewWidth, previewHeight);
            if (mCurrentFacing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
                // Frontcam has the image flipped, flip it back to not look
                // weird in portrait
                Matrix m = new Matrix();
                m.preScale(-1, 1);
                Bitmap dst = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), m, false);
                bitmap.recycle();
                bitmap = dst;
            }

            return bitmap;
        } else {
            return null;
        }
    } catch (ArrayIndexOutOfBoundsException e) {
        // TODO: FIXME: On some devices, the resolution of the preview might
        // abruptly change,
        // thus the YUV420SP data is not the size we expect, causing OOB
        // exception
        return null;
    }
}

From source file:com.ktouch.kdc.launcher4.camera.CameraManager.java

/**
 * Returns the last frame of the preview surface
 *
 * @return Bitmap/*  ww  w . j a  v  a2 s.co  m*/
 */
public Bitmap getLastPreviewFrame() {
    // Decode the last frame bytes
    byte[] data = mPreview.getLastFrameBytes();
    Camera.Parameters params = getParameters();

    if (params == null) {
        return null;
    }

    Camera.Size previewSize = params.getPreviewSize();
    if (previewSize == null) {
        return null;
    }

    int previewWidth = previewSize.width;
    int previewHeight = previewSize.height;

    // Convert YUV420SP preview data to RGB
    try {
        if (data != null && data.length > 8) {
            Bitmap bitmap = Util.decodeYUV420SP(mContext, data, previewWidth, previewHeight);
            if (mCurrentFacing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
                // Frontcam has the image flipped, flip it back to not look weird in portrait
                Matrix m = new Matrix();
                m.preScale(-1, 1);
                Bitmap dst = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), m, false);
                bitmap.recycle();
                bitmap = dst;
            }

            return bitmap;
        } else {
            return null;
        }
    } catch (ArrayIndexOutOfBoundsException e) {
        // TODO: FIXME: On some devices, the resolution of the preview might abruptly change,
        // thus the YUV420SP data is not the size we expect, causing OOB exception
        return null;
    }
}

From source file:com.android.rahul.myselfieapp.Fragment.CamVideoFragment.java

/**
 * Configures the necessary {@link android.graphics.Matrix} transformation to `mTextureView`.
 * This method should not to be called until the camera preview size is determined in
 * openCamera, or until the size of `mTextureView` is fixed.
 *
 * @param viewWidth  The width of `mTextureView`
 * @param viewHeight The height of `mTextureView`
 *//* w w  w  .  j a v a  2  s. c o  m*/
private void configureTransform(int viewWidth, int viewHeight) {
    Activity activity = getActivity();
    if (null == mTextureView || null == mPreviewSize || null == activity) {
        return;
    }
    int rotation = activity.getWindowManager().getDefaultDisplay().getRotation();
    Matrix matrix = new Matrix();
    RectF viewRect = new RectF(0, 0, viewWidth, viewHeight);
    RectF bufferRect = new RectF(0, 0, mPreviewSize.getHeight(), mPreviewSize.getWidth());
    float centerX = viewRect.centerX();
    float centerY = viewRect.centerY();
    if (Surface.ROTATION_90 == rotation || Surface.ROTATION_270 == rotation) {
        bufferRect.offset(centerX - bufferRect.centerX(), centerY - bufferRect.centerY());
        matrix.setRectToRect(viewRect, bufferRect, Matrix.ScaleToFit.FILL);
        float scale = Math.max((float) viewHeight / mPreviewSize.getHeight(),
                (float) viewWidth / mPreviewSize.getWidth());
        matrix.postScale(scale, scale, centerX, centerY);
        matrix.postRotate(90 * (rotation - 2), centerX, centerY);
    }
    mTextureView.setTransform(matrix);
}

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

public static Bitmap decodeSampledBitmapFromPath(String path, int reqWidth, int reqHeight) {
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;//  w ww  .  j  av  a2 s .  co m
    BitmapFactory.decodeFile(path, options);
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
    options.inJustDecodeBounds = false;

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

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

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

From source file:com.almalence.opencam.SavingService.java

public void saveResultPicture(long sessionID) {
    initSavingPrefs();/* w w  w .jav  a 2  s  . c om*/
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    // save fused result
    try {
        File saveDir = getSaveDir(false);

        Calendar d = Calendar.getInstance();

        int imagesAmount = Integer
                .parseInt(getFromSharedMem("amountofresultframes" + Long.toString(sessionID)));

        if (imagesAmount == 0)
            imagesAmount = 1;

        int imageIndex = 0;
        String sImageIndex = getFromSharedMem("resultframeindex" + Long.toString(sessionID));
        if (sImageIndex != null)
            imageIndex = Integer.parseInt(getFromSharedMem("resultframeindex" + Long.toString(sessionID)));

        if (imageIndex != 0)
            imagesAmount = 1;

        ContentValues values = null;

        boolean hasDNGResult = false;
        for (int i = 1; i <= imagesAmount; i++) {
            hasDNGResult = false;
            String format = getFromSharedMem("resultframeformat" + i + Long.toString(sessionID));

            if (format != null && format.equalsIgnoreCase("dng"))
                hasDNGResult = true;

            String idx = "";

            if (imagesAmount != 1)
                idx += "_" + ((format != null && !format.equalsIgnoreCase("dng") && hasDNGResult)
                        ? i - imagesAmount / 2
                        : i);

            String modeName = getFromSharedMem("modeSaveName" + Long.toString(sessionID));
            // define file name format. from settings!
            String fileFormat = getExportFileName(modeName);
            fileFormat += idx + ((format != null && format.equalsIgnoreCase("dng")) ? ".dng" : ".jpg");

            File file;
            if (ApplicationScreen.getForceFilename() == null) {
                file = new File(saveDir, fileFormat);
            } else {
                file = ApplicationScreen.getForceFilename();
            }

            OutputStream os = null;
            if (ApplicationScreen.getForceFilename() != null) {
                os = getApplicationContext().getContentResolver()
                        .openOutputStream(ApplicationScreen.getForceFilenameURI());
            } else {
                try {
                    os = new FileOutputStream(file);
                } catch (Exception e) {
                    // save always if not working saving to sdcard
                    e.printStackTrace();
                    saveDir = getSaveDir(true);
                    if (ApplicationScreen.getForceFilename() == null) {
                        file = new File(saveDir, fileFormat);
                    } else {
                        file = ApplicationScreen.getForceFilename();
                    }
                    os = new FileOutputStream(file);
                }
            }

            // Take only one result frame from several results
            // Used for PreShot plugin that may decide which result to save
            if (imagesAmount == 1 && imageIndex != 0)
                i = imageIndex;

            String resultOrientation = getFromSharedMem(
                    "resultframeorientation" + i + Long.toString(sessionID));
            int orientation = 0;
            if (resultOrientation != null)
                orientation = Integer.parseInt(resultOrientation);

            String resultMirrored = getFromSharedMem("resultframemirrored" + i + Long.toString(sessionID));
            Boolean cameraMirrored = false;
            if (resultMirrored != null)
                cameraMirrored = Boolean.parseBoolean(resultMirrored);

            int x = Integer.parseInt(getFromSharedMem("saveImageHeight" + Long.toString(sessionID)));
            int y = Integer.parseInt(getFromSharedMem("saveImageWidth" + Long.toString(sessionID)));
            if (orientation == 0 || orientation == 180 || (format != null && format.equalsIgnoreCase("dng"))) {
                x = Integer.valueOf(getFromSharedMem("saveImageWidth" + Long.toString(sessionID)));
                y = Integer.valueOf(getFromSharedMem("saveImageHeight" + Long.toString(sessionID)));
            }

            Boolean writeOrientationTag = true;
            String writeOrientTag = getFromSharedMem("writeorientationtag" + Long.toString(sessionID));
            if (writeOrientTag != null)
                writeOrientationTag = Boolean.parseBoolean(writeOrientTag);

            if (format != null && format.equalsIgnoreCase("jpeg")) {// if result in jpeg format

                if (os != null) {
                    byte[] frame = SwapHeap.SwapFromHeap(
                            Integer.parseInt(getFromSharedMem("resultframe" + i + Long.toString(sessionID))),
                            Integer.parseInt(
                                    getFromSharedMem("resultframelen" + i + Long.toString(sessionID))));
                    os.write(frame);
                    try {
                        os.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            } else if (format != null && format.equalsIgnoreCase("dng")) {
                saveDNGPicture(i, sessionID, os, x, y, orientation, cameraMirrored);
            } else {// if result in nv21 format
                int yuv = Integer.parseInt(getFromSharedMem("resultframe" + i + Long.toString(sessionID)));
                com.almalence.YuvImage out = new com.almalence.YuvImage(yuv, ImageFormat.NV21, x, y, null);
                Rect r;

                String res = getFromSharedMem("resultfromshared" + Long.toString(sessionID));
                if ((null == res) || "".equals(res) || "true".equals(res)) {
                    // to avoid problems with SKIA
                    int cropHeight = out.getHeight() - out.getHeight() % 16;
                    r = new Rect(0, 0, out.getWidth(), cropHeight);
                } else {
                    if (null == getFromSharedMem("resultcrop0" + Long.toString(sessionID))) {
                        // to avoid problems with SKIA
                        int cropHeight = out.getHeight() - out.getHeight() % 16;
                        r = new Rect(0, 0, out.getWidth(), cropHeight);
                    } else {
                        int crop0 = Integer
                                .parseInt(getFromSharedMem("resultcrop0" + Long.toString(sessionID)));
                        int crop1 = Integer
                                .parseInt(getFromSharedMem("resultcrop1" + Long.toString(sessionID)));
                        int crop2 = Integer
                                .parseInt(getFromSharedMem("resultcrop2" + Long.toString(sessionID)));
                        int crop3 = Integer
                                .parseInt(getFromSharedMem("resultcrop3" + Long.toString(sessionID)));

                        r = new Rect(crop0, crop1, crop0 + crop2, crop1 + crop3);

                    }
                }

                jpegQuality = Integer.parseInt(prefs.getString(ApplicationScreen.sJPEGQualityPref, "95"));
                if (!out.compressToJpeg(r, jpegQuality, os)) {
                    if (ApplicationScreen.instance != null && ApplicationScreen.getMessageHandler() != null) {
                        ApplicationScreen.getMessageHandler()
                                .sendEmptyMessage(ApplicationInterface.MSG_EXPORT_FINISHED_IOEXCEPTION);
                    }
                    return;
                }
                SwapHeap.FreeFromHeap(yuv);
            }

            String orientation_tag = String.valueOf(0);
            //            int sensorOrientation = CameraController.getSensorOrientation();
            //            int displayOrientation = CameraController.getDisplayOrientation();
            //            sensorOrientation = (360 + sensorOrientation + (cameraMirrored ? -displayOrientation
            //                  : displayOrientation)) % 360;

            //            if (CameraController.isFlippedSensorDevice() && cameraMirrored)
            //               orientation = (orientation + 180) % 360;

            switch (orientation) {
            default:
            case 0:
                orientation_tag = String.valueOf(0);
                break;
            case 90:
                orientation_tag = cameraMirrored ? String.valueOf(270) : String.valueOf(90);
                break;
            case 180:
                orientation_tag = String.valueOf(180);
                break;
            case 270:
                orientation_tag = cameraMirrored ? String.valueOf(90) : String.valueOf(270);
                break;
            }

            int exif_orientation = ExifInterface.ORIENTATION_NORMAL;
            if (writeOrientationTag) {
                switch ((orientation + 360) % 360) {
                default:
                case 0:
                    exif_orientation = ExifInterface.ORIENTATION_NORMAL;
                    break;
                case 90:
                    exif_orientation = cameraMirrored ? ExifInterface.ORIENTATION_ROTATE_270
                            : ExifInterface.ORIENTATION_ROTATE_90;
                    break;
                case 180:
                    exif_orientation = ExifInterface.ORIENTATION_ROTATE_180;
                    break;
                case 270:
                    exif_orientation = cameraMirrored ? ExifInterface.ORIENTATION_ROTATE_90
                            : ExifInterface.ORIENTATION_ROTATE_270;
                    break;
                }
            } else {
                switch ((additionalRotationValue + 360) % 360) {
                default:
                case 0:
                    exif_orientation = ExifInterface.ORIENTATION_NORMAL;
                    break;
                case 90:
                    exif_orientation = cameraMirrored ? ExifInterface.ORIENTATION_ROTATE_270
                            : ExifInterface.ORIENTATION_ROTATE_90;
                    break;
                case 180:
                    exif_orientation = ExifInterface.ORIENTATION_ROTATE_180;
                    break;
                case 270:
                    exif_orientation = cameraMirrored ? ExifInterface.ORIENTATION_ROTATE_90
                            : ExifInterface.ORIENTATION_ROTATE_270;
                    break;
                }
            }

            if (!enableExifTagOrientation)
                exif_orientation = ExifInterface.ORIENTATION_NORMAL;

            File parent = file.getParentFile();
            String path = parent.toString().toLowerCase();
            String name = parent.getName().toLowerCase();

            values = new ContentValues();
            values.put(ImageColumns.TITLE,
                    file.getName().substring(0,
                            file.getName().lastIndexOf(".") >= 0 ? file.getName().lastIndexOf(".")
                                    : file.getName().length()));
            values.put(ImageColumns.DISPLAY_NAME, file.getName());
            values.put(ImageColumns.DATE_TAKEN, System.currentTimeMillis());
            values.put(ImageColumns.MIME_TYPE, "image/jpeg");

            if (enableExifTagOrientation) {
                if (writeOrientationTag) {
                    values.put(ImageColumns.ORIENTATION, String.valueOf(
                            (Integer.parseInt(orientation_tag) + additionalRotationValue + 360) % 360));
                } else {
                    values.put(ImageColumns.ORIENTATION, String.valueOf((additionalRotationValue + 360) % 360));
                }
            } else {
                values.put(ImageColumns.ORIENTATION, String.valueOf(0));
            }

            values.put(ImageColumns.BUCKET_ID, path.hashCode());
            values.put(ImageColumns.BUCKET_DISPLAY_NAME, name);
            values.put(ImageColumns.DATA, file.getAbsolutePath());

            File tmpFile;
            if (ApplicationScreen.getForceFilename() == null) {
                tmpFile = file;
            } else {
                tmpFile = new File(getApplicationContext().getFilesDir(), "buffer.jpeg");
                tmpFile.createNewFile();
                copyFromForceFileName(tmpFile);
            }

            if (!enableExifTagOrientation) {
                Matrix matrix = new Matrix();
                if (writeOrientationTag && (orientation + additionalRotationValue) != 0) {
                    matrix.postRotate((orientation + additionalRotationValue + 360) % 360);
                    rotateImage(tmpFile, matrix);
                } else if (!writeOrientationTag && additionalRotationValue != 0) {
                    matrix.postRotate((additionalRotationValue + 360) % 360);
                    rotateImage(tmpFile, matrix);
                }
            }

            if (useGeoTaggingPrefExport) {
                Location l = MLocation.getLocation(getApplicationContext());
                if (l != null) {
                    double lat = l.getLatitude();
                    double lon = l.getLongitude();
                    boolean hasLatLon = (lat != 0.0d) || (lon != 0.0d);
                    if (hasLatLon) {
                        values.put(ImageColumns.LATITUDE, l.getLatitude());
                        values.put(ImageColumns.LONGITUDE, l.getLongitude());
                    }
                }
            }

            File modifiedFile = saveExifTags(tmpFile, sessionID, i, x, y, exif_orientation,
                    useGeoTaggingPrefExport, enableExifTagOrientation);
            if (ApplicationScreen.getForceFilename() == null) {
                file.delete();
                modifiedFile.renameTo(file);
            } else {
                copyToForceFileName(modifiedFile);
                tmpFile.delete();
                modifiedFile.delete();
            }

            Uri uri = getApplicationContext().getContentResolver().insert(Images.Media.EXTERNAL_CONTENT_URI,
                    values);
            broadcastNewPicture(uri);
        }

        ApplicationScreen.getMessageHandler().sendEmptyMessage(ApplicationInterface.MSG_EXPORT_FINISHED);
    } catch (IOException e) {
        e.printStackTrace();
        ApplicationScreen.getMessageHandler()
                .sendEmptyMessage(ApplicationInterface.MSG_EXPORT_FINISHED_IOEXCEPTION);
        return;
    } catch (Exception e) {
        e.printStackTrace();
        ApplicationScreen.getMessageHandler().sendEmptyMessage(ApplicationInterface.MSG_EXPORT_FINISHED);
    } finally {
        ApplicationScreen.setForceFilename(null);
    }
}

From source file:com.phonegap.plugins.wsiCameraLauncher.WsiCameraLauncher.java

private Bitmap fitInsideSquare(Bitmap b, int sideLength) {
    int grabWidth = b.getWidth();
    int grabHeight = b.getHeight();

    float scaleX = ((float) sideLength) / grabWidth;
    float scaleY = ((float) sideLength) / grabHeight;
    float scale = Math.min(scaleX, scaleY);

    Matrix m = new Matrix();
    m.postScale(scale, scale);//from  ww  w. j a v a  2  s. c o  m

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

From source file:com.phonegap.plugins.wsiCameraLauncher.WsiCameraLauncher.java

private Bitmap makeInsideSquare(Bitmap b, int sideLength) {
    int grabWidth = b.getWidth();
    int grabHeight = b.getHeight();
    if (grabWidth > grabHeight) {
        grabWidth = grabHeight;/*from  w ww. j a va2  s .  c o  m*/
    } else {
        grabHeight = grabWidth;
    }

    float scale = ((float) sideLength) / grabWidth;

    Matrix m = new Matrix();
    m.postScale(scale, scale);

    return Bitmap.createBitmap(b, 0, 0, grabWidth, grabHeight, m, true);
}

From source file:com.askjeffreyliu.camera2barcode.camera.CameraSource.java

/**
 * Configures the necessary {@link android.graphics.Matrix} transformation to `mTextureView`.
 * This method should be called after the camera preview size is determined in
 * setUpCameraOutputs and also the size of `mTextureView` is fixed.
 *
 * @param viewWidth  The width of `mTextureView`
 * @param viewHeight The height of `mTextureView`
 *///w ww .j  a  v  a2  s  .  c om
private void configureTransform(int viewWidth, int viewHeight) {
    if (null == mTextureView || null == mPreviewSize) {
        return;
    }
    int rotation = mDisplayOrientation;
    Matrix matrix = new Matrix();
    RectF viewRect = new RectF(0, 0, viewWidth, viewHeight);
    RectF bufferRect = new RectF(0, 0, mPreviewSize.getHeight(), mPreviewSize.getWidth());
    float centerX = viewRect.centerX();
    float centerY = viewRect.centerY();
    if (Surface.ROTATION_90 == rotation || Surface.ROTATION_270 == rotation) {
        bufferRect.offset(centerX - bufferRect.centerX(), centerY - bufferRect.centerY());
        matrix.setRectToRect(viewRect, bufferRect, Matrix.ScaleToFit.FILL);
        float scale = Math.max((float) viewHeight / mPreviewSize.getHeight(),
                (float) viewWidth / mPreviewSize.getWidth());
        matrix.postScale(scale, scale, centerX, centerY);
        matrix.postRotate(90 * (rotation - 2), centerX, centerY);
    } else if (Surface.ROTATION_180 == rotation) {
        matrix.postRotate(180, centerX, centerY);
    }
    mTextureView.setTransform(matrix);
}

From source file:edu.cens.loci.ui.PlaceListActivity.java

private Bitmap overlay(Bitmap... bitmaps) {

    if (bitmaps[0].equals(null))
        return null;

    Bitmap bmOverlay = Bitmap.createBitmap(60, 60, Bitmap.Config.ARGB_4444);

    Canvas canvas = new Canvas(bmOverlay);
    for (int i = 0; i < bitmaps.length; i++)
        canvas.drawBitmap(bitmaps[i], new Matrix(), null);

    return bmOverlay;
}