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.Color;

public class Main {
    public static int STEP = 14;

    public static Bitmap getMosaic(Bitmap bmpOriginal) {

        int width = bmpOriginal.getWidth();
        int height = bmpOriginal.getHeight();

        int sizeW = width / STEP;
        int sizeH = height / STEP;

        int resultW = sizeW * STEP;
        int resultH = sizeH * STEP;

        Bitmap bmpMosaic = Bitmap.createBitmap(resultW, resultH, Bitmap.Config.RGB_565);

        int col;
        for (int i = 0; i < sizeH; i++)
            for (int j = 0; j < sizeW; j++) {
                col = computeAverageColor(j, i, bmpOriginal);
                fillRigeon(col, j, i, bmpMosaic);
            }

        return bmpMosaic;
    }

    /**
     * @param x X coordinate of the region
     * @param y Y coordinate of the region
     * @param bmp Source bitmap
     * @return color value of the region
     * */
    static int computeAverageColor(int x, int y, Bitmap bmp) {
        int res[] = new int[3];
        for (int col = 0; col < 3; col++) {
            for (int i = x * STEP; i < (x + 1) * STEP; i++)
                for (int j = y * STEP; j < (y + 1) * STEP; j++) {
                    switch (col) {
                    case 0: //red
                        res[0] = res[0] + Color.red(bmp.getPixel(i, j));
                        break;

                    case 1: //green
                        res[1] = res[1] + Color.green(bmp.getPixel(i, j));
                        break;

                    case 2: //blue
                        res[2] = res[2] + Color.blue(bmp.getPixel(i, j));
                        break;
                    }
                }
            res[col] = res[col] / (STEP * STEP);
        }

        return Color.rgb(res[0], res[1], res[2]);
    }

    /**
     * @param color Color of the region
     * @param x X coordinate of the region
     * @param y Y coordinate of the region
     * @param bmp Source bitmap
     * */
    static void fillRigeon(int color, int x, int y, Bitmap bmp) {

        for (int i = x * STEP; i < (x + 1) * STEP; i++)
            for (int j = y * STEP; j < (y + 1) * STEP; j++) {
                bmp.setPixel(i, j, color);
            }
    }
}