Example usage for android.media ThumbnailUtils extractThumbnail

List of usage examples for android.media ThumbnailUtils extractThumbnail

Introduction

In this page you can find the example usage for android.media ThumbnailUtils extractThumbnail.

Prototype

public static Bitmap extractThumbnail(Bitmap source, int width, int height) 

Source Link

Document

Creates a centered bitmap of the desired size.

Usage

From source file:cw.kop.autobackground.settings.WearSettingsFragment.java

private void loadImageFile() {
    new Thread(new Runnable() {
        @Override// w  w  w .  ja va 2s.c  om
        public void run() {
            float sideLength = surfaceView.getWidth();
            Log.i(TAG, "sideLength: " + sideLength);
            if (sideLength > 0) {

                if (FileHandler.getCurrentBitmapFile() != null) {

                    BitmapFactory.Options options = new BitmapFactory.Options();
                    options.inJustDecodeBounds = true;
                    BitmapFactory.decodeFile(FileHandler.getCurrentBitmapFile().getAbsolutePath(), options);
                    options.inJustDecodeBounds = false;

                    int sampleSize = 1;

                    float longestLength = options.outWidth > options.outHeight ? options.outWidth
                            : options.outHeight;

                    while (longestLength / (sampleSize + 1) > sideLength) {
                        sampleSize++;
                    }
                    options.inSampleSize = sampleSize;

                    final Bitmap bitmap = ThumbnailUtils
                            .extractThumbnail(
                                    BitmapFactory.decodeFile(
                                            FileHandler.getCurrentBitmapFile().getAbsolutePath(), options),
                                    Math.round(sideLength), Math.round(sideLength));

                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            if (imageBitmap != null) {
                                try {
                                    imageBitmap.recycle();
                                } catch (Exception e) {

                                }
                            }
                            imageBitmap = bitmap;
                            redraw();
                        }
                    });

                }
            }
        }
    }).start();
}

From source file:com.mobicage.rogerthat.util.ui.UIUtils.java

public static Bitmap createThumbnail(Bitmap source, int maxWidthOrHeight) {
    if (source == null) {
        return null;
    }/*from   w w w. j a v a  2  s.c o m*/
    final int w;
    final int h;
    if (source.getWidth() > source.getHeight()) {
        w = maxWidthOrHeight;
        h = w * source.getHeight() / source.getWidth();
    } else {
        h = maxWidthOrHeight;
        w = h * source.getWidth() / source.getHeight();
    }
    return ThumbnailUtils.extractThumbnail(source, w, h);
}

From source file:com.android.contacts.common.ContactPhotoManager.java

/**
 * If necessary, decodes bytes stored in the holder to Bitmap.  As long as the
 * bitmap is held either by {@link #mBitmapCache} or by a soft reference in
 * the holder, it will not be necessary to decode the bitmap.
 *///from ww w . j  av a2  s  . c om
