Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Apache License 

import android.graphics.Bitmap;

import android.graphics.BitmapFactory;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;

import java.net.URL;

public class Main {

    public static Bitmap loadImageFromUrl(String url) {
        ByteArrayOutputStream out = null;
        Bitmap bitmap = null;
        int BUFFER_SIZE = 1024 * 8;
        try {
            BufferedInputStream in = new BufferedInputStream(new URL(url).openStream(), BUFFER_SIZE);
            out = new ByteArrayOutputStream(BUFFER_SIZE);
            int length = 0;
            byte[] tem = new byte[BUFFER_SIZE];
            length = in.read(tem);
            while (length != -1) {
                out.write(tem, 0, length);
                out.flush();
                length = in.read(tem);
            }
            in.close();
            if (out.toByteArray().length != 0) {
                bitmap = BitmapFactory.decodeByteArray(out.toByteArray(), 0, out.size());
            } else {
                out.close();
                return null;
            }
            out.close();
        } catch (OutOfMemoryError e) {

            out.reset();
            BitmapFactory.Options opts = new BitmapFactory.Options();
            opts.inSampleSize = 2;
            opts.inJustDecodeBounds = false;
            bitmap = BitmapFactory.decodeByteArray(out.toByteArray(), 0, out.size(), opts);
            return bitmap;
        } catch (Exception e) {

            return bitmap;
        }
        return bitmap;
    }
}