get Bitmap via HTTP connection - Android android.graphics

Android examples for android.graphics:Bitmap Operation

Description

get Bitmap via HTTP connection

Demo Code


//package com.java2s;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

public class Main {
    public static Bitmap getHttpBitmap(String path) {
        Bitmap bitmap = null;/*from   w  ww  . j a va2  s .c o  m*/
        byte[] b = null;
        try {
            URL url = new URL(path);
            HttpURLConnection con;

            con = (HttpURLConnection) url.openConnection();

            con.setRequestMethod("GET");
            con.setConnectTimeout(5000);
            InputStream in = con.getInputStream();

            b = readInputStream(in);

        } catch (Exception e) {

            e.printStackTrace();
        }

        bitmap = BitmapFactory.decodeByteArray(b, 0, b.length);

        return bitmap;
    }

    public static byte[] readInputStream(InputStream in) throws Exception {
        int len = 0;
        byte buf[] = new byte[1024];
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        while ((len = in.read(buf)) != -1) {
            out.write(buf, 0, len);
        }
        out.close();
        return out.toByteArray();
    }
}

Related Tutorials