Example usage for android.graphics Bitmap recycle

List of usage examples for android.graphics Bitmap recycle

Introduction

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

Prototype

public void recycle() 

Source Link

Document

Free the native object associated with this bitmap, and clear the reference to the pixel data.

Usage

From source file:com.aidy.launcher3.ui.workspace.Workspace.java

public void beginDragShared(View child, DragSource source) {
    // The drag bitmap follows the touch point around on the screen
    final Bitmap b = createDragBitmap(child, new Canvas(), DRAG_BITMAP_PADDING);

    final int bmpWidth = b.getWidth();
    final int bmpHeight = b.getHeight();

    float scale = mLauncher.getDragLayer().getLocationInDragLayer(child, mTempXY);
    int dragLayerX = Math.round(mTempXY[0] - (bmpWidth - scale * child.getWidth()) / 2);
    int dragLayerY = Math.round(mTempXY[1] - (bmpHeight - scale * bmpHeight) / 2 - DRAG_BITMAP_PADDING / 2);

    LauncherAppState app = LauncherAppState.getInstance();
    DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
    Point dragVisualizeOffset = null;
    Rect dragRect = null;/*from  ww  w. j a va2s.c  om*/
    if (child instanceof BubbleTextView || child instanceof PagedViewIcon) {
        int iconSize = grid.iconSizePx;
        int top = child.getPaddingTop();
        int left = (bmpWidth - iconSize) / 2;
        int right = left + iconSize;
        int bottom = top + iconSize;
        dragLayerY += top;
        // Note: The drag region is used to calculate drag layer offsets,
        // but the
        // dragVisualizeOffset in addition to the dragRect (the size) to
        // position the outline.
        dragVisualizeOffset = new Point(-DRAG_BITMAP_PADDING / 2, DRAG_BITMAP_PADDING / 2);
        dragRect = new Rect(left, top, right, bottom);
    } else if (child instanceof FolderIcon) {
        int previewSize = grid.folderIconSizePx;
        dragRect = new Rect(0, child.getPaddingTop(), child.getWidth(), previewSize);
    }

    // Clear the pressed state if necessary
    if (child instanceof BubbleTextView) {
        BubbleTextView icon = (BubbleTextView) child;
        icon.clearPressedOrFocusedBackground();
    }

    mDragController.startDrag(b, dragLayerX, dragLayerY, source, child.getTag(),
            DragController.DRAG_ACTION_MOVE, dragVisualizeOffset, dragRect, scale);

    if (child.getParent() instanceof ShortcutAndWidgetContainer) {
        mDragSourceInternal = (ShortcutAndWidgetContainer) child.getParent();
    }

    b.recycle();
}

From source file:com.android.launcher4.Workspace.java

public void beginExternalDragShared(View child, DragSource source) {
    LauncherAppState app = LauncherAppState.getInstance();
    DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
    int iconSize = grid.iconSizePx;

    // Notify launcher of drag start
    mLauncher.onDragStarted(child);/*w  ww .j  av a  2  s.  c  om*/

    // Compose a new drag bitmap that is of the icon size
    AtomicInteger padding = new AtomicInteger(DRAG_BITMAP_PADDING);
    final Bitmap tmpB = createDragBitmap(child, padding);
    Bitmap b = Bitmap.createBitmap(iconSize, iconSize, Bitmap.Config.ARGB_8888);
    Paint p = new Paint();
    p.setFilterBitmap(true);
    mCanvas.setBitmap(b);
    mCanvas.drawBitmap(tmpB, new Rect(0, 0, tmpB.getWidth(), tmpB.getHeight()),
            new Rect(0, 0, iconSize, iconSize), p);
    mCanvas.setBitmap(null);

    // Find the child's location on the screen
    int bmpWidth = tmpB.getWidth();
    float iconScale = (float) bmpWidth / iconSize;
    float scale = mLauncher.getDragLayer().getLocationInDragLayer(child, mTempXY) * iconScale;
    int dragLayerX = Math.round(mTempXY[0] - (bmpWidth - scale * child.getWidth()) / 2);
    int dragLayerY = Math.round(mTempXY[1]);

    // Note: The drag region is used to calculate drag layer offsets, but the
    // dragVisualizeOffset in addition to the dragRect (the size) to position the outline.
    Point dragVisualizeOffset = new Point(-padding.get() / 2, padding.get() / 2);
    Rect dragRect = new Rect(0, 0, iconSize, iconSize);

    if (child.getTag() == null || !(child.getTag() instanceof ItemInfo)) {
        String msg = "Drag started with a view that has no tag set. This "
                + "will cause a crash (issue 11627249) down the line. " + "View: " + child + "  tag: "
                + child.getTag();
        throw new IllegalStateException(msg);
    }

    // Start the drag
    DragView dv = mDragController.startDrag(b, dragLayerX, dragLayerY, source, child.getTag(),
            DragController.DRAG_ACTION_MOVE, dragVisualizeOffset, dragRect, scale);
    dv.setIntrinsicIconScaleFactor(source.getIntrinsicIconScaleFactor());

    // Recycle temporary bitmaps
    tmpB.recycle();
}

