android 从网络获取图片

1、开发android 程序免不了要跟服务器打交道,比如从服务器解析一张比较大的图片时,到了手机客户端有可能出现内存溢出的现象,此时我们就需要在客户端进行处理,比

如把图片等比缩放,让图片可以正常显示,下面就是从服务器解析得到图片后进行等比缩放。

package com.sunplus.app;


import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;


import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.widget.ImageView;

//note:添加网络权限
@SuppressLint("HandlerLeak")
public class MainActivity extends Activity {
    private String path = "http://172.20.224.12:8080/run/json/bb.png";
    private ImageView img = null; 
    private static int MAX_SIZE = 256;  //控制图片的大小 

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
        this.img = (ImageView) this.findViewById(R.id.img);

        LoadPic();
    }	
    private static Bitmap makeBitemap(byte[] value) {
        if (value == null)
            return null;

        // Load only size values
        BitmapFactory.Options sizeOptions = new BitmapFactory.Options();
        sizeOptions.inJustDecodeBounds = true;
        BitmapFactory.decodeByteArray(value, 0, value.length, sizeOptions);
        // Calculate factor to down scale image
        int scale = 1;
        int width_tmp = sizeOptions.outWidth;
        int height_tmp = sizeOptions.outHeight;
        while (width_tmp / 2 >= MAX_SIZE && height_tmp / 2 >= MAX_SIZE) {
            scale *= 2;
            width_tmp /= 2;
            height_tmp /= 2;
        }

        // Load image
        BitmapFactory.Options resultOptions = new BitmapFactory.Options();
        resultOptions.inSampleSize = scale;
        return BitmapFactory.decodeByteArray(value, 0, value.length, resultOptions);
    }

    private Handler myHandler = new Handler() {
        public void handleMessage(Message msg) {

            Bitmap bitMap = makeBitemap((byte[]) msg.obj);
            img.setImageBitmap(bitMap);
        };
    };

    private void LoadPic() {
        new Thread(new SThread()).start();
    }

    private class SThread implements Runnable {

        @Override
        public void run() {
            HttpURLConnection conn = null;
            try {
                URL url = new URL(path); // 实例化一个URL对象
                conn = (HttpURLConnection) url.openConnection(); // 打开一个url连接
                conn.setConnectTimeout(1000); // 设置超时显示
                conn.setRequestMethod("GET");
                byte[] buffer = null;
                if (conn.getResponseCode() == 200) {
                    buffer = createByteArray(new BufferedInputStream(conn.getInputStream()));
                    SystemClock.sleep(1000);
                    Message msg = new Message();
                    msg.obj = buffer;
                    myHandler.sendMessage(msg);
                }

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (conn != null)
                    conn.disconnect();
            }
        }

    }

    private static byte[] createByteArray(InputStream is) {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            copyStream(is, bos);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bos.toByteArray();
    }

    private static void copyStream(InputStream is, OutputStream os) throws IOException {
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = is.read(buffer)) != -1) {
            os.write(buffer, 0, len);
        }
        os.flush();

    }

}
note:在解析的过程千万别忘了添加网络权限

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

冰糖心书房

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值