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 Bitmap applyFilter(Bitmap bmpOriginal) {
        int width = bmpOriginal.getWidth();
        int height = bmpOriginal.getHeight();

        int core[][] = { { 1, 1, 1 }, { 1, 2, 1 }, { 1, 1, 1 } };

        int[] result = new int[height * width];
        int[][] pixels2D = new int[height][width];
        for (int i = 0; i < height; i++) {
            bmpOriginal.getPixels(pixels2D[i], 0, width, 0, i, width, 1);
        }

        int count = 0;
        int R, G, B;
        for (int i = 0; i < height; i++)
            for (int j = 0; j < width; j++) {
                R = dotProduct(i, j, 0, pixels2D, core) / 10 + 20;
                G = dotProduct(i, j, 1, pixels2D, core) / 10 + 20;
                B = dotProduct(i, j, 2, pixels2D, core) / 10 + 20;

                result[count] = Color.rgb(R, G, B);
                count++;
            }

        Bitmap bmpFiltered = Bitmap.createBitmap(result, 0, width, width, height, Bitmap.Config.RGB_565);
        return bmpFiltered;
    }

    /**
     * @param x X coordinate of a pixel
     * @param y Y coordinate of a pixel
     * @param col Tone (R-0, G-1, B-2)  
     * @param pixels2D Pixel matrix
     * @param core Core
     * @return pixel tone value, calculated in accordance with the core
     * */
    static int dotProduct(int x, int y, int col, int[][] pixels2D, int[][] core) {
        int sum = 0;

        int px = 1;
        for (int i = -1; i < 1; i++)
            for (int j = -1; j < 1; j++) {
                if ((x + i < 0) || (y + j < 0))
                    px = 1;
                else {
                    switch (col) {
                    case 0: //red
                        px = Color.red(pixels2D[x + i][y + j]);
                        break;

                    case 1: //green
                        px = Color.green(pixels2D[x + i][y + j]);
                        break;

                    case 2: //blue
                        px = Color.blue(pixels2D[x + i][y + j]);
                        break;
                    }
                }
                sum = sum + core[i + 1][j + 1] * px;
            }
        return sum;
    }
}