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.Canvas;
import android.graphics.Color;

import android.graphics.Paint;
import android.graphics.Bitmap.Config;

public class Main {
    public static Bitmap getHistogram(Bitmap bmpOriginal) {

        //Scale bmpOriginal to improve performance 
        final int dstWidth = 200;
        int dstHeight = dstWidth * bmpOriginal.getHeight() / bmpOriginal.getWidth();
        Bitmap bmpScaled = Bitmap.createScaledBitmap(bmpOriginal, dstWidth, dstHeight, false);
        int[] histogramValues = new int[256];

        int[] pixels = new int[dstWidth];
        int pxBrightness;
        for (int row = 0; row < dstHeight; row++) {
            bmpScaled.getPixels(pixels, 0, dstWidth, 0, row, dstWidth, 1);
            for (int col = 0; col < dstWidth; col++) {
                pxBrightness = rgbToGray(pixels[col]);
                histogramValues[pxBrightness]++;
            }
        }
        bmpScaled.recycle();

        int histogramMax = max(histogramValues);
        Bitmap bmpHistogram = Bitmap.createBitmap(256, histogramMax, Config.ARGB_8888);
        Canvas canvas = new Canvas(bmpHistogram);
        Paint paint = new Paint();
        paint.setColor(Color.CYAN);

        for (int i = 0; i < 256; i++)
            canvas.drawLine(i, histogramMax - histogramValues[i], i, histogramMax, paint);

        return bmpHistogram;
    }

    /***********************************Helper methods*******************************************************/

    static int rgbToGray(int rgb) {
        int r = (rgb >> 16) & 0xff;
        int g = (rgb >> 8) & 0xff;
        int b = rgb & 0xff;
        int k = (int) (.56 * g + .33 * r + .11 * b);
        return k;
    }

    static int max(int[] t) {
        int maximum = t[0];
        for (int i = 1; i < t.length; i++) {
            if (t[i] > maximum) {
                maximum = t[i];
            }
        }
        return maximum;
    }
}