private static void inflateBitmap(BitmapHolder holder, int requestedExtent) {
    final int sampleSize = BitmapUtil.findOptimalSampleSize(holder.originalSmallerExtent, requestedExtent);
    byte[] bytes = holder.bytes;
    if (bytes == null || bytes.length == 0) {
        return;
    }

    if (sampleSize == holder.decodedSampleSize) {
        // Check the soft reference.  If will be retained if the bitmap is also
        // in the LRU cache, so we don't need to check the LRU cache explicitly.
        if (holder.bitmapRef != null) {
            holder.bitmap = holder.bitmapRef.get();
            if (holder.bitmap != null) {
                return;
            }
        }
    }

    try {
        Bitmap bitmap = BitmapUtil.decodeBitmapFromBytes(bytes, sampleSize);

        // TODO: As a temporary workaround while framework support is being added to
        // clip non-square bitmaps into a perfect circle, manually crop the bitmap into
        // into a square if it will be displayed as a thumbnail so that it can be cropped
        // into a circle.
        final int height = bitmap.getHeight();
        final int width = bitmap.getWidth();

        // The smaller dimension of a scaled bitmap can range from anywhere from 0 to just
        // below twice the length of a thumbnail image due to the way we calculate the optimal
        // sample size.
        if (height != width && Math.min(height, width) <= mThumbnailSize * 2) {
            final int dimension = Math.min(height, width);
            bitmap = ThumbnailUtils.extractThumbnail(bitmap, dimension, dimension);
        }
        // make bitmap mutable and draw size onto it
        if (DEBUG_SIZES) {
            Bitmap original = bitmap;
            bitmap = bitmap.copy(bitmap.getConfig(), true);
            original.recycle();
            Canvas canvas = new Canvas(bitmap);
            Paint paint = new Paint();
            paint.setTextSize(16);
            paint.setColor(Color.BLUE);
            paint.setStyle(Style.FILL);
            canvas.drawRect(0.0f, 0.0f, 50.0f, 20.0f, paint);
            paint.setColor(Color.WHITE);
            paint.setAntiAlias(true);
            canvas.drawText(bitmap.getWidth() + "/" + sampleSize, 0, 15, paint);
        }

        holder.decodedSampleSize = sampleSize;
        holder.bitmap = bitmap;
        holder.bitmapRef = new SoftReference<Bitmap>(bitmap);
        if (DEBUG) {
            Log.d(TAG, "inflateBitmap " + btk(bytes.length) + " -> " + bitmap.getWidth() + "x"
                    + bitmap.getHeight() + ", " + btk(bitmap.getByteCount()));
        }
    } catch (OutOfMemoryError e) {
        // Do nothing - the photo will appear to be missing
    }
}

From source file:com.keylesspalace.tusky.activity.ComposeActivity.java

private void pickMedia(Uri uri, long mediaSize) {
    ContentResolver contentResolver = getContentResolver();
    if (mediaSize == MEDIA_SIZE_UNKNOWN) {
        displayTransientError(R.string.error_media_upload_opening);
        return;/*from w  ww  .ja  va 2 s . c o  m*/
    }
    String mimeType = contentResolver.getType(uri);
    if (mimeType != null) {
        String topLevelType = mimeType.substring(0, mimeType.indexOf('/'));
        switch (topLevelType) {
        case "video": {
            if (mediaSize > STATUS_MEDIA_SIZE_LIMIT) {
                displayTransientError(R.string.error_media_upload_size);
                return;
            }
            if (mediaQueued.size() > 0 && mediaQueued.get(0).type == QueuedMedia.Type.IMAGE) {
                displayTransientError(R.string.error_media_upload_image_or_video);
                return;
            }
            MediaMetadataRetriever retriever = new MediaMetadataRetriever();
            retriever.setDataSource(this, uri);
            Bitmap source = retriever.getFrameAtTime();
            Bitmap bitmap = ThumbnailUtils.extractThumbnail(source, 128, 128);
            source.recycle();
            addMediaToQueue(QueuedMedia.Type.VIDEO, bitmap, uri, mediaSize);
            break;
        }
        case "image": {
            InputStream stream;
            try {
                stream = contentResolver.openInputStream(uri);
            } catch (FileNotFoundException e) {
                displayTransientError(R.string.error_media_upload_opening);
                return;
            }
            Bitmap source = BitmapFactory.decodeStream(stream);
            Bitmap bitmap = ThumbnailUtils.extractThumbnail(source, 128, 128);
            source.recycle();
            try {
                if (stream != null) {
                    stream.close();
                }
            } catch (IOException e) {
                bitmap.recycle();
                displayTransientError(R.string.error_media_upload_opening);
                return;
            }
            addMediaToQueue(QueuedMedia.Type.IMAGE, bitmap, uri, mediaSize);
            break;
        }
        default: {
            displayTransientError(R.string.error_media_upload_type);
            break;
        }
        }
    } else {
        displayTransientError(R.string.error_media_upload_type);
    }
}

From source file:com.fa.mastodon.activity.ComposeActivity.java

