Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;

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

import java.io.OutputStream;
import java.net.URL;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

public class Main {
    private static final String I = "======================= [HELLO-WORLD] " + "Helper" + ": ";

    public static Bitmap getAndSetBitmapFromNet(String urlPath) {

        Bitmap bm = null;

        if (urlPath != null) {
            try {
                BufferedInputStream bis = new BufferedInputStream(new URL(urlPath).openStream(), 1024);
                final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
                BufferedOutputStream out = new BufferedOutputStream(dataStream, 1024);
                copy(bis, out);
                out.flush();
                final byte[] data = dataStream.toByteArray();
                bm = BitmapFactory.decodeByteArray(data, 0, data.length);
                Log.i(I, "data.length: " + data.length);
                out.close();
                dataStream.close();
                bis.close();
                bm = processBitmap(bm);
            } catch (IOException e) {
                Log.i(I, "URL Connection or Bitmap processing Exception");
                e.printStackTrace();
            }
        }
        return bm;
    }

    static void copy(InputStream in, OutputStream out) throws IOException {
        byte[] buffer = new byte[0xFFFF];

        int len;
        while ((len = in.read(buffer)) != -1) {
            out.write(buffer, 0, len);
        }
    }

    private static Bitmap processBitmap(Bitmap bm) {

        float width = bm.getWidth();
        float height = bm.getHeight();
        int maxWidth = 150;
        int maxHeight = 150;
        float oldHeight;
        int oldWidth;
        float newWidth;
        float newHeight;
        float schnitt;

        Log.i("==============>", "width: " + width);
        Log.i("==============>", "height: " + height);

        newWidth = maxWidth;
        schnitt = newWidth / width;
        newHeight = (int) (schnitt * height);

        if (newHeight > maxHeight) {
            oldHeight = newHeight;
            oldWidth = (int) newWidth;
            newHeight = maxHeight;
            schnitt = newHeight / oldHeight;
            newWidth = schnitt * oldWidth;
        }

        Log.i("==============>", "New Width: " + newWidth);
        Log.i("==============>", "New Height: " + newHeight);

        bm = Bitmap.createScaledBitmap(bm, (int) newWidth, (int) newHeight, true);
        Log.i(I, "create scaled Bitmap successful");

        return bm;
    }
}