Example usage for android.graphics BitmapFactory decodeFileDescriptor

List of usage examples for android.graphics BitmapFactory decodeFileDescriptor

Introduction

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

Prototype

public static Bitmap decodeFileDescriptor(FileDescriptor fd, Rect outPadding, Options opts) 

Source Link

Document

Decode a bitmap from the file descriptor.

Usage

From source file:mobisocial.musubi.objects.PictureObj.java

/**
 * Pass in one of raw or fd as the source of the image.
 * Not thread safe, only call on the ui thread.
 *//* w w  w  .  j  a v  a2 s  . c om*/
protected static void bindImageToView(Context context, ImageView imageView, byte[] raw, FileDescriptor fd) {
    // recycle old images (vs. caching in ImageCache)
    if (imageView.getDrawable() != null) {
        BitmapDrawable d = (BitmapDrawable) imageView.getDrawable();
        if (d != null && d.getBitmap() != null) {
            d.getBitmap().recycle();
        }
    }

    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    if (fd != null) {
        BitmapFactory.decodeFileDescriptor(fd, null, options);
    } else {
        BitmapFactory.decodeByteArray(raw, 0, raw.length, options);
    }
    Resources res = context.getResources();

    float scaleFactor;
    if (res.getBoolean(R.bool.is_tablet)) {
        scaleFactor = 3.0f;
    } else {
        scaleFactor = 2.0f;
    }
    DisplayMetrics dm = context.getResources().getDisplayMetrics();
    int pixels = dm.widthPixels;
    if (dm.heightPixels < pixels) {
        pixels = dm.heightPixels;
    }
    int width = (int) (pixels / scaleFactor);
    int height = (int) ((float) width / options.outWidth * options.outHeight);
    int max_height = (int) (AppStateObj.MAX_HEIGHT * dm.density);
    if (height > max_height) {
        width = width * max_height / height;
        height = max_height;
    }

    options.inJustDecodeBounds = false;
    options.inTempStorage = getTempData();
    options.inSampleSize = 1;
    //TODO: lame, can just compute
    while (options.outWidth / (options.inSampleSize + 1) >= width
            && options.outHeight / (options.inSampleSize + 1) >= height) {
        options.inSampleSize++;
    }
    options.inPurgeable = true;
    options.inInputShareable = true;

    Bitmap bm;
    if (fd != null) {
        bm = BitmapFactory.decodeFileDescriptor(fd, null, options);
    } else {
        bm = BitmapFactory.decodeByteArray(raw, 0, raw.length, options);
    }
    imageView.getLayoutParams().width = width + 13;
    imageView.getLayoutParams().height = height + 14;
    imageView.setImageBitmap(bm);
}

From source file:com.tangjd.displayingbitmaps.util.ImageResizer.java

/**
 * Decode and sample down a bitmap from a file input stream to the requested width and height.
 *
 * @param fileDescriptor The file descriptor to read from
 * @param reqWidth The requested width of the resulting bitmap
 * @param reqHeight The requested height of the resulting bitmap
 * @param cache The ImageCache used to find candidate bitmaps for use with inBitmap
 * @return A bitmap sampled down from the original with the same aspect ratio and dimensions
 *         that are equal to or greater than the requested width and height
 *///from  ww  w  .j  a  v  a 2  s. co m
public static Bitmap decodeSampledBitmapFromDescriptor(FileDescriptor fileDescriptor, int reqWidth,
        int reqHeight, ImageCache cache) {

    // First decode with inJustDecodeBounds=true to check dimensions
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFileDescriptor(fileDescriptor, null, options);

    // Calculate inSampleSize
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;

    // If we're running on Honeycomb or newer, try to use inBitmap
    if (Utils.hasHoneycomb()) {
        addInBitmapOptions(options, cache);
    }

    options.inPreferredConfig = Bitmap.Config.RGB_565;
    return BitmapFactory.decodeFileDescriptor(fileDescriptor, null, options);
}

From source file:com.example.fragmentexercise.ContactsAdapter.java

/**
 * Load a contact photo thumbnail and return it as a Bitmap, resizing the
 * image to the provided image dimensions as needed.
 * //w ww  .  ja v a  2s. co m
 * @param photoData
 *            photo ID Prior to Honeycomb, the contact's _ID value. For
 *            Honeycomb and later, the value of PHOTO_THUMBNAIL_URI.
 * @return A thumbnail Bitmap, sized to the provided width and height.
 *         Returns null if the thumbnail is not found.
 */