From source file:com.android.launcher3.Workspace.java

public void beginExternalDragShared(View child, DragSource source) {
    LauncherAppState app = LauncherAppState.getInstance();
    DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
    int iconSize = grid.iconSizePx;

    // Notify launcher of drag start
    mLauncher.onDragStarted(child);/*ww w  .ja v  a  2s.  com*/

    // Compose a new drag bitmap that is of the icon size
    AtomicInteger padding = new AtomicInteger(DRAG_BITMAP_PADDING);
    final Bitmap tmpB = createDragBitmap(child, padding);
    Bitmap b = Bitmap.createBitmap(iconSize, iconSize, Bitmap.Config.ARGB_8888);
    Paint p = new Paint();
    p.setFilterBitmap(true);
    mCanvas.setBitmap(b);
    mCanvas.drawBitmap(tmpB, new Rect(0, 0, tmpB.getWidth(), tmpB.getHeight()),
            new Rect(0, 0, iconSize, iconSize), p);
    mCanvas.setBitmap(null);

    // Find the child's location on the screen
    int bmpWidth = tmpB.getWidth();
    float iconScale = (float) bmpWidth / iconSize;
    float scale = mLauncher.getDragLayer().getLocationInDragLayer(child, mTempXY) * iconScale;
    int dragLayerX = Math.round(mTempXY[0] - (bmpWidth - scale * child.getWidth()) / 2);
    int dragLayerY = Math.round((float) mTempXY[1]); //bug410615 coverity problem.

    // Note: The drag region is used to calculate drag layer offsets, but the
    // dragVisualizeOffset in addition to the dragRect (the size) to position the outline.
    Point dragVisualizeOffset = new Point(-padding.get() / 2, padding.get() / 2);
    Rect dragRect = new Rect(0, 0, iconSize, iconSize);

    if (child.getTag() == null || !(child.getTag() instanceof ItemInfo)) {
        String msg = "Drag started with a view that has no tag set. This "
                + "will cause a crash (issue 11627249) down the line. " + "View: " + child + "  tag: "
                + child.getTag();
        throw new IllegalStateException(msg);
    }

    // Start the drag
    DragView dv = mDragController.startDrag(b, dragLayerX, dragLayerY, source, child.getTag(),
            DragController.DRAG_ACTION_MOVE, dragVisualizeOffset, dragRect, scale);
    dv.setIntrinsicIconScaleFactor(source.getIntrinsicIconScaleFactor());

    // Recycle temporary bitmaps
    tmpB.recycle();
}

From source file:com.auratech.launcher.Workspace.java