private void pickMedia(Uri uri, long mediaSize) {
    ContentResolver contentResolver = getContentResolver();
    if (mediaSize == MEDIA_SIZE_UNKNOWN) {
        displayTransientError(R.string.error_media_upload_opening);
        return;//from w  w w. j av  a  2  s. co  m
    }
    String mimeType = contentResolver.getType(uri);
    if (mimeType != null) {
        String topLevelType = mimeType.substring(0, mimeType.indexOf('/'));
        switch (topLevelType) {
        case "video": {
            if (mediaSize > STATUS_MEDIA_SIZE_LIMIT) {
                displayTransientError(R.string.error_media_upload_size);
                return;
            }
            if (mediaQueued.size() > 0 && mediaQueued.get(0).type == QueuedMedia.Type.IMAGE) {
                displayTransientError(R.string.error_media_upload_image_or_video);
                return;
            }
            MediaMetadataRetriever retriever = new MediaMetadataRetriever();
            retriever.setDataSource(this, uri);
            Bitmap source = retriever.getFrameAtTime();
            Bitmap bitmap = ThumbnailUtils.extractThumbnail(source, THUMBNAIL_SIZE, THUMBNAIL_SIZE);
            source.recycle();
            addMediaToQueue(QueuedMedia.Type.VIDEO, bitmap, uri, mediaSize);
            break;
        }
        case "image": {
            InputStream stream;
            try {
                stream = contentResolver.openInputStream(uri);
            } catch (FileNotFoundException e) {
                displayTransientError(R.string.error_media_upload_opening);
                return;
            }

            Bitmap source = BitmapFactory.decodeStream(stream);
            Bitmap bitmap = ThumbnailUtils.extractThumbnail(source, THUMBNAIL_SIZE, THUMBNAIL_SIZE);
            source.recycle();
            try {
                if (stream != null) {
                    stream.close();
                }
            } catch (IOException e) {
                bitmap.recycle();
                displayTransientError(R.string.error_media_upload_opening);
                return;
            }
            addMediaToQueue(QueuedMedia.Type.IMAGE, bitmap, uri, mediaSize);
            break;
        }
        default: {
            displayTransientError(R.string.error_media_upload_type);
            break;
        }
        }
    } else {
        displayTransientError(R.string.error_media_upload_type);
    }
}

From source file:com.creativeongreen.imageeffects.MainActivity.java

public void selectImage() {

    if (selectImageClicked) {
        lv1.setVisibility(View.GONE);
        selectImageClicked = false;/*from ww  w.  j a v a 2 s  .  c  o m*/
        return;
    } else {
        lv1.setVisibility(View.VISIBLE);
        selectImageClicked = true;
    }

    String filePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString();
    final File pictureStorageDir = new File(filePath, DIR_STORAGE_IMAGE);
    if (!pictureStorageDir.exists()) {
        Toast.makeText(this, getString(R.string.msg_no_image_file), Toast.LENGTH_SHORT).show();
        lv1.setVisibility(View.GONE);
        selectImageClicked = false;
        return;
    }

    File pictureListFiles[] = pictureStorageDir.listFiles(new FileExtensionFilter());

    if (pictureListFiles.length == 0) {
        Toast.makeText(this, getString(R.string.msg_no_image_file), Toast.LENGTH_SHORT).show();
        return;
    }

    final ArrayList<FileListEntry> alPictures = new ArrayList<FileListEntry>();

    int thumbWidth = 64, thumbHeight = 64;
    for (int i = 0; i < pictureListFiles.length; i++) {
        String file = pictureListFiles[i].getName();
        String fullPathFile = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
                .getAbsolutePath().toString() + File.separator + DIR_STORAGE_IMAGE + File.separator + file;
        String fileSize = new DecimalFormat("#,##0.0#").format(pictureListFiles[i].length() / 1024.0) + " KB";

        BitmapFactory.Options bmFactoryOptions = new BitmapFactory.Options();
        bmFactoryOptions.inJustDecodeBounds = true; // the decoder will return null (no bitmap)
        BitmapFactory.decodeFile(fullPathFile, bmFactoryOptions);

        FileListEntry mFileEntry = null;
        try {
            Bitmap bmThumbnail = ThumbnailUtils.extractThumbnail(BitmapFactory.decodeFile(fullPathFile),
                    thumbWidth, thumbHeight);
            mFileEntry = new FileListEntry(bmThumbnail, pictureListFiles[i].getName(), "\nSize: " + fileSize
                    + "\nDimensions: " + bmFactoryOptions.outWidth + " x " + bmFactoryOptions.outHeight);
        } catch (Throwable e) {
            // handle OOM error on BitmapFactory
            mFileEntry = new FileListEntry(null, pictureListFiles[i].getName(), "\nSize: " + fileSize);
        }

        alPictures.add(mFileEntry);
    }

    FileListAdapter adapter = new FileListAdapter(getApplicationContext(), R.layout.file_list_entry,
            alPictures);

    lv1.setAdapter(adapter);

    // listening to single listitem click
    lv1.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            // getting listitem index
            lv1.setVisibility(View.GONE);
            selectImageClicked = false;
            bmImageSrc = getBitmapFromExternalStorage(this, alPictures.get(position).getFilename());
            iv1.setImageBitmap(bmImageSrc);
        }

    });
}