private Bitmap loadContactPhotoThumbnail(String photoData) {
    // Creates an asset file descriptor for the thumbnail file.
    AssetFileDescriptor afd = null;
    // try-catch block for file not found
    try {
        // Creates a holder for the URI.
        Uri thumbUri;
        // If Android 3.0 or later
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            // Sets the URI from the incoming PHOTO_THUMBNAIL_URI
            thumbUri = Uri.parse(photoData);
        } else {
            // Prior to Android 3.0, constructs a photo Uri using _ID
            /*
             * Creates a contact URI from the Contacts content URI incoming
             * photoData (_ID)
             */
            final Uri contactUri = Uri.withAppendedPath(Contacts.CONTENT_URI, photoData);
            /*
             * Creates a photo URI by appending the content URI of
             * Contacts.Photo.
             */
            thumbUri = Uri.withAppendedPath(contactUri, Photo.CONTENT_DIRECTORY);
        }

        /*
         * Retrieves an AssetFileDescriptor object for the thumbnail URI
         * using ContentResolver.openAssetFileDescriptor
         */
        afd = mContext.getContentResolver().openAssetFileDescriptor(thumbUri, "r");
        /*
         * Gets a file descriptor from the asset file descriptor. This
         * object can be used across processes.
         */
        FileDescriptor fileDescriptor = afd.getFileDescriptor();
        // Decode the photo file and return the result as a Bitmap
        // If the file descriptor is valid
        if (fileDescriptor != null) {
            // Decodes the bitmap
            return BitmapFactory.decodeFileDescriptor(fileDescriptor, null, null);
        }
        // If the file isn't found
    } catch (FileNotFoundException e) {
        /*
         * Handle file not found errors
         */
    }
    // In all cases, close the asset file descriptor
    finally {
        if (afd != null) {
            try {
                afd.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return null;
}

From source file:com.benefit.buy.library.http.query.callback.BitmapAjaxCallback.java

private static Bitmap decodeFile(String path, BitmapFactory.Options options, boolean rotate) {
    Bitmap result = null;/*from www  . j  av  a 2s.c om*/
    if (options == null) {
        options = new Options();
    }
    options.inInputShareable = true;
    options.inPurgeable = true;
    FileInputStream fis = null;
    try {
        fis = new FileInputStream(path);
        FileDescriptor fd = fis.getFD();
        result = BitmapFactory.decodeFileDescriptor(fd, null, options);
        if ((result != null) && rotate) {
            result = rotate(path, result);
        }
    } catch (IOException e) {
        AQUtility.report(e);
    } finally {
        AQUtility.close(fis);
    }
    return result;
}

From source file:com.amachikhin.vkmachikhin.utils.image_cache.ImageResizer.java

/**
 * Decode and sample down a bitmap from a file input stream to the requested width and height.
 *
 * @param fileDescriptor The file descriptor to read from
 * @param reqWidth       The requested width of the resulting bitmap
 * @param reqHeight      The requested height of the resulting bitmap
 * @param cache          The ImageCache used to find candidate bitmaps for use with inBitmap
 * @return A bitmap sampled down from the original with the same aspect ratio and dimensions
 * that are equal to or greater than the requested width and height
 *///ww  w.jav a 2 s  . c  o  m
public static Bitmap decodeSampledBitmapFromDescriptor(FileDescriptor fileDescriptor, int reqWidth,
        int reqHeight, ImageCache cache) {

    // First decode with inJustDecodeBounds=true to check dimensions
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFileDescriptor(fileDescriptor, null, options);

    if (reqHeight < 0 || reqWidth < 0) {
        options.inDensity = mInDensity;
    } else {
        // Calculate inSampleSize
        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
    }

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;

    addInBitmapOptions(options, cache);

    return BitmapFactory.decodeFileDescriptor(fileDescriptor, null, options);
}

From source file:com.appbase.androidquery.callback.BitmapAjaxCallback.java

private static Bitmap decodeFile(String path, BitmapFactory.Options options, boolean rotate) {

    Bitmap result = null;// w  w w.jav a  2  s . c  om

    if (options == null) {
        options = new Options();
    }

    options.inInputShareable = true;
    options.inPurgeable = true;

    FileInputStream fis = null;

    try {

        fis = new FileInputStream(path);
        FileDescriptor fd = fis.getFD();
        result = BitmapFactory.decodeFileDescriptor(fd, null, options);

        if (result != null && rotate) {
            result = rotate(path, result);
        }

    } catch (IOException e) {
        AQUtility.report(e);
    } finally {
        AQUtility.close(fis);
    }

    return result;

}

From source file:com.pavlospt.rxfile.RxFile.java

private static Observable<Bitmap> getThumbnailFromUriWithSizeAndKind(final Context context, final Uri data,
        final int requiredWidth, final int requiredHeight, final int kind) {
    return Observable.fromCallable(new Func0<Bitmap>() {
        @Override//from   w  w w.j  a v a2 s.com
        public Bitmap call() {
            Bitmap bitmap = null;
            ParcelFileDescriptor parcelFileDescriptor;
            final BitmapFactory.Options options = new BitmapFactory.Options();
            if (requiredWidth > 0 && requiredHeight > 0) {
                options.inJustDecodeBounds = true;
                options.inSampleSize = calculateInSampleSize(options, requiredWidth, requiredHeight);
                options.inJustDecodeBounds = false;
            }
            if (!isMediaUri(data)) {
                logDebug("Not a media uri:" + data);
                if (isGoogleDriveDocument(data)) {
                    logDebug("Google Drive Uri:" + data);
                    DocumentFile file = DocumentFile.fromSingleUri(context, data);
                    if (file.getType().startsWith(Constants.IMAGE_TYPE)
                            || file.getType().startsWith(Constants.VIDEO_TYPE)) {
                        logDebug("Google Drive Uri:" + data + " (Video or Image)");
                        try {
                            parcelFileDescriptor = context.getContentResolver().openFileDescriptor(data,
                                    Constants.READ_MODE);
                            FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
                            bitmap = BitmapFactory.decodeFileDescriptor(fileDescriptor, null, options);
                            parcelFileDescriptor.close();
                            return bitmap;
                        } catch (IOException e) {
                            logError("Exception:" + e.getMessage() + " line: 209");
                            e.printStackTrace();
                        }
                    }
                } else if (data.getScheme().equals(Constants.FILE)) {
                    logDebug("Dropbox or other DocumentsProvider Uri:" + data);
                    try {
                        parcelFileDescriptor = context.getContentResolver().openFileDescriptor(data,
                                Constants.READ_MODE);
                        FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
                        bitmap = BitmapFactory.decodeFileDescriptor(fileDescriptor, null, options);
                        parcelFileDescriptor.close();
                        return bitmap;
                    } catch (IOException e) {
                        logError("Exception:" + e.getMessage() + " line: 223");
                        e.printStackTrace();
                    }
                } else {
                    try {
                        parcelFileDescriptor = context.getContentResolver().openFileDescriptor(data,
                                Constants.READ_MODE);
                        FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
                        bitmap = BitmapFactory.decodeFileDescriptor(fileDescriptor, null, options);
                        parcelFileDescriptor.close();
                        return bitmap;
                    } catch (IOException e) {
                        logError("Exception:" + e.getMessage() + " line: 235");
                        e.printStackTrace();
                    }
                }
            } else {
                logDebug("Uri for thumbnail:" + data);
                String[] parts = data.getLastPathSegment().split(":");
                String fileId = parts[1];
                Cursor cursor = null;
                try {
                    cursor = context.getContentResolver().query(data, null, null, null, null);
                    if (cursor != null) {
                        logDebug("Cursor size:" + cursor.getCount());
                        if (cursor.moveToFirst()) {
                            if (data.toString().contains(Constants.VIDEO)) {
                                bitmap = MediaStore.Video.Thumbnails.getThumbnail(context.getContentResolver(),
                                        Long.parseLong(fileId), kind, options);
                            } else if (data.toString().contains(Constants.IMAGE)) {
                                bitmap = MediaStore.Images.Thumbnails.getThumbnail(context.getContentResolver(),
                                        Long.parseLong(fileId), kind, options);
                            }
                        }
                    }
                    return bitmap;
                } catch (Exception e) {
                    logError("Exception:" + e.getMessage() + " line: 266");
                } finally {
                    if (cursor != null)
                        cursor.close();
                }
            }
            return bitmap;
        }
    });
}

From source file:inc.bait.jubilee.model.helper.util.ImgLoader.java

public static Bitmap decodeSampledBitmapFromDescriptor(FileDescriptor fileDescriptor, int reqWidth,
        int reqHeight) {

    // First decode with inJustDecodeBounds=true to check dimensions
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;//www .ja va2 s .co m
    BitmapFactory.decodeFileDescriptor(fileDescriptor, null, options);

    // Calculate inSampleSize
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

    options.inJustDecodeBounds = false;
    return BitmapFactory.decodeFileDescriptor(fileDescriptor, null, options);
}

From source file:com.beacon.afterui.views.gallery.ImageCache.java

public static Bitmap decodeSampledBitmapFromDescriptor(FileDescriptor fileDescriptor, int reqWidth,
        int reqHeight, ImageCache cache) {

    // First decode with inJustDecodeBounds=true to check dimensions
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;/*from  w w  w. ja v a  2  s . c om*/
    BitmapFactory.decodeFileDescriptor(fileDescriptor, null, options);

    // Calculate inSampleSize
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;

    // If we're running on Honeycomb or newer, try to use inBitmap
    if (Utils.hasHoneycomb()) {
        addInBitmapOptions(options, cache);
    }

    return BitmapFactory.decodeFileDescriptor(fileDescriptor, null, options);
}

From source file:at.flack.activity.NewFbContactActivity.java

public final Bitmap fetchThumbnail(Context context, Uri uri) {
    if (uri == null)
        return null;
    FileDescriptor fileDescriptor;
    try {/*from w w w. ja  va2 s.  c  o m*/
        fileDescriptor = context.getContentResolver().openAssetFileDescriptor(uri, "r").getFileDescriptor();
    } catch (FileNotFoundException e) {
        return null;
    }

    if (fileDescriptor != null) {
        return BitmapFactory.decodeFileDescriptor(fileDescriptor, null, null);
    }
    return null;
}