public void beginDragShared(View child, DragSource source) {
    // The drag bitmap follows the touch point around on the screen
    final Bitmap b = createDragBitmap(child, new Canvas(), DRAG_BITMAP_PADDING);

    final int bmpWidth = b.getWidth();
    final int bmpHeight = b.getHeight();

    float scale = mLauncher.getDragLayer().getLocationInDragLayer(child, mTempXY);
    int dragLayerX = Math.round(mTempXY[0] - (bmpWidth - scale * child.getWidth()) / 2);
    int dragLayerY = Math.round(mTempXY[1] - (bmpHeight - scale * bmpHeight) / 2 - DRAG_BITMAP_PADDING / 2);

    LauncherAppState app = LauncherAppState.getInstance();
    DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
    Point dragVisualizeOffset = null;
    Rect dragRect = null;//from w ww . jav  a  2  s.  co  m
    if (child instanceof BubbleTextView || child instanceof PagedViewIcon) {
        int iconSize = grid.iconSizePx;
        int top = child.getPaddingTop();
        int left = (bmpWidth - iconSize) / 2;
        int right = left + iconSize;
        int bottom = top + iconSize;
        dragLayerY += top;
        // Note: The drag region is used to calculate drag layer offsets, but the
        // dragVisualizeOffset in addition to the dragRect (the size) to position the outline.
        dragVisualizeOffset = new Point(-DRAG_BITMAP_PADDING / 2, DRAG_BITMAP_PADDING / 2);
        dragRect = new Rect(left, top, right, bottom);
    } else if (child instanceof FolderIcon) {
        int previewSize = grid.folderIconSizePx;
        dragRect = new Rect(0, child.getPaddingTop(), child.getWidth(), previewSize);
    }

    // Clear the pressed state if necessary
    if (child instanceof BubbleTextView) {
        BubbleTextView icon = (BubbleTextView) child;
        icon.clearPressedOrFocusedBackground();
    } else if (child instanceof FolderIcon) {
        // Dismiss the folder cling if we haven't already
        mLauncher.getLauncherClings().markFolderClingDismissed();
    }

    if (child.getTag() == null || !(child.getTag() instanceof ItemInfo)) {
        String msg = "Drag started with a view that has no tag set. This "
                + "will cause a crash (issue 11627249) down the line. " + "View: " + child + "  tag: "
                + child.getTag();
        throw new IllegalStateException(msg);
    }

    DragView dv = mDragController.startDrag(b, dragLayerX, dragLayerY, source, child.getTag(),
            DragController.DRAG_ACTION_MOVE, dragVisualizeOffset, dragRect, scale);
    dv.setIntrinsicIconScaleFactor(source.getIntrinsicIconScaleFactor());

    if (child.getParent() instanceof ShortcutAndWidgetContainer) {
        mDragSourceInternal = (ShortcutAndWidgetContainer) child.getParent();
    }

    b.recycle();
}

From source file:com.android.launcher3.Workspace.java

public void beginDragShared(View child, DragSource source) {
    child.clearFocus();//from   ww  w  .  j a va2s  .c  o m
    child.setPressed(false);

    // The outline is used to visualize where the item will land if dropped
    mDragOutline = createDragOutline(child, DRAG_BITMAP_PADDING);

    mLauncher.onDragStarted(child);
    // The drag bitmap follows the touch point around on the screen
    AtomicInteger padding = new AtomicInteger(DRAG_BITMAP_PADDING);
    final Bitmap b = createDragBitmap(child, padding);

    final int bmpWidth = b.getWidth();
    final int bmpHeight = b.getHeight();

    float scale = mLauncher.getDragLayer().getLocationInDragLayer(child, mTempXY);
    int dragLayerX = Math.round(mTempXY[0] - (bmpWidth - scale * child.getWidth()) / 2);
    int dragLayerY = Math.round(mTempXY[1] - (bmpHeight - scale * bmpHeight) / 2 - padding.get() / 2);

    LauncherAppState app = LauncherAppState.getInstance();
    DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
    Point dragVisualizeOffset = null;
    Rect dragRect = null;
    if (child instanceof BubbleTextView) {
        int iconSize = grid.iconSizePx;
        int top = child.getPaddingTop();
        int left = (bmpWidth - iconSize) / 2;
        int right = left + iconSize;
        int bottom = top + iconSize;
        dragLayerY += top;
        // Note: The drag region is used to calculate drag layer offsets, but the
        // dragVisualizeOffset in addition to the dragRect (the size) to position the outline.
        dragVisualizeOffset = new Point(-padding.get() / 2, padding.get() / 2);
        dragRect = new Rect(left, top, right, bottom);
    } else if (child instanceof FolderIcon) {
        int previewSize = grid.folderIconSizePx;
        dragRect = new Rect(0, child.getPaddingTop(), child.getWidth(), previewSize);
    }

    // Clear the pressed state if necessary
    if (child instanceof BubbleTextView) {
        BubbleTextView icon = (BubbleTextView) child;
        icon.clearPressedBackground();
    }

    if (child.getTag() == null || !(child.getTag() instanceof ItemInfo)) {
        String msg = "Drag started with a view that has no tag set. This "
                + "will cause a crash (issue 11627249) down the line. " + "View: " + child + "  tag: "
                + child.getTag();
        throw new IllegalStateException(msg);
    }

    DragView dv = mDragController.startDrag(b, dragLayerX, dragLayerY, source, child.getTag(),
            DragController.DRAG_ACTION_MOVE, dragVisualizeOffset, dragRect, scale);
    dv.setIntrinsicIconScaleFactor(source.getIntrinsicIconScaleFactor());

    if (child.getParent() instanceof ShortcutAndWidgetContainer) {
        mDragSourceInternal = (ShortcutAndWidgetContainer) child.getParent();
    }

    b.recycle();
}

