在安卓中获取图像缩略图

18
我需要一张图片的缩略图。我只知道存储在SD卡中的图像名称,能有人帮助我吗?

你想用那个缩略图做什么? - Mohd Mufiz
我需要缩略图,因为当我直接将所有图像URI放入GridView中时,我一直收到“java.lang.OutOfMemoryError”的错误提示。 - hexicle
4个回答

70

试一试。

final int THUMBSIZE = 64;

Bitmap ThumbImage = ThumbnailUtils.extractThumbnail(BitmapFactory.decodeFile(imagePath), 
                    THUMBSIZE, THUMBSIZE);

点击此处 以获取更多详细信息。


imagePath 是什么? - Azim Ansari
它是存储在SD卡中的图像路径名称。 - Chirag
如果您正在使用Uri来获取图像,则可以使用例如imageUri.getPath()来获取路径。 - xhenryx14
非常直接和实用,谢谢! - codingmechanic

11
使用 MediaStore.Images.Thumbnails,您可以查询并获取两种缩略图:MINI_KIND:512 x 384缩略图和MICRO_KIND:96 x 96缩略图。使用此调用的优点是缩略图由MediaStore缓存,因此如果先前创建了缩略图,则检索速度更快。

2
byte[] imageData = null;

try
{

final int THUMBNAIL_SIZE = 64;

FileInputStream fis = new FileInputStream(fileName);
Bitmap imageBitmap = BitmapFactory.decodeStream(fis);

Float width = new Float(imageBitmap.getWidth());
Float height = new Float(imageBitmap.getHeight());
Float ratio = width/height;
imageBitmap = Bitmap.createScaledBitmap(imageBitmap, (int)(THUMBNAIL_SIZE * ratio), THUMBNAIL_SIZE, false);

ByteArrayOutputStream baos = new ByteArrayOutputStream();
imageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
imageData = baos.toByteArray();

}
catch(Exception ex) {

} 

1
如果您喜欢高质量的缩略图,可以使用[RapidDecoder][1]库。使用方法如下所示:
import rapid.decoder.BitmapDecoder;
...
Bitmap bitmap = BitmapDecoder.from(getResources(), R.drawable.image)
                             .scale(width, height)
                             .useBuiltInDecoder(true)
                             .decode();

如果你想将比例缩小到50%以下并获得高质量的结果,请不要忘记使用内置解码器。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接