- package com.android.antking.imageview;
- import java.io.InputStream;
- import java.net.HttpURLConnection;
- import java.net.MalformedURLException;
- import java.net.URL;
- import android.app.Activity;
- import android.graphics.Bitmap;
- import android.graphics.BitmapFactory;
- import android.os.Bundle;
- import android.util.Log;
- import android.view.View;
- import android.widget.ImageView;
- public class MainActivity extends Activity {
- //定义一个图片显示控件
- private ImageView imageView;
- /** Called when the activity is first created. */
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- //图片资源
- String url = "http://s16.sinaimg.cn/orignal/89429f6dhb99b4903ebcf&690";
- //得到可用的图片
- Bitmap bitmap = getHttpBitmap(url);
- imageView = (ImageView)this.findViewById(R.id.imageViewId);
- //显示
- imageView.setImageBitmap(bitmap);
- }
- /**
- * 获取网落图片资源
- * @param url
- * @return
- */
- public static Bitmap getHttpBitmap(String url){
- URL myFileURL;
- Bitmap bitmap=null;
- try{
- myFileURL = new URL(url);
- //获得连接
- HttpURLConnection conn=(HttpURLConnection)myFileURL.openConnection();
- //设置超时时间为6000毫秒,conn.setConnectionTiem(0);表示没有时间限制
- conn.setConnectTimeout(6000);
- //连接设置获得数据流
- conn.setDoInput(true);
- //不使用缓存
- conn.setUseCaches(false);
- //这句可有可无,没有影响
- //conn.connect();
- //得到数据流
- InputStream is = conn.getInputStream();
- //解析得到图片
- bitmap = BitmapFactory.decodeStream(is);
- //关闭数据流
- is.close();
- }catch(Exception e){
- e.printStackTrace();
- }
- return bitmap;
- }
- }
从本地获取Bitmap对象方法
1.将文件转化为bitmap对象
public static final float DISPLAY_WIDTH = 200;
public static final float DISPLAY_HEIGHT = 200;
/**
* 从path中获取图片信息
* @param path
* @return
*/
private Bitmap decodeBitmap(String path){
BitmapFactory.Options op = new BitmapFactory.Options();
//inJustDecodeBounds
//If set to true, the decoder will return null (no bitmap), but the out…
op.inJustDecodeBounds = true;
Bitmap bmp = BitmapFactory.decodeFile(path, op); //获取尺寸信息
//获取比例大小
int wRatio = (int)Math.ceil(op.outWidth/DISPLAY_WIDTH);
int hRatio = (int)Math.ceil(op.outHeight/DISPLAY_HEIGHT);
//如果超出指定大小,则缩小相应的比例
if(wRatio > 1 && hRatio > 1){
if(wRatio > hRatio){
op.inSampleSize = wRatio;
}else{
op.inSampleSize = hRatio;
}
}
op.inJustDecodeBounds = false;
bmp = BitmapFactory.decodeFile(path, op);
return bmp;
}
在通过BitmapFactory.decodeFile(String path)方法将突破转成Bitmap时,遇到大一些的图片,我们经常会遇到OOM(Out Of Memory)的问题。所以用到了我们上面提到的BitmapFactory.Options这个类。
2.通过二进制流Stream来获取
Bitmap bmp = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageFileUri), null, bmpFactoryOptions);
该博客展示了如何在Android应用中使用ImageView加载网络和本地图片资源。通过创建URL对象,建立HttpURLConnection连接,设置超时时间并获取输入流,然后使用BitmapFactory.decodeStream解析流为Bitmap对象,最后将Bitmap显示在ImageView上。
2064

被折叠的 条评论
为什么被折叠?



