Android-网络图片实例

1.申请网络访问权限
<!-- 申请网络访问权限 -->
    <uses-permission android:name="android.permission.INTERNET"/>
2.界面
<!-- 网络图片查看器 -->
     <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" 
        android:id="@+id/imagePath"/>
    
    <Button android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="查看"
        android:onClick="getImage"
        /> 
    <ImageView android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="查看"
        android:id="@+id/imageView"/>
3.MainActivity注册事件
public void getImage(View v){
        Toast.makeText(getApplicationContext(), "查看图片",1);
        EditText editText=(EditText)findViewById(R.id.imagePath);
        String path=editText.getText().toString();
        if(path==null||"".equals(path.trim())) {
            path="http://192.168.1.17:8080/Test/01.jpg";
        }
        
        try {
            byte[] data=ImageService.getImage(path);
            //显示图片
            Bitmap bitMap=BitmapFactory.decodeByteArray(data,0,data.length);
            ImageView imageView=(ImageView) findViewById(R.id.imageView);
            imageView.setImageBitmap(bitMap);
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(getApplicationContext(),"获取图片失败:"+e.getMessage(),1);
        }
    }
4.图片下载
public class ImageService {

    //下载网络图片
    public static byte[] getImage(String path) throws Exception {
        URL url=new URL(path);
        HttpURLConnection con=(HttpURLConnection) url.openConnection();
        con.setConnectTimeout(5000);
        con.setRequestMethod("GET");
        if(con.getResponseCode()==200){
            InputStream in=con.getInputStream();
            return StreamTool.read(in);
        }
        return null;
    }
}
5.图片数据处理
public class StreamTool {

    /**
     * 读取流中的数据
     */
    public static byte[] read(InputStream inputStream) throws IOException {
        ByteArrayOutputStream outStream=new ByteArrayOutputStream();
        byte[] data=new byte[1024];
        int len=0;
        while((len=inputStream.read(data))!=-1){
            outStream.write(data,0,len);
        }
        inputStream.close();
        return outStream.toByteArray();
    }

}


你可能感兴趣的:(Android-网络图片实例)