From source file:com.codename1.impl.android.AndroidImplementation.java

@Override
public void releaseImage(Object image) {
    Bitmap i = (Bitmap) image;
    i.recycle();
}

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

/**
 * Called when the camera view exits./*from  w w w.  j a v  a  2 s  .  c  o  m*/
 *
 * @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.codename1.impl.android.AndroidImplementation.java

@Override
public Object createImage(String path) throws IOException {
    int IMAGE_MAX_SIZE = getDisplayHeight();
    if (exists(path)) {
        Bitmap b = null;
        try {/*w  ww .j a  va  2  s . c  om*/
            //Decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            o.inPreferredConfig = Bitmap.Config.ARGB_8888;

            InputStream fis = createFileInputStream(path);
            BitmapFactory.decodeStream(fis, null, o);
            fis.close();

            int scale = 1;
            if (o.outHeight > IMAGE_MAX_SIZE || o.outWidth > IMAGE_MAX_SIZE) {
                scale = (int) Math.pow(2, (int) Math.round(
                        Math.log(IMAGE_MAX_SIZE / (double) Math.max(o.outHeight, o.outWidth)) / Math.log(0.5)));
            }

            //Decode with inSampleSize
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inPreferredConfig = Bitmap.Config.ARGB_8888;

            if (sampleSizeOverride != -1) {
                o2.inSampleSize = sampleSizeOverride;
            } else {
                String sampleSize = Display.getInstance().getProperty("android.sampleSize", null);
                if (sampleSize != null) {
                    o2.inSampleSize = Integer.parseInt(sampleSize);
                } else {
                    o2.inSampleSize = scale;
                }
            }
            o2.inPurgeable = true;
            o2.inInputShareable = true;
            fis = createFileInputStream(path);
            b = BitmapFactory.decodeStream(fis, null, o2);
            fis.close();

            //fix rotation
            ExifInterface exif = new ExifInterface(path);
            int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                    ExifInterface.ORIENTATION_NORMAL);

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

            if (sampleSizeOverride < 0 && angle != 0) {
                Matrix mat = new Matrix();
                mat.postRotate(angle);
                Bitmap correctBmp = Bitmap.createBitmap(b, 0, 0, b.getWidth(), b.getHeight(), mat, true);
                b.recycle();
                b = correctBmp;
            }
        } catch (IOException e) {
        }
        return b;
    } else {
        InputStream in = this.getResourceAsStream(getClass(), path);
        if (in == null) {
            throw new IOException("Resource not found. " + path);
        }
        try {
            return this.createImage(in);
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (Exception ignored) {
                    ;
                }
            }
        }
    }
}

From source file:com.codename1.impl.android.AndroidImplementation.java

