网络访问之图片显示

来源:互联网 发布:php 接口验证 编辑:程序博客网 时间:2024/05/28 17:07

注意:访问网络必须加上访问网络的权限:

    <uses-permission android:name="android.permission.INTERNET"/>

1.布局代码略:

avtivity部分代码如下:

   public class MainActivity extends Activity {
    private EditText path;
    private Button button;
    private ImageView image;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_main);
        path=(EditText) findViewById(R.id.edit_1);
        image=(ImageView) findViewById(R.id.image_1);
        button=(Button) findViewById(R.id.button_1);
        button.setOnClickListener(new buttonOnClick()); 
    }
    public final class buttonOnClick implements OnClickListener{
@Override
public void onClick(View v) {
//获得图片路径
String pathText= path.getText().toString();
//将获取的图片以字节的形式存放
byte[] data;
try {

                       //创建逻辑类ImageService以及方法getImage方法
data = ImageService.getImage(pathText);

                      //将获取的图片数据转换成Bitmap对象
Bitmap bitmap=BitmapFactory.decodeByteArray(data, 0, data.length);
//设置显示图片
image.setImageBitmap(bitmap);
} catch (Exception e) {
// TODO Auto-generated catch block
Toast.makeText(getApplicationContext(), "获取图片失败",Toast.LENGTH_SHORT).show();
e.printStackTrace();
}

}
   
    }


}


ImageService部分代码如下:

package com.qq1009108034.service;


import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;


import com.qq1009108034.bean.StreamTool;


/*
 * 获取网络图片的数据
 */
public class ImageService {


public static byte[] getImage(String pathText) throws Exception {
URL url=new URL(pathText);

               //打开请求
HttpURLConnection conn=(HttpURLConnection) url.openConnection();

               //设置请求是否超时
conn.setReadTimeout(5000);
//设置请求的方法
conn.setRequestMethod("GET");

                //判断请求是否成功
if(conn.getResponseCode()==200){
InputStream inStream=conn.getInputStream();
return StreamTool.read(inStream);
}
return null ;
}


}

工具类:

public class StreamTool {


public static byte[] read(InputStream inStream) throws IOException {
ByteArrayOutputStream outStream=new ByteArrayOutputStream();
byte[] buffer =new byte[1024];
int len=0;
while((len=inStream.read(buffer))!=-1){
outStream.write(buffer);
}
inStream.close();
//返回出内存中的数据
return outStream.toByteArray();
}
    
}



0 0
原创粉丝点击