Java 类android.media.ThumbnailUtils 实例源码

项目:MediaChooser    文件:GalleryCache.java   
@Override
protected Bitmap doInBackground(Void... params) {
    Bitmap bitmap = null;
    try {
        bitmap = ThumbnailUtils.createVideoThumbnail(mImageKey, Thumbnails.FULL_SCREEN_KIND);

        if (bitmap != null) {
            bitmap = Bitmap.createScaledBitmap(bitmap, mMaxWidth, mMaxWidth, false);
            addBitmapToCache(mImageKey, bitmap);
            return bitmap;
        }
        return null;
    } catch (Exception e) {
        if (e != null) {
            e.printStackTrace();
        }
        return null;
    }
}
项目:GitHub    文件:LocalVideoThumbnailProducerTest.java   
@Before
public void setUp() throws Exception {
  MockitoAnnotations.initMocks(this);
  mExecutor = new TestExecutorService(new FakeClock());
  mLocalVideoThumbnailProducer = new LocalVideoThumbnailProducer(
      mExecutor,
      RuntimeEnvironment.application.getContentResolver());
  mFile = new File(RuntimeEnvironment.application.getExternalFilesDir(null), TEST_FILENAME);

  mockStatic(ThumbnailUtils.class);
  mProducerContext = new SettableProducerContext(
      mImageRequest,
      mRequestId,
      mProducerListener,
      mock(Object.class),
      ImageRequest.RequestLevel.FULL_FETCH,
      false,
      false,
      Priority.MEDIUM);
  when(mImageRequest.getSourceFile()).thenReturn(mFile);
}
项目:GitHub    文件:LocalVideoThumbnailProducerTest.java   
@Test
public void testLocalVideoMicroThumbnailReturnsNull() throws Exception {
  when(mProducerListener.requiresExtraMap(mRequestId)).thenReturn(true);
  when(
      android.media.ThumbnailUtils.createVideoThumbnail(
          mFile.getPath(), MediaStore.Images.Thumbnails.MICRO_KIND))
      .thenReturn(null);
  mLocalVideoThumbnailProducer.produceResults(mConsumer, mProducerContext);
  mExecutor.runUntilIdle();
  verify(mConsumer).onNewResult(null, Consumer.IS_LAST);
  verify(mProducerListener).onProducerStart(mRequestId, PRODUCER_NAME);
  Map<String, String> thumbnailNotFoundMap =
      ImmutableMap.of(LocalVideoThumbnailProducer.CREATED_THUMBNAIL, "false");
  verify(mProducerListener).onProducerFinishWithSuccess(
      mRequestId, PRODUCER_NAME, thumbnailNotFoundMap);
  verify(mProducerListener).onUltimateProducerReached(mRequestId, PRODUCER_NAME, false);
}
项目:SIGHT-For-the-Blind    文件:Helper.java   
public static float[] getPixels(Bitmap bitmap, int[] intValues, float[] floatValues) {
    if (bitmap.getWidth() != IMAGE_SIZE || bitmap.getHeight() != IMAGE_SIZE) {
        // rescale the bitmap if needed
        bitmap = ThumbnailUtils.extractThumbnail(bitmap, IMAGE_SIZE, IMAGE_SIZE);
    }

    bitmap.getPixels(intValues, 0, bitmap.getWidth(), 0, 0, bitmap.getWidth(), bitmap.getHeight());

    // Preprocess the image data from 0-255 int to normalized float based
    // on the provided parameters.
    for (int i = 0; i < intValues.length; ++i) {
        final int val = intValues[i];
        floatValues[i * 3] = (((val >> 16) & 0xFF) - IMAGE_MEAN) / IMAGE_STD;
        floatValues[i * 3 + 1] = (((val >> 8) & 0xFF) - IMAGE_MEAN) / IMAGE_STD;
        floatValues[i * 3 + 2] = ((val & 0xFF) - IMAGE_MEAN) / IMAGE_STD;
    }
    return floatValues;
}
项目:MediaNotification    文件:CircleImageView.java   
@Override
public void onDraw(Canvas canvas) {
    if (bitmap != null) {
        int size = Math.min(canvas.getWidth(), canvas.getHeight());
        if (size != this.size) {
            this.size = size;
            bitmap = ThumbnailUtils.extractThumbnail(bitmap, size, size);

            RoundedBitmapDrawable roundedBitmapDrawable = RoundedBitmapDrawableFactory.create(getResources(), bitmap);

            roundedBitmapDrawable.setCornerRadius(size / 2);
            roundedBitmapDrawable.setAntiAlias(true);

            bitmap = ImageUtils.drawableToBitmap(roundedBitmapDrawable);
        }

        canvas.drawBitmap(bitmap, 0, 0, paint);
    }
}
项目:AndroidBackendlessChat    文件:ImageUtils.java   
/**
 * Constructing a bitmap that contains the given bitmaps(max is three).
 *
 * For given two bitmaps the result will be a half and half bitmap.
 *
 * For given three the result will be a half of the first bitmap and the second
 * half will be shared equally by the two others.
 *
 * @param  bitmaps Array of bitmaps to use for the final image.
 * @param  width width of the final image, A positive number.
 * @param  height height of the final image, A positive number.
 *
 * @return A Bitmap containing the given images.
 * */