@Override
public com.codename1.ui.util.ImageIO getImageIO() {
    if (imIO == null) {
        imIO = new com.codename1.ui.util.ImageIO() {
            @Override//from w w w .j  av  a  2  s  .c om
            public Dimension getImageSize(String imageFilePath) throws IOException {
                BitmapFactory.Options o = new BitmapFactory.Options();
                o.inJustDecodeBounds = true;
                o.inPreferredConfig = Bitmap.Config.ARGB_8888;

                InputStream fis = createFileInputStream(imageFilePath);
                BitmapFactory.decodeStream(fis, null, o);
                fis.close();

                ExifInterface exif = new ExifInterface(imageFilePath);

                // if the image is in portrait mode
                int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                        ExifInterface.ORIENTATION_NORMAL);
                if (orientation == ExifInterface.ORIENTATION_ROTATE_90
                        || orientation == ExifInterface.ORIENTATION_ROTATE_270) {
                    return new Dimension(o.outHeight, o.outWidth);
                }
                return new Dimension(o.outWidth, o.outHeight);
            }

            private Dimension getImageSizeNoRotation(String imageFilePath) throws IOException {
                BitmapFactory.Options o = new BitmapFactory.Options();
                o.inJustDecodeBounds = true;
                o.inPreferredConfig = Bitmap.Config.ARGB_8888;

                InputStream fis = createFileInputStream(imageFilePath);
                BitmapFactory.decodeStream(fis, null, o);
                fis.close();

                return new Dimension(o.outWidth, o.outHeight);
            }

            @Override
            public void save(InputStream image, OutputStream response, String format, int width, int height,
                    float quality) throws IOException {
                Bitmap.CompressFormat f = Bitmap.CompressFormat.PNG;
                if (format == FORMAT_JPEG) {
                    f = Bitmap.CompressFormat.JPEG;
                }
                Image img = Image.createImage(image).scaled(width, height);
                Bitmap b = (Bitmap) img.getImage();
                b.compress(f, (int) (quality * 100), response);
            }

            @Override
            public String saveAndKeepAspect(String imageFilePath, String preferredOutputPath, String format,
                    int width, int height, float quality, boolean onlyDownscale, boolean scaleToFill)
                    throws IOException {
                ExifInterface exif = new ExifInterface(imageFilePath);
                Dimension d = getImageSizeNoRotation(imageFilePath);
                if (onlyDownscale) {
                    if (scaleToFill) {
                        if (d.getHeight() <= height || d.getWidth() <= width) {
                            return imageFilePath;
                        }
                    } else {
                        if (d.getHeight() <= height && d.getWidth() <= width) {
                            return imageFilePath;
                        }
                    }
                }

                float ratio = ((float) d.getWidth()) / ((float) d.getHeight());
                int heightBasedOnWidth = (int) (((float) width) / ratio);
                int widthBasedOnHeight = (int) (((float) height) * ratio);
                if (scaleToFill) {
                    if (heightBasedOnWidth >= width) {
                        height = heightBasedOnWidth;
                    } else {
                        width = widthBasedOnHeight;
                    }
                } else {
                    if (heightBasedOnWidth > width) {
                        width = widthBasedOnHeight;
                    } else {
                        height = heightBasedOnWidth;
                    }
                }
                sampleSizeOverride = Math.max(d.getWidth() / width, d.getHeight() / height);
                OutputStream im = FileSystemStorage.getInstance().openOutputStream(preferredOutputPath);
                Image i = Image.createImage(imageFilePath);
                Image newImage = i.scaled(width, height);
                int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                        ExifInterface.ORIENTATION_NORMAL);

                int angle = 0;
                switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    angle = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    angle = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    angle = 270;
                    break;
                }
                if (angle != 0) {
                    Matrix mat = new Matrix();
                    mat.postRotate(angle);
                    Bitmap b = (Bitmap) newImage.getImage();
                    Bitmap correctBmp = Bitmap.createBitmap(b, 0, 0, b.getWidth(), b.getHeight(), mat, true);
                    b.recycle();
                    newImage.dispose();
                    Image tmp = Image.createImage(correctBmp);
                    newImage = tmp;
                    save(tmp, im, format, quality);
                } else {
                    save(imageFilePath, im, format, width, height, quality);
                }
                sampleSizeOverride = -1;
                return preferredOutputPath;
            }

            @Override
            public void save(String imageFilePath, OutputStream response, String format, int width, int height,
                    float quality) throws IOException {
                Image i = Image.createImage(imageFilePath);
                Image newImage = i.scaled(width, height);
                save(newImage, response, format, quality);
                newImage.dispose();
                i.dispose();
            }

            @Override
            protected void saveImage(Image img, OutputStream response, String format, float quality)
                    throws IOException {
                Bitmap.CompressFormat f = Bitmap.CompressFormat.PNG;
                if (format == FORMAT_JPEG) {
                    f = Bitmap.CompressFormat.JPEG;
                }
                Bitmap b = (Bitmap) img.getImage();
                b.compress(f, (int) (quality * 100), response);
            }

            @Override
            public boolean isFormatSupported(String format) {
                return format == FORMAT_JPEG || format == FORMAT_PNG;
            }
        };
    }
    return imIO;
}