您的位置:首页 > 其它

图片资源类型转换为bitmap

2015-10-27 12:07 302 查看
1、网络图片:

背景:最新的SDK,不允许在main线程里面执行网络操作,否则报错:NetworkOnMainThreadException。

解决:在main线程中另开一个线程,进行相应的网络操作,再使用handler异步操作主线程的UI更新。

代码:

public class BitmapimgActivity extends Activity {
private ImageView imageView;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bitmapimg);
imageView = (ImageView) this.findViewById(R.id.imgs);

new Thread() {
public void run() {
// 图片资源
String url = "http://start.firefoxchina.cn/img/worldindex/logo.png";
// 得到可用的图片
Bitmap bitmap = getHttpBitmap(url);

Message msg=new Message();
msg.what=1;
msg.obj=bitmap;
handler.sendMessage(msg);
// imageView.setBackgroundResource(R.drawable.ic_launcher);
};

}.start();

}

Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
int s = msg.what;
if(s==1){
Bitmap bits=(Bitmap) msg.obj;

// 显示
imageView.setImageBitmap(bits);
}

}
};

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.bitmapimg, menu);
return true;
}

/**
* 获取网落图片资源
*
* @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;

}

}


2、本地图片(sdcard):

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

ImageView image1 = (ImageView) findViewById(R.id.iv1);  //获得ImageView对象
/*为什么图片一定要转化为 Bitmap格式的!! */
Bitmap bitmap = getLoacalBitmap("/sdcard/tubiao.jpg"); //从本地取图片(在cdcard中获取)  //
image1 .setImageBitmap(bitmap); //设置Bitmap
}

/**
* 加载本地图片
* @param url
* @return
*/
public static Bitmap getLoacalBitmap(String url) {
try {
FileInputStream fis = new FileInputStream(url);
return BitmapFactory.decodeStream(fis);  ///把流转化为Bitmap图片

} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: