Android从网络中获取图片

Android从网络中获取图片

1. 首先要在AndroidManifest.xml文件中添加访问网络的权限:
<uses-permission android:name="android.permission.INTERNET"/>
2. 接着是界面:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="网络图片地址" />

    <EditText 
        android:id="@+id/edit_address"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="http://a.hiphotos.baidu.com/image/pic/item/b3b7d0a20cf431adb35c8e304936acaf2edd9829.jpg"
        />

    <Button 
        android:id="@+id/btn_get"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="获取图片"
        />

    <ImageView
        android:id="@+id/imageview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />

</LinearLayout>
3. 然后是Activity中的方法:
public class MainActivity extends Activity {

    private Button btn_get;
    private EditText edit_address;
    private ImageView imageview;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        /*android 2.3版本之后不允许在主线程中进行http请求防止界面假死,此法不推荐使用。
         * 建议方法为新建线程操作。
         */
        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = 
                    new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }

        btn_get = (Button) findViewById(R.id.btn_get);
        edit_address = (EditText) findViewById(R.id.edit_address);
        imageview = (ImageView) findViewById(R.id.imageview);

        btn_get.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                String path = edit_address.getText().toString();
                ImageService imageService = new ImageService();
                try {
                    byte[] data = imageService.getImage(path);
                    Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
                    imageview.setImageBitmap(bitmap);
                } catch (Exception e) {
                    Toast.makeText(MainActivity.this, "获取失败", 1000).show();
                    Log.e("ImageError", e.toString());
                }
            }
        });
    }

    public class ImageService {
        public byte[] getImage(String path) throws Exception{
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5 * 1000);
            InputStream inputStream = conn.getInputStream();//通过输入流获取图片数据
            byte[] data = readInputStream(inputStream);//得到图片的二进制数据
            return data;
        }

        public byte[] readInputStream(InputStream inputStream) throws Exception {
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while((len = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, len);//写到内存
            }
            inputStream.close();
            return outputStream.toByteArray();
        }
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值