From source file:com.dycody.android.idealnote.DetailFragment.java

private void replacePlayingAudioBitmap(View v) {
    Drawable d = ((ImageView) v.findViewById(R.id.gridview_item_picture)).getDrawable();
    if (BitmapDrawable.class.isAssignableFrom(d.getClass())) {
        recordingBitmap = ((BitmapDrawable) d).getBitmap();
    } else {/*www .j a  va  2 s  .co  m*/
        recordingBitmap = ((GlideBitmapDrawable) d.getCurrent()).getBitmap();
    }
    ((ImageView) v.findViewById(R.id.gridview_item_picture)).setImageBitmap(ThumbnailUtils.extractThumbnail(
            BitmapFactory.decodeResource(mainActivity.getResources(), R.drawable.stop),
            Constants.THUMBNAIL_SIZE, Constants.THUMBNAIL_SIZE));
}

From source file:com.aimfire.demo.CamcorderActivity.java

private void generateThumbAndPreview(String filePath) {
    if (BuildConfig.DEBUG)
        Log.d(TAG, "generateThumbAndPreview");

    String movieNameNoExt = MediaScanner.getMovieNameNoExt(filePath);
    String previewPath = MainConsts.MEDIA_3D_THUMB_PATH + movieNameNoExt + ".jpeg";
    String thumbPath = MainConsts.MEDIA_3D_THUMB_PATH + movieNameNoExt + ".jpg";

    MediaMetadataRetriever retriever = new MediaMetadataRetriever();

    Bitmap bitmap = null;/*from  www . j  ava  2  s  . co  m*/

    try {
        FileInputStream inputStream = new FileInputStream(filePath);
        retriever.setDataSource(inputStream.getFD());
        inputStream.close();

        bitmap = retriever.getFrameAtTime(0L, MediaMetadataRetriever.OPTION_CLOSEST_SYNC);
        retriever.release();

        if (bitmap != null) {
            FileOutputStream out = null;
            out = new FileOutputStream(previewPath);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 95, out);
            out.close();

            Bitmap thumbnail = ThumbnailUtils.extractThumbnail(bitmap, MainConsts.THUMBNAIL_SIZE,
                    MainConsts.THUMBNAIL_SIZE);
            out = new FileOutputStream(thumbPath);
            thumbnail.compress(Bitmap.CompressFormat.JPEG, 100, out);
            out.close();
        }
    } catch (Exception e) {
        if (BuildConfig.DEBUG)
            Log.e(TAG, "generateThumbAndPreview: exception" + e.getMessage());
        retriever.release();
        FirebaseCrash.report(e);
    }
}