从网络上获取一张图片,然后显示在手机上
来源:互联网 发布:小米5突然没有网络 编辑:程序博客网 时间:2024/04/29 10:02
public class MainActivity extends Activity {
private EditText pathText;
private ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pathText=(EditText) this.findViewById(R.id.imagepath);
imageView=(ImageView) this.findViewById(R.id.imageView1);
Button button = (Button) this.findViewById(R.id.button1); //找到按钮
button.setOnClickListener(new ButtonOnClickListener()); //为按钮设置一个点击事件存储事件
}
private final class ButtonOnClickListener implements View.OnClickListener{
public void onClick(View v) {
String path = pathText.getText().toString(); //得到图片路径
try{
byte[] data=ImageService.getImage(path); //以字节数组来存放图片数据 , 将实现代码放到业务类中实现
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
imageView.setImageBitmap(bitmap); //显示图片
}catch (Exception e){
e.printStackTrace(); //将例外往空台打印出来
Toast.makeText(getApplicationContext(),R.string.error,1).show();
}
}
}
}
package com.example.service;
public class ImageService {
/**
* 获取网络图片的数据
* @param path 网络图片路径
* @return
*/
public static byte[] getImage(String path) throws Exception{
URL url=new URL(path);
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); //得到一个基于HTTP协议连接对象
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET"); //请求网络图片的方式
if(conn.getResponseCode()==200){
InputStream inStream = conn.getInputStream(); //输入流
return StreamTool.read(inStream); //返回从流中读到的数据
}
return null;
}
}
package com.example.utils;
public class StreamTool {
/**
* 读取流中的数据
* @param inStream
* @return
* @throws Exception
*/
public static byte[] read(InputStream inStream) throws Exception{
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while((len = inStream.read(buffer)) !=-1){
outStream.write(buffer,0,len);
}
inStream.close();
return outStream.toByteArray();
}
}
<!-- 访问internet权限 -->
<uses-permission android:name="android.permission.INTERNET"/>
- 从网络上获取一张图片,然后显示在手机上
- 从网络上获取网页的html代码,然后显示在手机上
- APICloud从手机获取图片显示在页面上
- 获取网络上的一张图片并显示在界面上
- 第四章 网络下载之httpurlconnection 从网络上下载一张图片,在本地显示
- android从网络中获得一张图片,并显示在屏幕上
- android从网络中获得一张图片,并显示在屏幕上
- android 实现从网络上抓取图片并显示在手机上
- 在网络上获取XML显示在手机上
- java 从服务上获取一张图片
- 获取网络上的一张图片.
- 如何在对话框上显示一张图片
- 从网络上获取图片
- 选择一张图片然后在图片上根据手指移动绘图,然后保存到SD卡
- 从http服务器获取图片并显示在视图上
- 从 相机 或者相册 获取图片显示在ImageView 上
- 从相机或者相册,获取图片显示在ImageView上
- android 获取网络图片并在Imageview上显示
- JAVA学习第三天(6)对象转型
- 异常处理
- android自定义控件(TopBar的实现)
- Ruby On Rails开发中关于jQuery-datetimepicker-rails的一些使用心得
- 第四单元 4.20
- 从网络上获取一张图片,然后显示在手机上
- Qt学习笔记(一)
- 利用ViewPager+Fragment+actionbar实现可左右滑动的Action Tab
- 黑马程序员---反射学习笔记
- FZU_2191_完美的数字(数论)
- NBUT 1586 买票回家啦 区间dp
- 黑马程序员---集合(List)学习笔记
- hdu 1035 dfs判环
- uva 10396