Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import java.io.IOException;

import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class Main {
    public static final String CONTENT_TYPE_IMAGE = "image";

    public static Bitmap getImageFromURL(String url) {

        try {

            return getImageFromURL(new URL(url));

        } catch (MalformedURLException e) {

            e.printStackTrace();

        }

        return null;

    }

    public static Bitmap getImageFromURL(URL url) {

        Bitmap bitmap = null;

        HttpURLConnection connection = null;

        try {

            connection = (HttpURLConnection) url.openConnection();

            if (connection.getResponseCode() != 200) {
                return null;
            }
            if (!CONTENT_TYPE_IMAGE.equalsIgnoreCase(connection.getContentType().substring(0, 5))) {
                return null;
            }

            bitmap = BitmapFactory.decodeStream(connection.getInputStream());

        } catch (IOException e) {

            e.printStackTrace();

        }

        if (connection != null) {

            connection.disconnect();

        }

        return bitmap;

    }
}