ImageView从网络上获取图像

     在实际开发中我们可能会从网络上获取一张图片显示在我们的手机上,这样我们可以使用HTTP协议进行操作。

一、建立工程,如图

 

二、activity_main.xml中代码

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" 
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    
    <ImageView android:id="@+id/imageview" 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />
     <Button 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/button"
        android:text="下载网络图片"
         />
    
    
</LinearLayout>
View Code

三、AndroidManifest.xml中代码

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.study.httpimageview"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.study.httpimageview.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
    <!-- 添加访问网络的一个授权 -->
    <uses-permission android:name="android.permission.INTERNET"/>
</manifest>
View Code

这个当中最主要的加了个网络访问权限

四、MainActivity.java中代码

package com.study.httpimageview;

import java.io.InputStream;

import android.os.Bundle;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class MainActivity extends Activity {

    private Button button;
    private ImageView imageView;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = (Button)this.findViewById(R.id.button);
        imageView = (ImageView)this.findViewById(R.id.imageview);
        button.setOnClickListener(new View.OnClickListener() {
            
            @Override
            public void onClick(View v) {
                /*try {
                    InputStream inputStream = HttpUtils.getImageViewInputStream();
                    Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                    imageView.setImageBitmap(bitmap);
                } catch (Exception e) {
                    // TODO: handle exception
                }*/
                
                byte[] data = HttpUtils.getImageViewArray();
                Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
                imageView.setImageBitmap(bitmap);
            }
        });
    }


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

五、HttpUtils中代码

package com.study.httpimageview;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpUtils {
    
    
    public HttpUtils(){
        
    }
    /***
     * 从网络中获取图片信息,以流的形式返回
     */
    private final static String URL_PATH_STRING = "http://www.4493.com/uploads/attaches/2011/04/1302234716-EWZW9J.jpg";//访问图片的路径
    public static InputStream getImageViewInputStream()throws IOException{
        InputStream inputStream = null;
            URL url = new URL(URL_PATH_STRING);
            if(url != null){
                HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
                httpURLConnection.setConnectTimeout(3000);//设置连接超时时间
                httpURLConnection.setRequestMethod("GET");
                httpURLConnection.setDoInput(true);
                int response_code = httpURLConnection.getResponseCode();
                if(response_code == 200){
                    inputStream = httpURLConnection.getInputStream();
                }
            }
    
        
        return inputStream;
    }
    
    /***
     * 从网络中获取图片信息,以字节数组的形式返回
     */
    public static byte[] getImageViewArray(){
        byte[] data = null;
        InputStream inputStream = null;
        //ByteArrayOutputStream不需要关闭的输出流,直接写入到内存中
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try {
            URL url = new URL(URL_PATH_STRING);
            if(url != null){
                HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
                httpURLConnection.setConnectTimeout(3000);//设置连接超时时间
                httpURLConnection.setRequestMethod("GET");
                httpURLConnection.setDoInput(true);
                int response_code = httpURLConnection.getResponseCode();
                int len = 0;
                byte[] b_data = new byte[1024];
                if(response_code == 200){
                    inputStream = httpURLConnection.getInputStream();
                    while((len = inputStream.read(b_data)) != -1){
                        outputStream.write(b_data,0,len);
                    }
                    data = outputStream.toByteArray();
                }
            }
        } catch (Exception e) {
            // TODO: handle exception
        }finally{
            if(inputStream != null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        
        return data;
    }
}
View Code

六、效果图

点击的时候,有点慢的原因是因为在Android应用开发当中,要去网络数据,包括图片数据的话,一般都不会在主线程中加载的!这个后面会讲到,这里就这么先实现。

原文地址:https://www.cnblogs.com/kingshow123/p/httpimageview.html