Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import org.apache.http.util.ByteArrayBuffer;
import java.io.BufferedInputStream;

import java.io.IOException;
import java.io.InputStream;

import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class Main {

    public static byte[] downloadImage(String imageUrl) {
        if (imageUrl.endsWith(".jpg") || imageUrl.endsWith(".bmp") || imageUrl.endsWith(".png")
                || imageUrl.endsWith(".gif")) {
            try {
                URL url = new URL(imageUrl);
                URLConnection urlConn = url.openConnection();
                InputStream is = urlConn.getInputStream();
                BufferedInputStream bis = new BufferedInputStream(is);
                ByteArrayBuffer baf = new ByteArrayBuffer(50);
                int current = 0;

                while ((current = bis.read()) != -1) {
                    baf.append((byte) current);
                }

                return baf.toByteArray();
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return null;
    }
}