@Nullable public static Bitmap getMixImagesBitmap(@Size(min = 1) int width,@Size(min = 1) int height, @NonNull Bitmap...bitmaps){

    if (height == 0 || width == 0) return null;

    if (bitmaps.length == 0) return null;

    Bitmap finalImage = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(finalImage);

    Paint paint = new Paint(Paint.FILTER_BITMAP_FLAG);

    if (bitmaps.length == 2){
        canvas.drawBitmap(ThumbnailUtils.extractThumbnail(bitmaps[0], width/2, height), 0, 0, paint);
        canvas.drawBitmap(ThumbnailUtils.extractThumbnail(bitmaps[1], width/2, height), width/2, 0, paint);
    }
    else{
        canvas.drawBitmap(ThumbnailUtils.extractThumbnail(bitmaps[0], width/2, height), 0, 0, paint);
        canvas.drawBitmap(ThumbnailUtils.extractThumbnail(bitmaps[1], width/2, height/2), width/2, 0, paint);
        canvas.drawBitmap(ThumbnailUtils.extractThumbnail(bitmaps[2], width/2, height/2), width/2, height/2, paint);
    }

    return finalImage;
}
项目:androidthings-imageclassifier    文件:Helper.java   
public static float[] getPixels(Bitmap bitmap) {
    if (bitmap.getWidth() != IMAGE_SIZE || bitmap.getHeight() != IMAGE_SIZE) {
        // rescale the bitmap if needed
        bitmap = ThumbnailUtils.extractThumbnail(bitmap, IMAGE_SIZE, IMAGE_SIZE);
    }
    int[] intValues = new int[IMAGE_SIZE * IMAGE_SIZE];

    bitmap.getPixels(intValues, 0, bitmap.getWidth(), 0, 0, bitmap.getWidth(), bitmap.getHeight());

    float[] floatValues = new float[IMAGE_SIZE * IMAGE_SIZE * 3];
    // Preprocess the image data from 0-255 int to normalized float based
    // on the provided parameters.
    for (int i = 0; i < intValues.length; ++i) {
        final int val = intValues[i];
        floatValues[i * 3] = (((val >> 16) & 0xFF) - IMAGE_MEAN) / IMAGE_STD;
        floatValues[i * 3 + 1] = (((val >> 8) & 0xFF) - IMAGE_MEAN) / IMAGE_STD;
        floatValues[i * 3 + 2] = ((val & 0xFF) - IMAGE_MEAN) / IMAGE_STD;
    }
    return floatValues;
}
项目:androidthings-imageclassifier    文件:Helper.java   
public static float[] getPixels(Bitmap bitmap) {
    if (bitmap.getWidth() != IMAGE_SIZE || bitmap.getHeight() != IMAGE_SIZE) {
        // rescale the bitmap if needed
        bitmap = ThumbnailUtils.extractThumbnail(bitmap, IMAGE_SIZE, IMAGE_SIZE);
    }
    int[] intValues = new int[IMAGE_SIZE * IMAGE_SIZE];

    bitmap.getPixels(intValues, 0, bitmap.getWidth(), 0, 0, bitmap.getWidth(), bitmap.getHeight());

    float[] floatValues = new float[IMAGE_SIZE * IMAGE_SIZE * 3];
    // Preprocess the image data from 0-255 int to normalized float based
    // on the provided parameters.
    for (int i = 0; i < intValues.length; ++i) {
        final int val = intValues[i];
        floatValues[i * 3] = (((val >> 16) & 0xFF) - IMAGE_MEAN) / IMAGE_STD;
        floatValues[i * 3 + 1] = (((val >> 8) & 0xFF) - IMAGE_MEAN) / IMAGE_STD;
        floatValues[i * 3 + 2] = ((val & 0xFF) - IMAGE_MEAN) / IMAGE_STD;
    }
    return floatValues;
}
项目:androidthings-imageclassifier    文件:Helper.java   
public static float[] getPixels(Bitmap bitmap) {
    if (bitmap.getWidth() != IMAGE_SIZE || bitmap.getHeight() != IMAGE_SIZE) {
        // rescale the bitmap if needed
        bitmap = ThumbnailUtils.extractThumbnail(bitmap, IMAGE_SIZE, IMAGE_SIZE);
    }
    int[] intValues = new int[IMAGE_SIZE * IMAGE_SIZE];

    bitmap.getPixels(intValues, 0, bitmap.getWidth(), 0, 0, bitmap.getWidth(), bitmap.getHeight());

    float[] floatValues = new float[IMAGE_SIZE * IMAGE_SIZE * 3];
    // Preprocess the image data from 0-255 int to normalized float based
    // on the provided parameters.
    for (int i = 0; i < intValues.length; ++i) {
        final int val = intValues[i];
        floatValues[i * 3] = (((val >> 16) & 0xFF) - IMAGE_MEAN) / IMAGE_STD;
        floatValues[i * 3 + 1] = (((val >> 8) & 0xFF) - IMAGE_MEAN) / IMAGE_STD;
        floatValues[i * 3 + 2] = ((val & 0xFF) - IMAGE_MEAN) / IMAGE_STD;
    }
    return floatValues;
}
项目:editor-sql    文件:FeThumbUtils.java   
/**
 * 从系统媒体库获取图片,视频,音乐,apk文件的缩略图
 *
 * @param context  Context
 * @param mimeType 文件类型
 * @param path     文件路径
 * @param isList   是否为列表模式
 * @return 缩略图
 */
