Monday 26 October 2015

SKETCH APP

To make a sketch app in android you need to apply 3 filters to your image

1-GRAYSCALE FILTER
2-INVERT THE COLORS
3- GAUSSIAN BLUR

when you succesfully apply these filters then you need to apply color dodge blend function to merge the two Images that you have created .



IS CONVERTED TO







Here is the code
to get the image and show it to the Imageview


//

public void loadImagefromGallery(View view) {
    ImageView imageView= (ImageView) findViewById(R.id.imgView1);
    imageView.setImageDrawable(null);
    imageView.setImageResource(0);
    Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    startActivityForResult(galleryIntent, RESULT_LOAD);
}

protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    super.onActivityResult(requestCode, resultCode, data);
    try {
        // When an Image is picked        if (requestCode == RESULT_LOAD && resultCode == RESULT_OK                && null != data) {
            // Get the Image from data
            Uri selectedImage = data.getData();
            String[] filePathColumn = {MediaStore.Images.Media.DATA};

            // Get the cursor            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            // Move to first row            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            img_Decodable_Str = cursor.getString(columnIndex);
            cursor.close();
            ImageView imgView = (ImageView) findViewById(R.id.imgView1);

//

CODE TO APPLY GRAYSCALE FILTER.


//

ColorMatrix matrix = new ColorMatrix();
matrix.setSaturation(0);

ColorMatrixColorFilter filter = new ColorMatrixColorFilter(matrix);
imgView.setColorFilter(filter);

//

CODE TO APPLY INVERT FILTER


//

float[] colorMatrix_Negative = {
        -1.0f, 0, 0, 0, 255, //red        0, -1.0f, 0, 0, 255, //green        0, 0, -1.0f, 0, 255, //blue        0, 0, 0, 1.0f, 0 //alpha};

ColorMatrix colorMatrix = new ColorMatrix();
colorMatrix.set(colorMatrix_Negative);

ColorFilter colorFilter_Negative = new ColorMatrixColorFilter(colorMatrix_Negative);

//

CODE FOR CONCAT TWO FILTERS


//

ColorMatrix colorMatrixConcat = new ColorMatrix();
colorMatrixConcat.setConcat(matrix, colorMatrix);

ColorMatrixColorFilter filter1 = new ColorMatrixColorFilter(colorMatrixConcat);
imgView.setColorFilter(filter1);

//

CODE FOR GAUSSIAN BLUR


//

public static Bitmap applyGaussianBlur(Bitmap src) {

    double[][] GaussianBlurConfig = new double[][]{
            {-1, 0, -1},
            {0, 4, 0},
            {-1, 0, -1}
    };

    ConvolutionMatrix convMatrix = new ConvolutionMatrix(3);

    convMatrix.applyConfig(GaussianBlurConfig);
    convMatrix.Factor = 1;
    convMatrix.Offset = 150;
    //return out put bitmap    return ConvolutionMatrix.computeConvolution3x3(src, convMatrix);
}

//


HERE IS THE FULL CODE


MAINACTIVITY.JAVA

//

package com.example.sk.sketch;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.File;
import java.io.FileOutputStream;
import java.nio.IntBuffer;
import java.util.Random;

public class MainActivity extends AppCompatActivity {
    private static int RESULT_LOAD = 1;
    String img_Decodable_Str;

    Bitmap bitmapOrg;

    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void loadImagefromGallery(View view) {
        ImageView imageView= (ImageView) findViewById(R.id.imgView1);
        imageView.setImageDrawable(null);
        imageView.setImageResource(0);
        Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(galleryIntent, RESULT_LOAD);
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        super.onActivityResult(requestCode, resultCode, data);
        try {
            // When an Image is picked            if (requestCode == RESULT_LOAD && resultCode == RESULT_OK                    && null != data) {
                // Get the Image from data
                Uri selectedImage = data.getData();
                String[] filePathColumn = {MediaStore.Images.Media.DATA};

                // Get the cursor                Cursor cursor = getContentResolver().query(selectedImage,
                        filePathColumn, null, null, null);
                // Move to first row                cursor.moveToFirst();

                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                img_Decodable_Str = cursor.getString(columnIndex);
                cursor.close();
                ImageView imgView = (ImageView) findViewById(R.id.imgView1);
                
                Bitmap bitmapImage = BitmapFactory.decodeFile(img_Decodable_Str);
                Bitmap converetdImage = getResizedBitmap(bitmapImage, 500);


                float[] colorMatrix_Negative = {
                        -1.0f, 0, 0, 0, 255, //red                        0, -1.0f, 0, 0, 255, //green                        0, 0, -1.0f, 0, 255, //blue                        0, 0, 0, 1.0f, 0 //alpha                };

                ColorMatrix colorMatrix = new ColorMatrix();
                colorMatrix.set(colorMatrix_Negative);

                ColorFilter colorFilter_Negative = new ColorMatrixColorFilter(colorMatrix_Negative);

                ColorMatrix matrix = new ColorMatrix();
                matrix.setSaturation(0);

                ColorMatrixColorFilter filter = new ColorMatrixColorFilter(matrix);
                imgView.setColorFilter(filter);

              
                imgView.setImageBitmap(converetdImage);

                Bitmap bm = ((BitmapDrawable) imgView.getDrawable()).getBitmap();


                ColorMatrix colorMatrixConcat = new ColorMatrix();
                colorMatrixConcat.setConcat(matrix, colorMatrix);

                ColorMatrixColorFilter filter1 = new ColorMatrixColorFilter(colorMatrixConcat);
                imgView.setColorFilter(filter1);

                
                imgView.setImageBitmap(applyGaussianBlur(converetdImage));
                Bitmap cm = ((BitmapDrawable) imgView.getDrawable()).getBitmap();

                Bitmap result = ColorDodgeBlend(cm, bm);
                imgView.setColorFilter(filter);

                imgView.setImageBitmap((result));

              

            } else {
                Toast.makeText(this, "Hey pick your image first",
                        Toast.LENGTH_LONG).show();
            }
        } catch (Exception e) {
            Toast.makeText(this, "Something went embrassing", Toast.LENGTH_LONG)
                    .show();
        }

    }


    private int colordodge(int in1, int in2) {
        float image = (float) in2;
        float mask = (float) in1;
        return ((int) ((image == 255) ? image : Math.min(255, (((long) mask << 8) / (255 - image)))));

    }

    public Bitmap ColorDodgeBlend(Bitmap source, Bitmap layer) {
        Bitmap base = source.copy(Bitmap.Config.ARGB_8888, true);
        Bitmap blend = layer.copy(Bitmap.Config.ARGB_8888, false);

        IntBuffer buffBase = IntBuffer.allocate(base.getWidth() * base.getHeight());
        base.copyPixelsToBuffer(buffBase);
        buffBase.rewind();

        IntBuffer buffBlend = IntBuffer.allocate(blend.getWidth() * blend.getHeight());
        blend.copyPixelsToBuffer(buffBlend);
        buffBlend.rewind();

        IntBuffer buffOut = IntBuffer.allocate(base.getWidth() * base.getHeight());
        buffOut.rewind();

        while (buffOut.position() < buffOut.limit()) {
            int filterInt = buffBlend.get();
            int srcInt = buffBase.get();

            int redValueFilter = Color.red(filterInt);
            int greenValueFilter = Color.green(filterInt);
            int blueValueFilter = Color.blue(filterInt);

            int redValueSrc = Color.red(srcInt);
            int greenValueSrc = Color.green(srcInt);
            int blueValueSrc = Color.blue(srcInt);

            int redValueFinal = colordodge(redValueFilter, redValueSrc);
            int greenValueFinal = colordodge(greenValueFilter, greenValueSrc);
            int blueValueFinal = colordodge(blueValueFilter, blueValueSrc);

            int pixel = Color.argb(255, redValueFinal, greenValueFinal, blueValueFinal);

            buffOut.put(pixel);
        }

        buffOut.rewind();

        base.copyPixelsFromBuffer(buffOut);
        blend.recycle();

        return base;
    }


    public static Bitmap applyGaussianBlur(Bitmap src) {

        double[][] GaussianBlurConfig = new double[][]{
                {-1, 0, -1},
                {0, 4, 0},
                {-1, 0, -1}
        };

        ConvolutionMatrix convMatrix = new ConvolutionMatrix(3);

        convMatrix.applyConfig(GaussianBlurConfig);
        convMatrix.Factor = 1;
        convMatrix.Offset = 150;
        //return out put bitmap        return ConvolutionMatrix.computeConvolution3x3(src, convMatrix);
    }

    public Bitmap getResizedBitmap(Bitmap image, int maxSize) {
        int width = image.getWidth();
        int height = image.getHeight();

        float bitmapRatio = (float) width / (float) height;
        if (bitmapRatio > 0) {
            width = maxSize;
            height = (int) (width / bitmapRatio);
        } else {
            height = maxSize;
            width = (int) (height * bitmapRatio);
        }
        return Bitmap.createScaledBitmap(image, width, height, true);
    }

    public void taptoshare(View v) {
        //ImageView omg= (ImageView) findViewById(R.id.imgView1);        View content = findViewById(R.id.imgView1);
        content.setDrawingCacheEnabled(true);
        Bitmap bitmap1 = content.getDrawingCache();

        String fname2 = random() + ".jpg";


        File root = Environment.getExternalStorageDirectory();
        File file = new File(root.getAbsolutePath() + "/DCIM/Camera/"+fname2);
        try {
            file.createNewFile();
            FileOutputStream ostream = new FileOutputStream(file);
            bitmap1.compress(Bitmap.CompressFormat.JPEG, 100, ostream);
            ostream.close();
            Toast toast = Toast.makeText(getApplicationContext(), "file saved",
                    Toast.LENGTH_SHORT);
            toast.setGravity(Gravity.TOP | Gravity.LEFT, 0, 0);
            toast.show();
            Intent i=new Intent(MainActivity.this,MainActivity.class);

            content.setDrawingCacheEnabled(false);
        //    omg.setImageDrawable(null);        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    public String random() {
        Random generator = new Random();
        StringBuilder randomStringBuilder = new StringBuilder();
        int randomLength = generator.nextInt(10);
        char tempChar;
        for (int i = 0; i < randomLength; i++){
            tempChar = (char) (generator.nextInt(96) + 32);
            randomStringBuilder.append(tempChar);
        }
        return randomStringBuilder.toString();
    }



//    @Override    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will        // automatically handle clicks on the Home/Up button, so long        // as you specify a parent activity in AndroidManifest.xml.        int id = item.getItemId();

        //noinspection SimplifiableIfStatement        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}


//

CONVOLUTIONMATRIX.JAVA

//

package com.example.sk.sketch;

/** * Created by sk on 10/11/2015. */import android.graphics.Bitmap;
import android.graphics.Color;

public class ConvolutionMatrix {
    public static final int SIZE = 3;

    public double[][] Matrix;
    public double Factor = 1;
    public double Offset = 1;

    //Constructor with argument of size    public ConvolutionMatrix(int size) {
        Matrix = new double[size][size];
    }

    public void setAll(double value) {
        for (int x = 0; x < SIZE; ++x) {
            for (int y = 0; y < SIZE; ++y) {
                Matrix[x][y] = value;
            }
        }
    }

    public void applyConfig(double[][] config) {
        for(int x = 0; x < SIZE; ++x) {
            for(int y = 0; y < SIZE; ++y) {
                Matrix[x][y] = config[x][y];
            }
        }
    }

    public static Bitmap computeConvolution3x3(Bitmap src, ConvolutionMatrix matrix) {
        int width = src.getWidth();
        int height = src.getHeight();
        Bitmap result = Bitmap.createBitmap(width, height, src.getConfig());

        int A, R, G, B;
        int sumR, sumG, sumB;
        int[][] pixels = new int[SIZE][SIZE];

        for(int y = 0; y < height - 2; ++y) {
            for(int x = 0; x < width - 2; ++x) {

                // get pixel matrix                for(int i = 0; i < SIZE; ++i) {
                    for(int j = 0; j < SIZE; ++j) {
                        pixels[i][j] = src.getPixel(x + i, y + j);
                    }
                }

                // get alpha of center pixel                A = Color.alpha(pixels[1][1]);

                // init color sum                sumR = sumG = sumB = 0;

                // get sum of RGB on matrix                for(int i = 0; i < SIZE; ++i) {
                    for(int j = 0; j < SIZE; ++j) {
                        sumR += (Color.red(pixels[i][j]) * matrix.Matrix[i][j]);
                        sumG += (Color.green(pixels[i][j]) * matrix.Matrix[i][j]);
                        sumB += (Color.blue(pixels[i][j]) * matrix.Matrix[i][j]);
                    }
                }

                // get final Red                R = (int)(sumR / matrix.Factor + matrix.Offset);
                if(R < 0) { R = 0; }
                else if(R > 255) { R = 255; }

                // get final Green                G = (int)(sumG / matrix.Factor + matrix.Offset);
                if(G < 0) { G = 0; }
                else if(G > 255) { G = 255; }

                // get final Blue                B = (int)(sumB / matrix.Factor + matrix.Offset);
                if(B < 0) { B = 0; }
                else if(B > 255) { B = 255; }

                // apply new pixel                result.setPixel(x + 1, y + 1, Color.argb(A, R, G, B));
            }
        }

        // final image        return result;
    }
}

//

ANDROID MANIFEST.XML

//

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.example.sk.sketch" >

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <application        android:allowBackup="true"        android:icon="@mipmap/sket"        android:label="@string/app_name"        android:theme="@style/AppTheme" >
        <activity            android:name=".MainActivity"            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>

</manifest>
//

No comments:

Post a Comment