我正在使用LoadImage
方法从网址加载图片并将其存储在Bitmap对象中。然后我减小它的大小。获得缩小的图像尺寸后,我将其显示在我的布局的ImageView
中。现在我想知道图像尺寸是否减小了。我怎么检查呢?
public class ReduceImageActivity extends Activity {
String image_URL = "http://pennapps.com/biblioteka/images/C.jpg";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ImageView bmImage = (ImageView) findViewById(R.id.imageView1);
BitmapFactory.Options bmOptions;
bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 1;
Bitmap bm = LoadImage(image_URL, bmOptions);
getResizedBitmap(bm, 200, 200);
System.out.println("after resizing it"+bm);
bmImage.setImageBitmap(getResizedBitmap(bm, 200, 200));
}
private Bitmap LoadImage(String URL, BitmapFactory.Options options) {
Bitmap bitmap = null;
InputStream in = null;
try {
in = OpenHttpConnection(URL);
bitmap = BitmapFactory.decodeStream(in, null, options);
in.close();
} catch (IOException e1) {
}
return bitmap;
}
private InputStream OpenHttpConnection(String strURL) throws IOException {
InputStream inputStream = null;
URL url = new URL(strURL);
URLConnection conn = url.openConnection();
try {
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setRequestMethod("GET");
httpConn.connect();
if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
inputStream = httpConn.getInputStream();
}
} catch (Exception ex) {
}
return inputStream;
}
public Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth) {
int width = bm.getWidth();
int height = bm.getHeight();
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
// create a matrix for the manipulation
Matrix matrix = new Matrix();
// resize the bit map
matrix.postScale(scaleWidth, scaleHeight);
// recreate the new Bitmap
Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height,
matrix, false);
System.out.println("in getresizebitmap"+resizedBitmap.toString());
return resizedBitmap;
}
}
答案 0 :(得分:2)
缩小图像尺寸后,可以使用以下方法检查新(缩小)图像的大小;
getWidth()
getHeight()
使用 - > resizedBitmap.getWidth(), resizedBitmap.getHeight()
答案 1 :(得分:2)
使用getWidth
,getHeight
作为@barzos建议。请注意,对getResizedBitmap(bm, 200, 200)
的调用不会更改原始bm
位图,而是会生成一个新位图,因此请按以下方式使用:
Bitmap bm = LoadImage(image_URL, bmOptions);
Bitmap resized = getResizedBitmap(bm, 200, 200);
System.out.println("after resizing [w: " + resized.getWidth() + ", h: " + resized.getHeight() + "]");
bmImage.setImageBitmap(resized);
这也消除了对getResizedBitmap
的一次不必要的调用,从而节省了CPU和内存资源。