Android大图片之缩略图,以及对原图依照指定宽高裁剪成缩略图

时间:2023-03-09 14:31:44
Android大图片之缩略图,以及对原图依照指定宽高裁剪成缩略图


《Android大图片之变换缩略图,以及对原始大图片依照指定宽、高裁剪成缩略图》

在Android的ImageView载入图像资源过程中,出于性能和内存开销的须要。有时候须要把一个原始的超大图片依照一定比例等比例缩放成较小的缩略图。或者须要把原始的超大图片,裁剪成指定宽高值的较小图片,针对这样的开发需求,能够使用Android SDK自身提供的工具类:ThumbnailUtils完毕。

ThumbnailUtils的在Android官方的开发文档链接地址:

http://developer.android.com/reference/android/media/ThumbnailUtils.html

以下以一个超大图片为例,使用ThumbnailUtils等比例缩放成缩略图和依照指定的宽高裁剪成满足须要的缩略图。

測试用的MainActivity.java :

package zhangphil.thumbnail;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.ThumbnailUtils;
import android.os.Bundle;
import android.widget.ImageView; public class MainActivity extends Activity { @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); ImageView imageView0 = (ImageView) findViewById(R.id.imageView0);
// 对原始资源图片不做不论什么处理和调整。直接载入到ImageView。
imageView0.setImageResource(R.drawable.image); Bitmap sourceBitmap = BitmapFactory.decodeResource(this.getResources(),
R.drawable.image); // 把原始bitmap截取成一个 MIN_SIZE * MIN_SIZE 的正方形缩略图。注意:默认是以中心为原点截取成缩略图。
int MIN_SIZE = 300;
ImageView imageView1 = (ImageView) findViewById(R.id.imageView1);
Bitmap bmp1 = ThumbnailUtils.extractThumbnail(sourceBitmap, MIN_SIZE,
MIN_SIZE);
imageView1.setImageBitmap(bmp1); // 获得原始bitmap的高和宽。以下将对原始Bitmap等比例缩放成缩略图载入。 int h = sourceBitmap.getHeight();
int w = sourceBitmap.getWidth(); // 缩略图缩放的比例尺
int THUMB_SIZE; THUMB_SIZE = 5;
// 对原始图片Bitmap等比例缩小5倍的缩略图
ImageView imageView2 = (ImageView) findViewById(R.id.imageView2);
Bitmap bmp2 = ThumbnailUtils.extractThumbnail(sourceBitmap, w / THUMB_SIZE, h
/ THUMB_SIZE);
imageView2.setImageBitmap(bmp2); // 对原始图片Bitmap等比例缩小10倍的缩略图。 THUMB_SIZE = 10;
ImageView imageView3 = (ImageView) findViewById(R.id.imageView3);
Bitmap bmp3 = ThumbnailUtils.extractThumbnail(sourceBitmap, w / THUMB_SIZE, h
/ THUMB_SIZE);
imageView3.setImageBitmap(bmp3);
}
}

MainActivity.java须要的布局文件activity_main.xml :

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" > <LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" > <ImageView
android:id="@+id/imageView0"
android:layout_width="wrap_content"
android:layout_height="wrap_content" /> <ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" /> <ImageView
android:id="@+id/imageView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" /> <ImageView
android:id="@+id/imageView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout> </ScrollView>

须要处理的目标的大图,原始大图资源:

Android大图片之缩略图,以及对原图依照指定宽高裁剪成缩略图

代码执行处理结果如图所看到的:

Android大图片之缩略图,以及对原图依照指定宽高裁剪成缩略图