这篇文章将为大家详细讲解有关Android中怎么实现图片压缩并加载显示,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。
解析:
图片压缩的关键就是
options.inSampleSize = scale;
如果scale > 0,表示图片进行了压缩
/**
* 压缩图片
* @author chen.lin
*
*/
public class LoadImageActivity extends Activity implements OnClickListener {
private Button mBtnLoad;
private ImageView mImageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_load);
initViews();
}
private void initViews() {
mBtnLoad = (Button) findViewById(R.id.btnLoadImage);
mImageView = (ImageView) findViewById(R.id.imageView);
mBtnLoad.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if (v == mBtnLoad) {
Options options = new Options();
BitmapFactory.decodeFile("/sdcard/images/1.jpg", options);
//不去真的解析图片,只是获取图片的头部信息,宽高
options.inJustDecodeBounds = true;
//得到图片的真实宽高
int imageHeight = options.outHeight;
int imageWidth = options.outWidth;
//得到屏幕的宽高
WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);
int screenHeight = wm.getDefaultDisplay().getHeight();
int screenWidth = wm.getDefaultDisplay().getWidth();
//得到缩放比例
int scale = 1;
int scaleX = imageWidth / screenWidth;
int scaleY = imageHeight / screenHeight;
if (scaleX > scaleY & scaleX >=1) {//表示如果宽的缩放比例大于高的,并且scaleX>=1都为true
scale = scaleX;
}
if (scaleY > scaleX & scaleY >=1) {//表示如果高的缩放比例大于宽的,并且scaleY>=1都为true
scale = scaleY;
}
//解析图片
options.inJustDecodeBounds = false;
//修改图片的缩放比例,如果scale=4说明图片缩小4倍,像数=1/16
options.inSampleSize = scale;
Bitmap bm = BitmapFactory.decodeFile("/sdcard/images/1.jpg", options);
mImageView.setImageBitmap(bm);
}
}
}
布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ImageView
android:id="@+id/imageView"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1" />
<EditText
android:id="@+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10" >
<requestFocus />
</EditText>
<Button
android:id="@+id/btnLoadImage"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:onClick="loadImage"
android:text="加载图片" />
</LinearLayout>
关于Android中怎么实现图片压缩并加载显示就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。