安卓图片缩放中java.lang.IllegalArgumentException: width and height must be > 0错误

  第一次写博客,都是低级的错误,大神见笑了。

  今天做安卓加载图片到 ImageView,报了 一个 java.lang.IllegalArgumentException: width and height must be > 0错误,只能怪我英文不好,没看懂。先把我的代码贴出来。

 1 bmp = BitmapFactory.decodeStream(cr.openInputStream(uri));
 2 
 3 // 缩放图片
 4 WindowManager wm = getWindowManager();
 5 int width = wm.getDefaultDisplay().getWidth();
 6 int height = wm.getDefaultDisplay().getHeight();
 7 // 图片的宽高
 8 int photo_width = bmp.getWidth();
 9 int photo_height = bmp.getHeight();
10 // 缩放比例,如小于1就设置为1
11 int bili = (photo_width/width)>(photo_height/height)?(photo_width/width):(photo_height/height);
12 bili = bili>1?bili:1;
13 System.out.println("bili:"+bili);
14 Matrix matrix = new Matrix(); 
15 matrix.postScale(1/bili,1/bili); //长和宽放大缩小的比例
16 Bitmap resizeBmp = Bitmap.createBitmap(bmp,0,0,bmp.getWidth(),bmp.getHeight(),matrix,true);
17 
18 System.out.println(resizeBmp.getWidth()+":"+resizeBmp.getHeight());
19 
20 img1.setImageBitmap(resizeBmp);

一直在15行报错,我就不明白了,最后百度 matrix.postScale 中出现了赋值,于是我恍然大悟, matrix.postScale 接收的浮点类型的数,而我给的整数类型, 于是我该成了 matrix.postScale(1f/bili,1f/bili); 就没报错了。后来我仔细想想,这里的计算不合理,前面计算比例的时候应该用float的。

  以后还是要养成好习惯,浮点类型的尽量写上 f。

 

posted @ 2015-08-03 20:45  yuyuyu。  阅读(16669)  评论(0编辑  收藏  举报