下面列出了怎么用android.media.ThumbnailUtils的API类实例代码及写法,或者点击链接到github查看源代码。
private float[] getPixels(Bitmap bitmap) {
int[] intValues = new int[IMAGE_SIZE * IMAGE_SIZE];
float[] floatValues = new float[IMAGE_SIZE * IMAGE_SIZE * 3];
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());
for (int i = 0; i < intValues.length; ++i) {
final int val = intValues[i];
floatValues[i * 3] = Color.red(val) / 255.0f;
floatValues[i * 3 + 1] = Color.green(val) / 255.0f;
floatValues[i * 3 + 2] = Color.blue(val) / 255.0f;
}
return floatValues;
}
@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);
}
}
@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;
}
}
});
}
}
}
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);
}
@Override
protected Drawable doInBackground(Void... voids) {
// This is run on a background thread.
try {
// TODO(peconn): Replace this with something from the C++ Chrome stack.
URL imageUrl = new URL(mUrl);
InputStream in = imageUrl.openStream();
Bitmap raw = BitmapFactory.decodeStream(in);
int dimension = Math.min(raw.getHeight(), raw.getWidth());
RoundedBitmapDrawable img = RoundedBitmapDrawableFactory.create(mResources,
ThumbnailUtils.extractThumbnail(raw, dimension, dimension));
img.setCircular(true);
return img;
} catch (IOException e) {
Log.e(TAG, "Error downloading image: " + e.toString());
}
return null;
}
/**
* 获取图片缩略图
*/
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;
}
/**
* 获取图片缩略图
*/
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;
}
@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);
}
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);
}
/** 创建缩略图,返回缩略图文件路径 */
//没实现
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方法
}
private InputStream getVideoThumbnailStream(String filePath) {
Bitmap bitmap = ThumbnailUtils.createVideoThumbnail(
filePath, MediaStore.Images.Thumbnails.FULL_SCREEN_KIND);
if (bitmap != null) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0, bos);
return new ByteArrayInputStream(bos.toByteArray());
}
return null;
}
public static Bitmap createVideoThumbnail(String filePath, int width, int height, int offsetMillSecond) {
Bitmap bitmap = createVideoThumbnail(filePath, offsetMillSecond);
if (bitmap != null) {
return ThumbnailUtils.extractThumbnail(bitmap, width, height);
}
return bitmap;
}
public static Bitmap createVideoThumbnail(String filePath, int width, int height) {
Bitmap bp = createVideoThumbnail(filePath);
if (bp != null) {
return ThumbnailUtils.extractThumbnail(bp, width, height);
}
return bp;
}
public static Bitmap createVideoThumbnail(String filePath, int width, int height, int offsetMillSecond) {
Bitmap bitmap = createVideoThumbnail(filePath, offsetMillSecond);
if (bitmap != null) {
return ThumbnailUtils.extractThumbnail(bitmap, width, height);
}
return bitmap;
}
public static Bitmap createVideoThumbnail(String filePath, int width, int height) {
Bitmap bp = createVideoThumbnail(filePath);
if (bp != null) {
return ThumbnailUtils.extractThumbnail(bp, width, height);
}
return bp;
}
public static Bitmap createVideoThumbnail(String filePath, int width, int height, int offsetMillSecond) {
Bitmap bitmap = createVideoThumbnail(filePath, offsetMillSecond);
if (bitmap != null) {
return ThumbnailUtils.extractThumbnail(bitmap, width, height);
}
return bitmap;
}
public static Bitmap createVideoThumbnail(String filePath, int width, int height) {
Bitmap bp = createVideoThumbnail(filePath);
if (bp != null) {
return ThumbnailUtils.extractThumbnail(bp, width, height);
}
return bp;
}
@Override
public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
if (!cropped) {
final int dimension = Math.min(resource.getWidth(), resource.getHeight());
resource = ThumbnailUtils.extractThumbnail(resource, dimension, dimension);
}
ByteArrayOutputStream stream = new ByteArrayOutputStream();
resource.compress(Bitmap.CompressFormat.JPEG, 30, stream);
try {
addFullSizePhoto(rawId, stream.toByteArray(), contentResolver);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 根据指定的图像路径和大小来获取缩略图
* 此方法有两点好处:
* 1. 使用较小的内存空间,第一次获取的bitmap实际上为null,只是为了读取宽度和高度,
* 第二次读取的bitmap是根据比例压缩过的图像,第三次读取的bitmap是所要的缩略图。
* 2. 缩略图对于原图像来讲没有拉伸,这里使用了2.2版本的新工具ThumbnailUtils,使
* 用这个工具生成的图像不会被拉伸。
*
* @param imagePath 图像的路径
* @param width 指定输出图像的宽度
* @param height 指定输出图像的高度
* @return 生成的缩略图
*/
public static Bitmap getImageThumbnail(String imagePath, int width, int height) {
Bitmap bitmap = null;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
// 获取这个图片的宽和高,注意此处的bitmap为null
bitmap = BitmapFactory.decodeFile(imagePath, options);
BitmapUtils.recycler(bitmap);
options.inJustDecodeBounds = false; // 设为 false
// 计算缩放比
int h = options.outHeight;
int w = options.outWidth;
int beWidth = w / width;
int beHeight = h / height;
int be = 1;
if (beWidth < beHeight) {
be = beWidth;
} else {
be = beHeight;
}
if (be <= 0) {
be = 1;
}
options.inSampleSize = be;
// 重新读入图片,读取缩放后的bitmap,注意这次要把options.inJustDecodeBounds 设为 false
bitmap = BitmapFactory.decodeFile(imagePath, options);
// 利用ThumbnailUtils来创建缩略图,这里要指定要缩放哪个Bitmap对象
Bitmap thumb = ThumbnailUtils.extractThumbnail(bitmap, width, height, ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
BitmapUtils.recycler(bitmap);
return thumb;
}
private Bitmap getVideoDrawable(String path) throws OutOfMemoryError {
try {
Bitmap thumb = ThumbnailUtils.createVideoThumbnail(path,
MediaStore.Images.Thumbnails.MINI_KIND);
return thumb;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
//Uri imageUri = Uri.fromFile(new File(list.get(position)));// For files on device
File f = new File(list.get(position));
Bitmap bitmap;
if (f.getAbsolutePath().endsWith("mp4")) {
((Holder) holder).play.setVisibility(View.VISIBLE);
bitmap = ThumbnailUtils.createVideoThumbnail(f.getAbsolutePath(), MediaStore.Video.Thumbnails.MINI_KIND);
} else {
((Holder) holder).play.setVisibility(View.GONE);
bitmap = new BitmapDrawable(context.getResources(), f.getAbsolutePath()).getBitmap();
}
RoundedBitmapDrawable roundedBitmapDrawable = RoundedBitmapDrawableFactory.create(context.getResources(), bitmap);
final float roundPx = (float) bitmap.getWidth() * 0.06f;
roundedBitmapDrawable.setCornerRadius(roundPx);
((Holder) holder).iv.setImageDrawable(roundedBitmapDrawable);
((Holder) holder).iv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(f.getAbsolutePath()));
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
intent.setDataAndType(Uri.parse(f.getAbsolutePath()), Files.probeContentType(f.toPath()));
} else {
intent.setData(Uri.parse(f.getAbsolutePath()));
}
} catch (IOException e) {
e.printStackTrace();
}
context.startActivity(intent);
}
});
/*Bitmap scaled = com.fxn.utility.Utility.getScaledBitmap(
500f, com.fxn.utility.Utility.rotate(d,list.get(position).getOrientation()));*/
}
public static Bitmap getVideoThumbnail(String videoPath, int width, int height, int kind) {
Bitmap bitmap = null;
// 获取视频的缩略图
bitmap = ThumbnailUtils.createVideoThumbnail(videoPath, kind);
if(bitmap!= null){
bitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height,
ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
}
return bitmap;
}
public void generateVideoThmb(String srcFilePath, File destFile) {
try {
Bitmap bitmap = ThumbnailUtils.createVideoThumbnail(srcFilePath, 120);
FileOutputStream out = new FileOutputStream(destFile);
ThumbnailUtils.extractThumbnail(bitmap, 200, 200).compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private Bitmap getRoundBitmap(@DrawableRes int drawable, int size) {
Bitmap bitmap = ImageUtils.drawableToBitmap(ContextCompat.getDrawable(getContext(), drawable));
bitmap = Bitmap.createBitmap(bitmap, bitmap.getWidth() / 6, bitmap.getHeight() / 6, (int) (0.666 * bitmap.getWidth()), (int) (0.666 * bitmap.getHeight()));
bitmap = ThumbnailUtils.extractThumbnail(bitmap, size, size);
RoundedBitmapDrawable roundedBitmapDrawable = RoundedBitmapDrawableFactory.create(getResources(), bitmap);
roundedBitmapDrawable.setCornerRadius(size / 2);
roundedBitmapDrawable.setAntiAlias(true);
return ImageUtils.drawableToBitmap(roundedBitmapDrawable);
}
public static String extractThumbnail(String videoPath, String thumbPath) {
if (!AttachmentStore.isFileExist(thumbPath)) {
Bitmap bitmap = ThumbnailUtils.createVideoThumbnail(videoPath, MediaStore.Images.Thumbnails.MICRO_KIND);
if (bitmap != null) {
AttachmentStore.saveBitmap(bitmap, thumbPath, true);
return thumbPath;
}
}
return thumbPath;
}
@Nullable
@Override
public Result load(Request request, int networkPolicy) throws IOException {
Uri uri = request.uri;
String path = uri.getPath();
if (!TextUtils.isEmpty(path)) {
Bitmap bm = ThumbnailUtils.createVideoThumbnail(path, MediaStore.Images.Thumbnails.MINI_KIND);
return new Result(bm, Picasso.LoadedFrom.DISK);
}
return null;
}
/**
* 根据指定的图像路径和大小来获取缩略图
* 此方法有两点好处:
* 1. 使用较小的内存空间,第一次获取的bitmap实际上为null,只是为了读取宽度和高度,
* 第二次读取的bitmap是根据比例压缩过的图像,第三次读取的bitmap是所要的缩略图。
* 2. 缩略图对于原图像来讲没有拉伸,这里使用了2.2版本的新工具ThumbnailUtils,使
* 用这个工具生成的图像不会被拉伸。
* @param imagePath 图像的路径
* @param width 指定输出图像的宽度
* @param height 指定输出图像的高度
* @return 生成的缩略图
*/
private static Bitmap getImageThumbnail(String imagePath, int width, int height) {
Bitmap bitmap = null;
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 / width;
int beHeight = h / height;
int be = 1;
if (beWidth < beHeight) {
be = beWidth;
} else {
be = beHeight;
}
if (be <= 0) {
be = 1;
}
options.inSampleSize = be;
// 重新读入图片,读取缩放后的bitmap,注意这次要把options.inJustDecodeBounds 设为 false
bitmap = BitmapFactory.decodeFile(imagePath, options);
// 利用ThumbnailUtils来创建缩略图,这里要指定要缩放哪个Bitmap对象
bitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height,
ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
return bitmap;
}
public static String convertToBase64(Bitmap bitmap, int maxWidth, int maxHeight) {
if (bitmap == null) {
return null;
}
long startTime = System.currentTimeMillis();
int[] targetSize = computeTargetSize(bitmap, maxWidth, maxHeight);
// 10-100ms量级
Bitmap thumbnail = ThumbnailUtils.extractThumbnail(bitmap, targetSize[0], targetSize[1]);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.PNG, 100, baos);
String result = Base64.encodeToString(baos.toByteArray(), Base64.DEFAULT);
// L.d("ImageUtil.convertToBase64 cost %s ms", (System.currentTimeMillis() - startTime));
return result;
}
@Override
public void onDraw(Canvas canvas) {
Bitmap image = ImageUtils.drawableToBitmap(getDrawable());
if (image != null) {
int size = Math.min(getWidth(), getHeight());
image = ThumbnailUtils.extractThumbnail(image, size, size);
RoundedBitmapDrawable roundedBitmapDrawable = RoundedBitmapDrawableFactory.create(getResources(), image);
roundedBitmapDrawable.setCornerRadius(size / 2);
roundedBitmapDrawable.setAntiAlias(true);
canvas.drawBitmap(ImageUtils.drawableToBitmap(roundedBitmapDrawable), 0, 0, paint);
}
}
private ImageView addThumbnail(Bitmap bitmap) {
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(thumbnailSize, thumbnailSize);
lp.setMargins(10, 10, 10, 10);
Bitmap image = ThumbnailUtils.extractThumbnail(bitmap, thumbnailSize, thumbnailSize);
ImageView thumbnailView = createThumbnailView(lp, image);
thumbnailsContainer.addView(thumbnailView);
return thumbnailView;
}