public static Bitmap getThumbFromDb(Context context, String mimeType, String path, boolean isList) {

    int width = isList ? 40 : 104;
    int height = isList ? 40 : 72;
    int thumbnailsValues = MediaStore.Images.Thumbnails.MINI_KIND;
    if (mimeType.startsWith("image")) {
        return ThumbnailUtils.extractThumbnail(getThumbImage(context, path, thumbnailsValues), FeViewUtils.dpToPx(width), FeViewUtils.dpToPx(height));
    } else if (mimeType.startsWith("video")) {
        return ThumbnailUtils.extractThumbnail(getVideoImage(context, path, thumbnailsValues), FeViewUtils.dpToPx(width), FeViewUtils.dpToPx(height));
    } else if (mimeType.startsWith("audio") || mimeType.equals("application/ogg")) {
        return ThumbnailUtils.extractThumbnail(getMusicThumb(path), FeViewUtils.dpToPx(width), FeViewUtils.dpToPx(height));
    } else if (mimeType.equals("application/vnd.android.package-archive")) {
        //app 图标在平铺模式下 56dp  设计规定
        width = isList ? 40 : 56;
        height = isList ? 40 : 56;
        Bitmap bitmap = getLocalApkIcon(context.getPackageManager(), path);
        if (bitmap != null) {
            return FeThumbUtils.scaleBitMap(bitmap, FeViewUtils.dpToPx(width), FeViewUtils.dpToPx(height));
        }

        return null;
    }

    return null;
}
项目:editor-sql    文件:FeThumbUtils.java   
public static Bitmap getThumbFromThumbPath(Context ctx, String filePath, int kind) {
    Bitmap bitmap;
    try {
        bitmap = BitmapFactory.decodeFile(filePath);
        bitmap = ThumbnailUtils.extractThumbnail(bitmap, 80, 80,
                ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    } catch (OutOfMemoryError o) {
        System.gc();
        try {
            bitmap = createImageThumbnailThrowErrorOrException(ctx,
                    filePath, kind);
            return bitmap;
        } catch (Throwable t) {
            t.printStackTrace();
            return null;
        }
    }
    return bitmap;
}
项目:sample-tensorflow-imageclassifier    文件:Helper.java   
public static float[] getPixels(Bitmap bitmap, int[] intValues, float[] floatValues) {
    if (bitmap.getWidth() != IMAGE_SIZE || bitmap.getHeight() != IMAGE_SIZE) {
        // rescale the bitmap if needed
        bitmap = ThumbnailUtils.extractThumbnail(bitmap, IMAGE_SIZE, IMAGE_SIZE);
    }

    bitmap.getPixels(intValues, 0, bitmap.getWidth(), 0, 0, bitmap.getWidth(), bitmap.getHeight());

    // Preprocess the image data from 0-255 int to normalized float based
    // on the provided parameters.
    for (int i = 0; i < intValues.length; ++i) {
        final int val = intValues[i];
        floatValues[i * 3] = (((val >> 16) & 0xFF) - IMAGE_MEAN) / IMAGE_STD;
        floatValues[i * 3 + 1] = (((val >> 8) & 0xFF) - IMAGE_MEAN) / IMAGE_STD;
        floatValues[i * 3 + 2] = ((val & 0xFF) - IMAGE_MEAN) / IMAGE_STD;
    }
    return floatValues;
}
项目:cardinalsSample    文件:ImageUtil.java   
/**
 * 获取图片的缩略图
 *
 * @param imagePath 图片路径
 * @param maxWidth  最大宽度
 * @param maxHeight 最大高度
 * @return 一个bitmap缩略图
 */
public static Bitmap getImageThumbnail(String imagePath, int maxWidth, int maxHeight) {
    Bitmap bitmap;
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    // 获取这个图片的宽和高,注意此处的bitmap为null
    bitmap = BitmapFactory.decodeFile(imagePath, options);
    options.inJustDecodeBounds = false; // 设为 false
    // 计算缩放比
    int h = options.outHeight;
    int w = options.outWidth;
    int beWidth = w / maxWidth;
    int beHeight = h / maxHeight;
    int be = beWidth < beHeight ? beWidth : beHeight;

    if (be <= 0) {
        be = 1;
    }
    options.inSampleSize = be;
    // 重新读入图片,读取缩放后的bitmap,注意这次要把options.inJustDecodeBounds 设为 false
    bitmap = BitmapFactory.decodeFile(imagePath, options);
    // 利用ThumbnailUtils来创建缩略图,这里要指定要缩放哪个Bitmap对象
    bitmap = ThumbnailUtils.extractThumbnail(bitmap, maxWidth, maxHeight,
            ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
    return bitmap;
}
项目:chat-sdk-android-push-firebase    文件:ImageUtils.java   
/**
 * Constructing a bitmap that contains the given bitmaps(max is three).
 *
 * For given two bitmaps the result will be a half and half bitmap.
 *
 * For given three the result will be a half of the first bitmap and the second
 * half will be shared equally by the two others.
 *
 * @param  bitmaps Array of bitmaps to use for the final image.
 * @param  width width of the final image, A positive number.
 * @param  height height of the final image, A positive number.
 *
 * @return A Bitmap containing the given images.
 * */
@Nullable public static Bitmap getMixImagesBitmap(@Size(min = 1) int width,@Size(min = 1) int height, @NonNull Bitmap...bitmaps){

    if (height == 0 || width == 0) return null;

    if (bitmaps.length == 0) return null;

    Bitmap finalImage = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(finalImage);

    Paint paint = new Paint(Paint.FILTER_BITMAP_FLAG);

    if (bitmaps.length == 2){
        canvas.drawBitmap(ThumbnailUtils.extractThumbnail(bitmaps[0], width/2, height), 0, 0, paint);
        canvas.drawBitmap(ThumbnailUtils.extractThumbnail(bitmaps[1], width/2, height), width/2, 0, paint);
    }
    else{
        canvas.drawBitmap(ThumbnailUtils.extractThumbnail(bitmaps[0], width/2, height), 0, 0, paint);
        canvas.drawBitmap(ThumbnailUtils.extractThumbnail(bitmaps[1], width/2, height/2), width/2, 0, paint);
        canvas.drawBitmap(ThumbnailUtils.extractThumbnail(bitmaps[2], width/2, height/2), width/2, height/2, paint);
    }

    return finalImage;
}
项目:chromium-for-android-56-debug-video    文件:SnippetArticleViewHolder.java   
private void fadeThumbnailIn(SnippetArticle snippet, Bitmap thumbnail) {
    mImageCallback = null;
    if (thumbnail == null) return; // Nothing to do, we keep the placeholder.

    // We need to crop and scale the downloaded bitmap, as the ImageView we set it on won't be
    // able to do so when using a TransitionDrawable (as opposed to the straight bitmap).
    // That's a limitation of TransitionDrawable, which doesn't handle layers of varying sizes.
    Resources res = mThumbnailView.getResources();
    int targetSize = res.getDimensionPixelSize(R.dimen.snippets_thumbnail_size);
    Bitmap scaledThumbnail = ThumbnailUtils.extractThumbnail(
            thumbnail, targetSize, targetSize, ThumbnailUtils.OPTIONS_RECYCLE_INPUT);

    // Store the bitmap to skip the download task next time we display this snippet.
    snippet.setThumbnailBitmap(scaledThumbnail);

    // Cross-fade between the placeholder and the thumbnail.
    Drawable[] layers = {mThumbnailView.getDrawable(),
            new BitmapDrawable(mThumbnailView.getResources(), scaledThumbnail)};
    TransitionDrawable transitionDrawable = new TransitionDrawable(layers);
    mThumbnailView.setImageDrawable(transitionDrawable);
    transitionDrawable.startTransition(FADE_IN_ANIMATION_TIME_MS);
}
项目:AdaptiveIconView    文件:AdaptiveIconView.java   
private Bitmap getScaledBitmap(Bitmap bitmap, int width, int height) {
    double scale = icon.getScale();

    if (scale <= 1)
        return ThumbnailUtils.extractThumbnail(bitmap, (int) ((2 - scale) * width), (int) ((2 - scale) * height));
    else if (bitmap.getWidth() > 1 && bitmap.getHeight() > 1) {
        int widthMargin = (int) ((scale - 1) * width);
        int heightMargin = (int) ((scale - 1) * height);

        if (widthMargin > 0 && heightMargin > 0) {
            Bitmap source = ThumbnailUtils.extractThumbnail(bitmap, (int) ((2 - scale) * width), (int) ((2 - scale) * height));
            int dWidth = width + widthMargin;
            int dHeight = height + heightMargin;
            bitmap = Bitmap.createBitmap(dWidth, dHeight, bitmap.getConfig());
            Canvas canvas = new Canvas(bitmap);
            canvas.drawBitmap(source, (dWidth - source.getWidth()) / 2, (dHeight - source.getHeight()) / 2, new Paint());
            return bitmap;
        }
    } else if (bitmap.getWidth() > 0 && bitmap.getHeight() > 0)
        return ThumbnailUtils.extractThumbnail(bitmap, width, height);

    return null;
}
项目:jackknife    文件:ImageUtils.java   
public static Bitmap getImageThumbnail(String imagePath, int width, int height) {
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    options.inJustDecodeBounds = false;
    int outWidth = options.outWidth;
    int outHeight = options.outHeight;
    int w = outWidth / width;
    int h = outHeight / height;
    int inSampleSize;
    if (w < h) {
        inSampleSize = w;
    } else {
        inSampleSize = h;
    }
    if (inSampleSize <= 0) {
        inSampleSize = 1;
    }
    options.inSampleSize = inSampleSize;
    Bitmap bitmap = BitmapFactory.decodeFile(imagePath, options);
    bitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height,
            ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
    return bitmap;
}
项目:KrGallery    文件:CameraController.java   
@Override
public void onInfo(MediaRecorder mediaRecorder, int what, int extra) {
    if (what == MediaRecorder.MEDIA_RECORDER_INFO_MAX_DURATION_REACHED || what == MediaRecorder.MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED || what == MediaRecorder.MEDIA_RECORDER_INFO_UNKNOWN) {
        MediaRecorder tempRecorder = recorder;
        recorder = null;
        if (tempRecorder != null) {
            tempRecorder.stop();
            tempRecorder.release();
        }
        if (onVideoTakeCallback != null) {
            final Bitmap bitmap = ThumbnailUtils.createVideoThumbnail(recordedFile, MediaStore.Video.Thumbnails.MINI_KIND);
            AndroidUtilities.runOnUIThread(new Runnable() {
                @Override
                public void run() {
                    if (onVideoTakeCallback != null) {
                        onVideoTakeCallback.onFinishVideoRecording(bitmap);
                        onVideoTakeCallback = null;
                    }
                }
            });
        }
    }
}
项目:PlusGram    文件:CameraController.java   
@Override
public void onInfo(MediaRecorder mediaRecorder, int what, int extra) {
    if (what == MediaRecorder.MEDIA_RECORDER_INFO_MAX_DURATION_REACHED || what == MediaRecorder.MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED || what == MediaRecorder.MEDIA_RECORDER_INFO_UNKNOWN) {
        MediaRecorder tempRecorder = recorder;
        recorder = null;
        if (tempRecorder != null) {
            tempRecorder.stop();
            tempRecorder.release();
        }
        final Bitmap bitmap = ThumbnailUtils.createVideoThumbnail(recordedFile, MediaStore.Video.Thumbnails.MINI_KIND);
        AndroidUtilities.runOnUIThread(new Runnable() {
            @Override
            public void run() {
                onVideoTakeCallback.onFinishVideoRecording(bitmap);
            }
        });
    }
}
项目:PlusGram    文件:CameraController.java   
public void stopVideoRecording(CameraSession session, boolean abandon) {
    try {
        CameraInfo info = session.cameraInfo;
        Camera camera = info.camera;
        if (camera != null && recorder != null) {
            MediaRecorder tempRecorder = recorder;
            recorder = null;
            tempRecorder.stop();
            tempRecorder.release();
            camera.reconnect();
            camera.startPreview();
            session.stopVideoRecording();
        }
        if (!abandon) {
            final Bitmap bitmap = ThumbnailUtils.createVideoThumbnail(recordedFile, MediaStore.Video.Thumbnails.MINI_KIND);
            AndroidUtilities.runOnUIThread(new Runnable() {
                @Override
                public void run() {
                    onVideoTakeCallback.onFinishVideoRecording(bitmap);
                }
            });
        }
    } catch (Exception e) {
        FileLog.e("tmessages", e);
    }
}
项目:RLibrary    文件:Utils.java   
public static boolean extractThumbnail(String videoPath, String thumbPath) {
    if (!isFileExist(thumbPath)) {
        Bitmap thumbnail = null;
        thumbnail = ThumbnailUtils.createVideoThumbnail(videoPath, MediaStore.Images.Thumbnails.MINI_KIND);
        if (thumbnail == null) {
            try {
                thumbnail = createVideoThumbnail(videoPath);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (thumbnail != null) {
            saveBitmap(thumbnail, thumbPath, true);
            return true;
        }
    }
    return false;
}
项目:Ocr-android    文件:BitmapUtils.java   
/**
 * 将彩色图转换为纯黑白二色
 *
 * @param origin bitmap
 * @return Bitmap
 */
@SuppressWarnings("NumericOverflow")
public static Bitmap turnBlackWhite(Bitmap origin) {
    int w = origin.getWidth();
    int h = origin.getHeight();
    int[] pixels = new int[w * h];
    origin.getPixels(pixels, 0, w, 0, 0, w, h);
    int alpha = 0xFF << 24;
    for (int i = 0; i < h; i++) {
        for (int j = 0; j < w; j++) {
            int gray = pixels[w * i + j];
            int red = ((gray & 0x00FF0000) >> 16);
            int green = ((gray & 0x000FF00) >> 8);
            int blue = (gray & 0x000000FF);
            gray = (int) (red * 0.3 + green * 0.59 + blue * 0.11);
            gray = alpha | (gray << 16) | (gray << 8) | gray;
            pixels[w * i + j] = gray;
        }
    }
    Bitmap bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
    bitmap.setPixels(pixels, 0, w, 0, 0, w, h);
    return ThumbnailUtils.extractThumbnail(bitmap, w, h);
}
项目:MyTravelingDiary    文件:StickerManager.java   
private Bitmap resize(Bitmap source, int size) {
    if (source == null) {
        return null;
    }
    int scale = 1;
    if (size < source.getWidth() / 4) {
        scale = 4;
    } else if (size < source.getWidth() * 3 / 4) {
        scale = 2;
    } else if (size < source.getWidth()) {
        scale = 1;
    }
    int width = source.getWidth() / scale;
    int height = source.getHeight() / scale;

    if (width >= source.getWidth() && height >= source.getHeight()) {
        return source;
    } else {
        return ThumbnailUtils.extractThumbnail(source, width, height, ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
    }
}
项目:yun2win-sdk-android    文件:FilesAdapter.java   
@Override
protected Object doInBackground(FileItem... params) {
    Bitmap bitmap = null;
    // 鑾峰彇瑙嗛鐨勭缉鐣ュ浘
    FileItem item = params[0];
    bitmap = ThumbnailUtils.createVideoThumbnail(item.getFilePath(),
            Thumbnails.MICRO_KIND);
    bitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height,
            ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
    if (bitmap != null) {
        item.setIcon(bitmap);
        publishProgress();
        return bitmap;
    } else {
        return null;
    }
}
项目:yun2win-sdk-android    文件:StickerManager.java   
private Bitmap resize(Bitmap source, int size) {
    if (source == null) {
        return null;
    }
    int scale = 1;
    if (size < source.getWidth() / 4) {
        scale = 4;
    } else if (size < source.getWidth() * 3 / 4) {
        scale = 2;
    } else if (size < source.getWidth()) {
        scale = 1;
    }
    int width = source.getWidth() / scale;
    int height = source.getHeight() / scale;

    if (width >= source.getWidth() && height >= source.getHeight()) {
        return source;
    } else {
        return ThumbnailUtils.extractThumbnail(source, width, height, ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
    }
}
项目:Viewer    文件:BitmapUtils.java   
/**
 * 获取图片缩略图
 */
public static Bitmap getPictureImage(String urlPath) {
    Bitmap bitmap = null;
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    bitmap = BitmapFactory.decodeFile(urlPath, options);
    options.inJustDecodeBounds = false;
    int h = options.outHeight;
    int w = options.outWidth;
    int beWidth = w / 100;
    int beHeight = h / 80;
    int be = 1;
    if (beWidth < beHeight) {
        be = beWidth;
    } else {
        be = beHeight;
    }
    if (be <= 0) {
        be = 1;
    }
    options.inSampleSize = be;
    bitmap = BitmapFactory.decodeFile(urlPath, options);
    bitmap = ThumbnailUtils.extractThumbnail(bitmap, 100, 80,ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
    return bitmap;
}
项目:Viewer    文件:CommUtil.java   
/**
 * 获取图片缩略图
 */
public static Bitmap getPictureImage(String urlPath) {
    Bitmap bitmap = null;
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    bitmap = BitmapFactory.decodeFile(urlPath, options);
    options.inJustDecodeBounds = false;
    int h = options.outHeight;
    int w = options.outWidth;
    int beWidth = w / 100;
    int beHeight = h / 80;
    int be = 1;
    if (beWidth < beHeight) {
        be = beWidth;
    } else {
        be = beHeight;
    }
    if (be <= 0) {
        be = 1;
    }
    options.inSampleSize = be;
    bitmap = BitmapFactory.decodeFile(urlPath, options);
    bitmap = ThumbnailUtils.extractThumbnail(bitmap, 100, 80,ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
    return bitmap;
}
项目:HeyaLauncher    文件:Tools.java   
/**
     * Resize a bitmap to fit the new dimensions (Fit-Center)
     *
     * @param source
     * @param fitWidth
     * @param fitHeight
     * @return
     */
    public static Bitmap resizeBitmapToFit(Bitmap source, Integer fitWidth, Integer fitHeight)
    {
        return ThumbnailUtils.extractThumbnail(source, fitWidth, fitHeight);
//        // Set new width and height to fit center
//        int targetW = fitWidth;
//        int targetH = fitHeight;
//        Log.d("PHOTO", "Target-Size : " + targetW + "x" + targetH);
//
//        // Get size of current bitmap
//        int photoW = source.getWidth();
//        int photoH = source.getHeight();
//        Log.d("PHOTO", "Source-Size : " + photoW + "x" + photoH);
//
//        // Create and return correct bitmap
//        Matrix m = new Matrix();
//        m.setRectToRect(new RectF(0, 0, photoW, photoH), new RectF(0, 0, targetW, targetH), Matrix.ScaleToFit.CENTER);
//
//        Bitmap retVal = Bitmap.createBitmap(source, 0, 0, photoW, photoH, m, true);
//        Log.d("PHOTO", "Cropped-Size: " + retVal.getWidth() + "x" + retVal.getHeight());
//        return retVal;
    }
项目:OpenGraphView    文件:RoundableImageView.java   
@Override
public void setImageBitmap(Bitmap bm) {
    super.setImageBitmap(bm);
    if (bm == null) {
        mPaint.reset();
        mPaint.setColor(ContextCompat.getColor(getContext(), android.R.color.transparent));
        invalidate();
        return;
    } else {
        mPaint.setColor(ContextCompat.getColor(getContext(), android.R.color.white));
    }

    Bitmap centerCroppedBitmap = ThumbnailUtils.extractThumbnail(bm, mSide, mSide);
    BitmapShader shader = new BitmapShader(centerCroppedBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
    mPaint.setShader(shader);
}
项目:AndroidChromium    文件:SnippetArticleViewHolder.java   
private void fadeThumbnailIn(SnippetArticle snippet, Bitmap thumbnail) {
    mImageCallback = null;
    if (thumbnail == null) return; // Nothing to do, we keep the placeholder.

    // We need to crop and scale the downloaded bitmap, as the ImageView we set it on won't be
    // able to do so when using a TransitionDrawable (as opposed to the straight bitmap).
    // That's a limitation of TransitionDrawable, which doesn't handle layers of varying sizes.
    Resources res = mThumbnailView.getResources();
    int targetSize = res.getDimensionPixelSize(R.dimen.snippets_thumbnail_size);
    Bitmap scaledThumbnail = ThumbnailUtils.extractThumbnail(
            thumbnail, targetSize, targetSize, ThumbnailUtils.OPTIONS_RECYCLE_INPUT);

    // Store the bitmap to skip the download task next time we display this snippet.
    snippet.setThumbnailBitmap(scaledThumbnail);

    // Cross-fade between the placeholder and the thumbnail.
    Drawable[] layers = {mThumbnailView.getDrawable(),
            new BitmapDrawable(mThumbnailView.getResources(), scaledThumbnail)};
    TransitionDrawable transitionDrawable = new TransitionDrawable(layers);
    mThumbnailView.setImageDrawable(transitionDrawable);
    transitionDrawable.startTransition(FADE_IN_ANIMATION_TIME_MS);
}
项目:BigApp_Discuz_Android    文件:CameraUtils.java   
/** 创建缩略图,返回缩略图文件路径 */
//没实现
   public String createThumbnail(Bitmap source, String fileName){
       int oldW = source.getWidth();
       int oldH = source.getHeight();

       int w = Math.round((float)oldW/MAX_SIZES);  //MAX_SIZE为缩略图最大尺寸
       int h = Math.round((float)oldH/MAX_SIZES);

       int newW = 0;
       int newH = 0;

       if(w <= 1 && h <= 1){
           return saveBitmap(source, fileName);
       }

       int i = w > h ? w : h;  //获取缩放比例

       newW = oldW/i;
       newH = oldH/i;

       Bitmap imgThumb = ThumbnailUtils.extractThumbnail(source, newW, newH);  //关键代码!!

       return saveBitmap(imgThumb, fileName);  //注:saveBitmap方法为保存图片并返回路径的private方法
   }
项目:AyoSunny    文件:GalleryCache.java   
@Override
protected Bitmap doInBackground(Void... params) {
    Bitmap bitmap = null;
    try {
        bitmap = ThumbnailUtils.createVideoThumbnail(mImageKey, Thumbnails.FULL_SCREEN_KIND);

        if (bitmap != null) {
            bitmap = Bitmap.createScaledBitmap(bitmap, mMaxWidth, mMaxWidth, false);
            addBitmapToCache(mImageKey, bitmap);
            return bitmap;
        }
        return null;
    } catch (Exception e) {
        if (e != null) {
            e.printStackTrace();
        }
        return null;
    }
}
项目:InstaImageDownloader    文件:DownloadFragment.java   
/**
 * After completing background task
 * Dismiss the progress dialog
 **/
@Override protected void onPostExecute(String file_url) {

    circularProgress.setVisibility(View.GONE);
    Toast.makeText(mContext, "Post Saved", Toast.LENGTH_LONG).show();

    String extension = "";

    // recognizing weather its a image or video from file format
    int i = file_url.lastIndexOf('.');
    extension = file_url.substring(i + 1);

    if (extension.equalsIgnoreCase("mp4")) {
        Bitmap thumbnail = ThumbnailUtils.createVideoThumbnail(file_url, MediaStore.Images.Thumbnails.MINI_KIND);
        ivImage.setImageBitmap(thumbnail);
        //ivPlayBtn.setVisibility(View.VISIBLE);
    } else {
        ivImage.setImageDrawable(Drawable.createFromPath(file_url));
    }
    ((OnPostDownload) activity).refreshList();
}
项目:PEP---Notes    文件:BitmapHelper.java   
/**
    * Creates a thumbnail of requested size by doing a first sampled decoding of the bitmap to optimize memory
    */
public static Bitmap getThumbnail(Context mContext, Uri uri, int reqWidth, int reqHeight) {
    Bitmap srcBmp = BitmapUtils.decodeSampledFromUri(mContext, uri, reqWidth, reqHeight);

    // If picture is smaller than required thumbnail
    Bitmap dstBmp;
    if (srcBmp.getWidth() < reqWidth && srcBmp.getHeight() < reqHeight) {
        dstBmp = ThumbnailUtils.extractThumbnail(srcBmp, reqWidth, reqHeight);

        // Otherwise the ratio between measures is calculated to fit requested thumbnail's one
    } else {
        // Cropping
        int x = 0, y = 0, width = srcBmp.getWidth(), height = srcBmp.getHeight();
        float ratio = ((float) reqWidth / (float) reqHeight) * ((float) srcBmp.getHeight() / (float) srcBmp
                .getWidth());
        if (ratio < 1) {
            x = (int) (srcBmp.getWidth() - srcBmp.getWidth() * ratio) / 2;
            width = (int) (srcBmp.getWidth() * ratio);
        } else {
            y = (int) (srcBmp.getHeight() - srcBmp.getHeight() / ratio) / 2;
            height = (int) (srcBmp.getHeight() / ratio);
        }
        dstBmp = Bitmap.createBitmap(srcBmp, x, y, width, height);
    }
    return dstBmp;
}
项目:GifAssistant    文件:VideosListAdapter.java   
@Override
public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder holder = null;
    if (convertView == null) {
        holder=new ViewHolder();  
        convertView = mInflater.inflate(R.layout.videos_list_item, null);
        holder.thumb = (ImageView)convertView.findViewById(R.id.video_thumb);
        holder.name = (TextView)convertView.findViewById(R.id.video_name);
        holder.time = (TextView)convertView.findViewById(R.id.video_file_created_time);
        holder.duration = (TextView) convertView.findViewById(R.id.video_total_duration);
        convertView.setTag(holder);
    }else {
        logd("convertView != null, reuse");
        holder = (ViewHolder)convertView.getTag();
    }

    VideosInfo videoInfo = new VideosInfo(mVideosPaths.get(position));
    //holder.thumb.setImageBitmap(ExtractPicturesWorker.extractBitmap(mVideosPaths.get(position), 0));
    holder.thumb.setImageBitmap(ThumbnailUtils.createVideoThumbnail(mVideosPaths.get(position), Thumbnails.MINI_KIND));
    holder.name.setText("文件名:" + videoInfo.getName());
    holder.time.setText("时间:" + videoInfo.getLastModifyTime());
    holder.duration.setText("时长:" + videoInfo.getDuration());

    return convertView;
}
项目:OpenCVTour    文件:Utilities.java   
/**
 * Creates and returns a Bitmap of the image at the given filepath, scaled down to fit the area the Bitmap will be displayed in
 * @param image_file_path location of the image to sample
 * @param reqWidth width at which the resultant Bitmap will be displayed
 * @param reqHeight height at which the resultant Bitmap will be displayed
 * @return a Bitmap large enough to cover the given area
 */
public static Bitmap decodeSampledBitmap(String image_file_path, int reqWidth, int reqHeight) {
    Log.v(TAG, "creating bitmap for " + image_file_path);

    long start = android.os.SystemClock.uptimeMillis();

    final BitmapFactory.Options options = getBitmapBounds(image_file_path);

    options.inSampleSize = calculateInSampleSize(options.outWidth, options.outHeight, reqWidth, reqHeight);
    options.inJustDecodeBounds = false;

    Bitmap sampled = BitmapFactory.decodeFile(image_file_path, options);
    long sampled_time = android.os.SystemClock.uptimeMillis();
    Log.v(TAG, "created sampled bitmap for " + image_file_path + ", took " + (sampled_time-start) + "ms");

    Bitmap oriented = fixOrientation(sampled, image_file_path);
    long orientation_fixed_time = android.os.SystemClock.uptimeMillis();
    Log.v(TAG, "fixed orientation for " + image_file_path + ", took " + (orientation_fixed_time-sampled_time) + "ms");

    Bitmap final_bitmap = ThumbnailUtils.extractThumbnail(oriented, reqWidth, reqHeight);
    long end = android.os.SystemClock.uptimeMillis();
    Log.v(TAG, "finished resizing bitmap for " + image_file_path + ", took " + (end-orientation_fixed_time) + "ms");
    Log.v(TAG, "finished creating bitmap for " + image_file_path + ", took " + (end-start) + "ms");

    return final_bitmap;
}
项目:fresco    文件:LocalVideoThumbnailProducerTest.java   
@Before
public void setUp() throws Exception {
  MockitoAnnotations.initMocks(this);
  mExecutor = new TestExecutorService(new FakeClock());
  mLocalVideoThumbnailProducer = new LocalVideoThumbnailProducer(
      mExecutor,
      RuntimeEnvironment.application.getContentResolver());
  mFile = new File(RuntimeEnvironment.application.getExternalFilesDir(null), TEST_FILENAME);

  mockStatic(ThumbnailUtils.class);
  mProducerContext = new SettableProducerContext(
      mImageRequest,
      mRequestId,
      mProducerListener,
      mock(Object.class),
      ImageRequest.RequestLevel.FULL_FETCH,
      false,
      false,
      Priority.MEDIUM);
  when(mImageRequest.getSourceFile()).thenReturn(mFile);
}
项目:fresco    文件:LocalVideoThumbnailProducerTest.java   
@Test
public void testLocalVideoMicroThumbnailReturnsNull() throws Exception {
  when(mProducerListener.requiresExtraMap(mRequestId)).thenReturn(true);
  when(
      android.media.ThumbnailUtils.createVideoThumbnail(
          mFile.getPath(), MediaStore.Images.Thumbnails.MICRO_KIND))
      .thenReturn(null);
  mLocalVideoThumbnailProducer.produceResults(mConsumer, mProducerContext);
  mExecutor.runUntilIdle();
  verify(mConsumer).onNewResult(null, Consumer.IS_LAST);
  verify(mProducerListener).onProducerStart(mRequestId, PRODUCER_NAME);
  Map<String, String> thumbnailNotFoundMap =
      ImmutableMap.of(LocalVideoThumbnailProducer.CREATED_THUMBNAIL, "false");
  verify(mProducerListener).onProducerFinishWithSuccess(
      mRequestId, PRODUCER_NAME, thumbnailNotFoundMap);
  verify(mProducerListener).onUltimateProducerReached(mRequestId, PRODUCER_NAME, false);
}
项目:SimplifySpan    文件:CustomLabelSpan.java   
@Override
public int getSize(Paint paint, CharSequence text, int start, int end, Paint.FontMetricsInt fm) {
    if (isInit) {
        isInit = false;
        initFinalHeight(paint);
        initFinalWidth(paint);

        // Re Create Bitmap
        if (isDrawBitmap) {
            Bitmap newBitmap = ThumbnailUtils.extractThumbnail(mBitmap, Math.round(mFinalWidth), Math.round(mFinalHeight));
            if (null != newBitmap) {
                mBitmap.recycle();
                mBitmap = newBitmap;
            }
        }
    }

    return Math.round(mFinalWidth);
}
项目:base-imageloader    文件:ImageDecorder.java   
@TargetApi(Build.VERSION_CODES.FROYO)
private InputStream getVideoThumbnailStream(String filePath)
{
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO)
    {
        Bitmap bitmap = ThumbnailUtils
                .createVideoThumbnail(filePath, MediaStore.Images.Thumbnails.FULL_SCREEN_KIND);
        if (bitmap != null)
        {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.PNG, 0, bos);
            return new ByteArrayInputStream(bos.toByteArray());
        }
    }
    return null;
}