Showing posts with label Android code sample: bitmap and image. Show all posts
Showing posts with label Android code sample: bitmap and image. Show all posts

Draw bitmap programmatically for SurfaceView

This exercise create Bitmap programmatically, then draw the bitmap on SurfaceView by calling canvas.drawBitmap().

Draw bitmap programmatically for SurfaceView


I show two approachs in the example:
  • prepareBitmap_A:
    - Create a array of int, fill in data point-by-point, then createBitmap from the array.
  • prepareBitmap_B:
    - Create a bitmap, then fill in pixels by calling setPixel.

I also add code to display the (approximate) processing time in various steps for reference. The videos on the bottom show the result.

MySurfaceView.java
package com.example.androidsurfaceview;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.util.AttributeSet;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class MySurfaceView extends SurfaceView {

private SurfaceHolder surfaceHolder;
private MyThread myThread;

MainActivity mainActivity;

long timeStart;
long timeA;
long timeB;
long timeFillBackground;
long timeDrawBitmap;
long timeTotal;

long numberOfPt;

public MySurfaceView(Context context) {
super(context);
init(context);
}

public MySurfaceView(Context context,
AttributeSet attrs) {
super(context, attrs);
init(context);
}

public MySurfaceView(Context context,
AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context);
}

private void init(Context c){
mainActivity = (MainActivity)c;
numberOfPt = 0;
myThread = new MyThread(this);

surfaceHolder = getHolder();


surfaceHolder.addCallback(new SurfaceHolder.Callback(){

@Override
public void surfaceCreated(SurfaceHolder holder) {
myThread.setRunning(true);
myThread.start();
}

@Override
public void surfaceChanged(SurfaceHolder holder,
int format, int width, int height) {
// TODO Auto-generated method stub

}

@Override
public void surfaceDestroyed(SurfaceHolder holder) {
boolean retry = true;
myThread.setRunning(false);
while (retry) {
try {
myThread.join();
retry = false;
} catch (InterruptedException e) {
}
}
}});
}

private Bitmap prepareBitmap_A(int w, int h, long cnt){
int[] data = new int[w*h];

//fill with dummy data
for(int x=0; x<w; x++){
for(int y=0; y<h; y++){
//data[x + y*w] = 0xFF000000 + x;

if(cnt>=0){
data[x + y*w] = 0xFFff0000;
cnt--;
}else{
data[x + y*w] = 0xFFa0a0a0;
}

}
}
timeA = System.currentTimeMillis();
Bitmap bm = Bitmap.createBitmap(data, w, h, Bitmap.Config.ARGB_8888);
timeB = System.currentTimeMillis();
return bm;
}

private Bitmap prepareBitmap_B(int w, int h, long cnt){

Bitmap bm = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
timeA = System.currentTimeMillis();

//fill with dummy data
for(int x=0; x<w; x++){
for(int y=0; y<h; y++){
//data[x + y*w] = 0xFF000000 + x;

if(cnt>=0){
bm.setPixel(x, y, 0xFFff0000);
cnt--;
}else{
bm.setPixel(x, y, 0xFFa0a0a0);
}

}
}
timeB = System.currentTimeMillis();
return bm;
}

protected void drawSomething(Canvas canvas) {

numberOfPt += 500;
if(numberOfPt > (long)((getWidth()*getHeight()))){
numberOfPt = 0;
}

timeStart = System.currentTimeMillis();
Bitmap bmDummy = prepareBitmap_A(getWidth(), getHeight(), numberOfPt);

canvas.drawColor(Color.BLACK);
timeFillBackground = System.currentTimeMillis();
canvas.drawBitmap(bmDummy,
0, 0, null);
timeDrawBitmap = System.currentTimeMillis();

mainActivity.runOnUiThread(new Runnable() {

@Override
public void run() {
mainActivity.showDur(
timeA - timeStart,
timeB - timeA,
timeFillBackground - timeB,
timeDrawBitmap - timeFillBackground,
timeDrawBitmap - timeStart);
}
});
}

}

Modify activity_main.xml to add TextView to display processing time.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.androidsurfaceview.MainActivity" >

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:autoLink="web"
android:text="http://arteluzevida.blogspot.com/"
android:textStyle="bold" />

<TextView
android:id="@+id/durA"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Duration: " />
<TextView
android:id="@+id/durB"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Duration: " />
<TextView
android:id="@+id/durFillBack"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Duration: " />
<TextView
android:id="@+id/durDrawBM"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Duration: " />
<TextView
android:id="@+id/durTotal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Duration: " />

<com.example.androidsurfaceview.MySurfaceView
android:layout_width="match_parent"
android:layout_height="match_parent" />

</LinearLayout>

MainActivity.java
package com.example.androidsurfaceview;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends Activity {

TextView textDurA, textDurB, textDurFillBack,
textDurDrawBM, textDurTotal;

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

textDurA = (TextView)findViewById(R.id.durA);
textDurB = (TextView)findViewById(R.id.durB);
textDurFillBack = (TextView)findViewById(R.id.durFillBack);
textDurDrawBM = (TextView)findViewById(R.id.durDrawBM);
textDurTotal = (TextView)findViewById(R.id.durTotal);

}

protected void showDur(long dA, long dB, long dFill, long dDraw, long dTotal){
textDurA.setText("Duration(ms) - A: " + dA);
textDurB.setText("Duration(ms) - B: " + dB);
textDurFillBack.setText("Duration(ms) - Fill Background: " + dFill);
textDurDrawBM.setText("Duration(ms) - drawBitmap: " + dDraw);
textDurTotal.setText("Duration(ms) - Total: " + dTotal);
}

}

MyThread.java refer to last exercise, "Create animation on SurfaceView in background Thread".


download filesDownload the files.

prepareBitmap_A:

prepareBitmap_B:

Sharpen bitmap using Convolution

The previous exercise "Blur bitmap using Convolution". By changing the matrix of Convolution class, we can use it to sharpen bitmap.

 class Convolution {

// matrix to sharpen image
int[][] matrix = { { 0, -1, 0 }, { -1, 5, -1 }, { 0, -1, 0 } };
...


Sharpen bitmap using Convolution




more: Something about processing images in Android

Blur bitmap using Convolution

The previous exercise blur bitmap by averaging pixels with surrounding pixels. In this exercise, we are going to implement a class of Convolution, to blur bitmap with Convolution Matrix.

Blur bitmap using Convolution


package com.example.androiddrawbitmap;

import java.io.FileNotFoundException;

import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

public class MainActivity extends Activity {

Button btnLoadImage;
ImageView imageResult, imageOriginal;
TextView textDur;

final int RQS_IMAGE1 = 1;

Uri source;
Bitmap bitmapMaster;
Canvas canvasMaster;

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

btnLoadImage = (Button) findViewById(R.id.loadimage);
imageResult = (ImageView) findViewById(R.id.result);
imageOriginal = (ImageView) findViewById(R.id.original);
textDur = (TextView) findViewById(R.id.dur);

btnLoadImage.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View arg0) {
Intent intent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, RQS_IMAGE1);
}
});
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);

if (resultCode == RESULT_OK) {
switch (requestCode) {
case RQS_IMAGE1:
source = data.getData();

try {
bitmapMaster = BitmapFactory
.decodeStream(getContentResolver().openInputStream(
source));

imageOriginal.setImageBitmap(bitmapMaster);
loadBlurBitmap(bitmapMaster);

} catch (FileNotFoundException e) {
e.printStackTrace();
}

break;
}
}
}

private void loadBlurBitmap(Bitmap src) {
if (src != null) {

Bitmap bmBlur;
Convolution convolution = new Convolution();

long startTime = System.currentTimeMillis();
bmBlur = convolution.convBitmap(src);
long duration = System.currentTimeMillis() - startTime;

imageResult.setImageBitmap(bmBlur);
textDur.setText("processing duration(ms): " + duration);
}
}

class Convolution {

// matrix to blur image
int[][] matrix = { { 1, 1, 1 }, { 1, 1, 1 }, { 1, 1, 1 } };
// kernal_width x kernal_height = dimension pf matrix
// halfWidth = (kernal_width - 1)/2
// halfHeight = (kernal_height - 1)/2
int kernal_width = 3;
int kernal_height = 3;
int kernal_halfWidth = 1;
int kernal_halfHeight = 1;

public Bitmap convBitmap(Bitmap src) {

int[][] sourceMatrix = new int[kernal_width][kernal_height];

// averageWeight = total of matrix[][]. The result of each
// pixel will be divided by averageWeight to get the average
int averageWeight = 0;
for (int i = 0; i < kernal_width; i++) {
for (int j = 0; j < kernal_height; j++) {
averageWeight += matrix[i][j];
}
}
if (averageWeight == 0) {
averageWeight = 1;
}

int pixelR, pixelG, pixelB, pixelA;

int w = src.getWidth();
int h = src.getHeight();
Bitmap bm = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);

// fill sourceMatrix with surrounding pixel
for (int x = 0; x < w; x++) {
for (int y = 0; y < h; y++) {

for (int xk = 0; xk < kernal_width; xk++) {
for (int yk = 0; yk < kernal_height; yk++) {
int px = x + xk - kernal_halfWidth;
int py = y + yk - kernal_halfHeight;

if (px < 0) {
px = 0;
} else if (px >= w) {
px = w - 1;
}

if (py < 0) {
py = 0;
} else if (py >= h) {
py = h - 1;
}

sourceMatrix[xk][yk] = src.getPixel(px, py);

}
}

pixelR = pixelG = pixelB = pixelA = 0;

for (int k = 0; k < kernal_width; k++) {
for (int l = 0; l < kernal_height; l++) {

pixelR += Color.red(sourceMatrix[k][l])
* matrix[k][l];
pixelG += Color.green(sourceMatrix[k][l])
* matrix[k][l];
pixelB += Color.blue(sourceMatrix[k][l])
* matrix[k][l];
pixelA += Color.alpha(sourceMatrix[k][l])
* matrix[k][l];
}
}
pixelR = pixelR / averageWeight;
pixelG = pixelG / averageWeight;
pixelB = pixelB / averageWeight;
pixelA = pixelA / averageWeight;

if (pixelR < 0) {
pixelR = 0;
} else if (pixelR > 255) {
pixelR = 255;
}

if (pixelG < 0) {
pixelG = 0;
} else if (pixelG > 255) {
pixelG = 255;
}

if (pixelB < 0) {
pixelB = 0;
} else if (pixelB > 255) {
pixelB = 255;
}

if (pixelA < 0) {
pixelA = 0;
} else if (pixelA > 255) {
pixelA = 255;
}

bm.setPixel(x, y,
Color.argb(pixelA, pixelR, pixelG, pixelB));
}
}

return bm;
}
}
}


Keep using layout in the post Blur bitmap.

download filesDownload the files.

download filesDownload and try the APK.

Next: By changing the matrix in Convolution class, we can use it to sharpen bitmap.


more: Something about processing images in Android

Blur bitmap

This exercise generate a blur bitmap by changing each pixel to the average of its surrounding 5x5 pixel.

Blur bitmap


package com.example.androiddrawbitmap;

import java.io.FileNotFoundException;

import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

public class MainActivity extends Activity {

Button btnLoadImage;
ImageView imageResult, imageOriginal;
TextView textDur;

final int RQS_IMAGE1 = 1;

Uri source;
Bitmap bitmapMaster;
Canvas canvasMaster;

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

btnLoadImage = (Button) findViewById(R.id.loadimage);
imageResult = (ImageView) findViewById(R.id.result);
imageOriginal = (ImageView)findViewById(R.id.original);
textDur = (TextView)findViewById(R.id.dur);

btnLoadImage.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View arg0) {
Intent intent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, RQS_IMAGE1);
}
});
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);

if (resultCode == RESULT_OK) {
switch (requestCode) {
case RQS_IMAGE1:
source = data.getData();

try {
bitmapMaster = BitmapFactory
.decodeStream(getContentResolver().openInputStream(
source));

imageOriginal.setImageBitmap(bitmapMaster);
loadBlurBitmap(bitmapMaster);

} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

break;
}
}
}

private void loadBlurBitmap(Bitmap src) {
if (src != null) {

Bitmap bmBlur;

long startTime = System.currentTimeMillis();
bmBlur = getBlurBitmap(src);
long duration = System.currentTimeMillis() - startTime;

imageResult.setImageBitmap(bmBlur);
textDur.setText("processing duration(ms): " + duration);
}
}

private Bitmap getBlurBitmap(Bitmap src) {

final int widthKernal = 5;
final int heightKernal = 5;

int w = src.getWidth();
int h = src.getHeight();

Bitmap blurBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);

for (int x = 0; x < w; x++) {
for (int y = 0; y < h; y++) {

int r = 0;
int g = 0;
int b = 0;
int a = 0;

for (int xk = 0; xk < widthKernal; xk++) {
for (int yk = 0; yk < heightKernal; yk++) {
int px = x + xk -2;
int py = y + yk -2;

if(px < 0){
px = 0;
}else if(px >= w){
px = w-1;
}

if(py < 0){
py = 0;
}else if(py >= h){
py = h-1;
}

int intColor = src.getPixel(px, py);
r += Color.red(intColor);
g += Color.green(intColor);
b += Color.blue(intColor);
a += Color.alpha(intColor);

}
}

blurBitmap.setPixel(x, y, Color.argb(a/25, r/25, g/25, b/25));

}
}

return blurBitmap;
}

}


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/background_dark"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:autoLink="web"
android:text="http://arteluzevida.blogspot.com/"
android:textStyle="bold" />

<Button
android:id="@+id/loadimage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Load Image 1" />

<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<ImageView
android:id="@+id/original"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:scaleType="fitXY" />
<ImageView
android:id="@+id/result"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:scaleType="fitXY" />
<TextView
android:id="@+id/dur"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
</ScrollView>
</LinearLayout>

download filesDownload the files.

download filesDownload and try the APK.



more: Something about processing images in Android

Example to apply BlurMaskFilter on Bitmap

apply BlurMaskFilter on Bitmap


package com.example.androiddrawbitmap;

import java.io.FileNotFoundException;

import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BlurMaskFilter;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;

public class MainActivity extends Activity {

Button btnLoadImage;
ImageView imageResult;

final int RQS_IMAGE1 = 1;

Uri source;
Bitmap bitmapMaster;
Canvas canvasMaster;

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

btnLoadImage = (Button) findViewById(R.id.loadimage);
imageResult = (ImageView) findViewById(R.id.result);

btnLoadImage.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View arg0) {
Intent intent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, RQS_IMAGE1);
}
});
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);

if (resultCode == RESULT_OK) {
switch (requestCode) {
case RQS_IMAGE1:
source = data.getData();

try {
bitmapMaster = BitmapFactory
.decodeStream(getContentResolver().openInputStream(
source));
loadGrayBitmap(bitmapMaster);

} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

break;
}
}
}

private void loadGrayBitmap(Bitmap src) {
if (src != null) {

int w = src.getWidth();
int h = src.getHeight();
RectF rectF = new RectF(w/4, h/4, w*3/4, h*3/4);
float blurRadius = 100.0f;

Bitmap bitmapResult = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
Canvas canvasResult = new Canvas(bitmapResult);

Paint blurPaintOuter = new Paint();
blurPaintOuter.setColor(0xFFffffff);
blurPaintOuter.setMaskFilter(new
BlurMaskFilter(blurRadius, BlurMaskFilter.Blur.INNER));
canvasResult.drawBitmap(bitmapMaster, 0, 0, blurPaintOuter);

Paint blurPaintInner = new Paint();
blurPaintInner.setColor(0xFFffffff);
blurPaintInner.setMaskFilter(new
BlurMaskFilter(blurRadius, BlurMaskFilter.Blur.OUTER));
canvasResult.drawRect(rectF, blurPaintInner);

imageResult.setImageBitmap(bitmapResult);
}
}
}


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:background="@android:color/background_dark"
tools:context=".MainActivity" >

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:autoLink="web"
android:text="http://arteluzevida.blogspot.com/"
android:textStyle="bold" />

<Button
android:id="@+id/loadimage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Load Image 1" />

<ImageView
android:id="@+id/result"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:scaleType="centerInside" />

</LinearLayout>


download filesDownload the files.



more: Something about processing images in Android

Convert Bitmap to gray-scale with ColorMatrix

To convert Bitmap to gray-scale, we can apply ColorMatrix with the following matrix:

   //Array to generate Gray-Scale image
float[] GrayArray = {
0.213f, 0.715f, 0.072f, 0.0f, 0.0f,
0.213f, 0.715f, 0.072f, 0.0f, 0.0f,
0.213f, 0.715f, 0.072f, 0.0f, 0.0f,
0.0f, 0.0f, 0.0f, 1.0f, 0.0f,
};

Convert Bitmap to gray-scale with ColorMatrix


package com.example.androiddrawbitmap;

import java.io.FileNotFoundException;

import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Paint;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;

public class MainActivity extends Activity {

Button btnLoadImage;
ImageView imageResult;

final int RQS_IMAGE1 = 1;

Uri source;
Bitmap bitmapMaster;
Canvas canvasMaster;

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

btnLoadImage = (Button) findViewById(R.id.loadimage);
imageResult = (ImageView) findViewById(R.id.result);

btnLoadImage.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View arg0) {
Intent intent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, RQS_IMAGE1);
}
});

}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);

if (resultCode == RESULT_OK) {
switch (requestCode) {
case RQS_IMAGE1:
source = data.getData();

try {
bitmapMaster = BitmapFactory
.decodeStream(getContentResolver().openInputStream(
source));
loadGrayBitmap(bitmapMaster);

} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

break;
}
}
}

private void loadGrayBitmap(Bitmap src) {
if (src != null) {

//Array to generate Identity image
float[] IdentityArray = {
1.0f, 0.0f, 0.0f, 0.0f, 0.0f,
0.0f, 1.0f, 0.0f, 0.0f, 0.0f,
0.0f, 0.0f, 1.0f, 0.0f, 0.0f,
0.0f, 0.0f, 0.0f, 1.0f, 0.0f,
};

//Array to generate Gray-Scale image
float[] GrayArray = {
0.213f, 0.715f, 0.072f, 0.0f, 0.0f,
0.213f, 0.715f, 0.072f, 0.0f, 0.0f,
0.213f, 0.715f, 0.072f, 0.0f, 0.0f,
0.0f, 0.0f, 0.0f, 1.0f, 0.0f,
};

ColorMatrix colorMatrixGray = new ColorMatrix(GrayArray);

int w = src.getWidth();
int h = src.getHeight();

Bitmap bitmapResult = Bitmap
.createBitmap(w, h, Bitmap.Config.ARGB_8888);
Canvas canvasResult = new Canvas(bitmapResult);
Paint paint = new Paint();

ColorMatrixColorFilter filter = new ColorMatrixColorFilter(colorMatrixGray);
paint.setColorFilter(filter);
canvasResult.drawBitmap(src, 0, 0, paint);

imageResult.setImageBitmap(bitmapResult);
}
}

}


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:autoLink="web"
android:text="http://arteluzevida.blogspot.com/"
android:textStyle="bold" />

<Button
android:id="@+id/loadimage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Load Image 1" />

<ImageView
android:id="@+id/result"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:background="@android:color/background_dark"
android:scaleType="centerInside" />

</LinearLayout>


download filesDownload the files.

download filesDownload and try the APK.

Remark: This exercise aim to demonstrate the matrix. Actually you can setSaturation(0) of  ColorMatrix to do the same effect.



more: Something about processing images in Android

ColorMatrix.setConcat() to combine ColorMatrixes

The exercise "Set the rotation on a color axis of Bitmap with ColorMatrix" create rotated ColorMatrix for one color only, not all. We can create ColorMatrix from more than one by calling ColorMatrix.setConcat().

ColorMatrix.setConcat() to combine ColorMatrixs


package com.example.androiddrawbitmap;

import java.io.FileNotFoundException;

import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Paint;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;

public class MainActivity extends Activity {

Button btnLoadImage;
ImageView imageResult;
SeekBar rotBarRed, rotBarGreen, rotBarBlue;
TextView rotText;

final int RQS_IMAGE1 = 1;

Uri source;
Bitmap bitmapMaster;
Canvas canvasMaster;

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

btnLoadImage = (Button) findViewById(R.id.loadimage);
imageResult = (ImageView) findViewById(R.id.result);

btnLoadImage.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View arg0) {
Intent intent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, RQS_IMAGE1);
}
});

rotText = (TextView) findViewById(R.id.textRot);
rotBarRed = (SeekBar) findViewById(R.id.rotbarred);
rotBarGreen = (SeekBar) findViewById(R.id.rotbargreen);
rotBarBlue = (SeekBar) findViewById(R.id.rotbarblue);
rotBarRed.setOnSeekBarChangeListener(seekBarChangeListener);
rotBarGreen.setOnSeekBarChangeListener(seekBarChangeListener);
rotBarBlue.setOnSeekBarChangeListener(seekBarChangeListener);

}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);

if (resultCode == RESULT_OK) {
switch (requestCode) {
case RQS_IMAGE1:
source = data.getData();

try {
bitmapMaster = BitmapFactory
.decodeStream(getContentResolver().openInputStream(
source));

rotBarRed.setProgress(0);
rotBarGreen.setProgress(0);
rotBarBlue.setProgress(0);

loadBitmapRotate();

} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

break;
}
}
}

OnSeekBarChangeListener seekBarChangeListener = new OnSeekBarChangeListener() {

@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub

}

@Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub

}

@Override
public void onStopTrackingTouch(SeekBar seekBar) {
loadBitmapRotate();
}
};

private void loadBitmapRotate() {
if (bitmapMaster != null) {

float rotRed = (float) rotBarRed.getProgress();
float rotGreen = (float) rotBarGreen.getProgress();
float rotBlue = (float) rotBarBlue.getProgress();

rotText.setText("setRotate: " + String.valueOf(rotRed) + ", "
+ String.valueOf(rotGreen) + ", " + String.valueOf(rotBlue));

Bitmap bitmapColorScaled = updateRot(bitmapMaster, rotRed,
rotGreen, rotBlue);

imageResult.setImageBitmap(bitmapColorScaled);
}
}

private Bitmap updateRot(Bitmap src, float degreesRed, float degreesGreen,
float degreesBlue) {

int w = src.getWidth();
int h = src.getHeight();

Bitmap bitmapResult = Bitmap
.createBitmap(w, h, Bitmap.Config.ARGB_8888);
Canvas canvasResult = new Canvas(bitmapResult);
Paint paint = new Paint();

ColorMatrix colorMatrixRed = new ColorMatrix();
colorMatrixRed.setRotate(0, degreesRed);
ColorMatrix colorMatrixGreen = new ColorMatrix();
colorMatrixGreen.setRotate(1, degreesGreen);
ColorMatrix colorMatrixBlue = new ColorMatrix();
colorMatrixBlue.setRotate(2, degreesBlue);
ColorMatrix colorMatrixConcat = new ColorMatrix();
colorMatrixConcat.setConcat(colorMatrixRed, colorMatrixGreen);
colorMatrixConcat.setConcat(colorMatrixConcat, colorMatrixBlue);

ColorMatrixColorFilter filter = new ColorMatrixColorFilter(
colorMatrixConcat);
paint.setColorFilter(filter);
canvasResult.drawBitmap(src, 0, 0, paint);

return bitmapResult;
}
}


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:autoLink="web"
android:text="http://arteluzevida.blogspot.com/"
android:textStyle="bold" />

<Button
android:id="@+id/loadimage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Load Image 1" />

<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent" >

<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >

<ImageView
android:id="@+id/result"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:background="@android:color/background_dark"
android:scaleType="centerInside" />

<TextView
android:id="@+id/textRot"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="ColorMatrix Rotate" />

<SeekBar
android:id="@+id/rotbarred"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:max="360"
android:progress="0" />
<SeekBar
android:id="@+id/rotbargreen"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:max="360"
android:progress="0" />
<SeekBar
android:id="@+id/rotbarblue"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:max="360"
android:progress="0" />
</LinearLayout>
</ScrollView>

</LinearLayout>


download filesDownload the files.

download filesDownload and try the APK.



more: Something about processing images in Android

Scale color and alpha of colormatrix with setScale()

Example of using ColorMatrix.setScale(float rScale, float gScale, float bScale, float aScale).

Example of using ColorMatrix.setScale()

package com.example.androiddrawbitmap;

import java.io.FileNotFoundException;

import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Paint;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;

public class MainActivity extends Activity {

Button btnLoadImage;
ImageView imageResult;
SeekBar scaleBarRed, scaleBarGreen, scaleBarBlue, scaleBarAlpha;
TextView cmScaleText;

final int RQS_IMAGE1 = 1;

Uri source;
Bitmap bitmapMaster;
Canvas canvasMaster;

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

btnLoadImage = (Button) findViewById(R.id.loadimage);
imageResult = (ImageView) findViewById(R.id.result);

btnLoadImage.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View arg0) {
Intent intent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, RQS_IMAGE1);
}
});

cmScaleText = (TextView) findViewById(R.id.textCMScale);
scaleBarRed = (SeekBar) findViewById(R.id.scalebarred);
scaleBarGreen = (SeekBar) findViewById(R.id.scalebargreen);
scaleBarBlue = (SeekBar) findViewById(R.id.scalebarblue);
scaleBarAlpha = (SeekBar) findViewById(R.id.scalebaralpha);
scaleBarRed.setOnSeekBarChangeListener(seekBarChangeListener);
scaleBarGreen.setOnSeekBarChangeListener(seekBarChangeListener);
scaleBarBlue.setOnSeekBarChangeListener(seekBarChangeListener);
scaleBarAlpha.setOnSeekBarChangeListener(seekBarChangeListener);

}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);

if (resultCode == RESULT_OK) {
switch (requestCode) {
case RQS_IMAGE1:
source = data.getData();

try {
bitmapMaster = BitmapFactory
.decodeStream(getContentResolver().openInputStream(
source));

scaleBarRed.setProgress(100);
scaleBarGreen.setProgress(100);
scaleBarBlue.setProgress(100);
scaleBarAlpha.setProgress(100);

loadBitmapScaleColor();

} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

break;
}
}
}

OnSeekBarChangeListener seekBarChangeListener =
new OnSeekBarChangeListener() {

@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub

}

@Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub

}

@Override
public void onStopTrackingTouch(SeekBar seekBar) {
loadBitmapScaleColor();
}
};

private void loadBitmapScaleColor() {
if (bitmapMaster != null) {

int progressScaleRed = scaleBarRed.getProgress();
int progressScaleGreen = scaleBarGreen.getProgress();
int progressScaleBlue = scaleBarBlue.getProgress();
int progressScaleAlpha = scaleBarAlpha.getProgress();

float scaleRed = (float) progressScaleRed/100;
float scaleGreen = (float) progressScaleGreen/100;
float scaleBlue = (float) progressScaleBlue/100;
float scaleAlpha = (float) progressScaleAlpha/100;

cmScaleText.setText("setScale: "
+ String.valueOf(scaleRed) + ", "
+ String.valueOf(scaleGreen) + ", "
+ String.valueOf(scaleBlue) + ", "
+ String.valueOf(scaleAlpha));

Bitmap bitmapColorScaled = updateScale(
bitmapMaster,
scaleRed,
scaleGreen,
scaleBlue,
scaleAlpha);

imageResult.setImageBitmap(bitmapColorScaled);
}
}

private Bitmap updateScale(Bitmap src, float rScale, float gScale,
float bScale, float aScale) {

int w = src.getWidth();
int h = src.getHeight();

Bitmap bitmapResult = Bitmap
.createBitmap(w, h, Bitmap.Config.ARGB_8888);
Canvas canvasResult = new Canvas(bitmapResult);
Paint paint = new Paint();
ColorMatrix colorMatrix = new ColorMatrix();
colorMatrix.setScale(rScale, gScale, bScale, aScale);
ColorMatrixColorFilter filter = new ColorMatrixColorFilter(colorMatrix);
paint.setColorFilter(filter);
canvasResult.drawBitmap(src, 0, 0, paint);

return bitmapResult;
}
}


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:autoLink="web"
android:text="http://arteluzevida.blogspot.com/"
android:textStyle="bold" />

<Button
android:id="@+id/loadimage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Load Image 1" />

<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent" >

<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >

<ImageView
android:id="@+id/result"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:background="@drawable/ic_launcher"
android:scaleType="centerInside" />

<TextView
android:id="@+id/textCMScale"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="ColorMatrix Scale" />

<SeekBar
android:id="@+id/scalebarred"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:max="200"
android:progress="100" />
<SeekBar
android:id="@+id/scalebargreen"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:max="200"
android:progress="100" />
<SeekBar
android:id="@+id/scalebarblue"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:max="200"
android:progress="100" />
<SeekBar
android:id="@+id/scalebaralpha"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:max="200"
android:progress="100" />
</LinearLayout>
</ScrollView>

</LinearLayout>


download filesDownload the files.

download filesDownload and try the APK.



more: Something about processing images in Android

Set the rotation on a color axis of Bitmap with ColorMatrix

Example to set the rotation on a color axis by the specified values. axis=0 correspond to a rotation around the RED color axis=1 correspond to a rotation around the GREEN color axis=2 correspond to a rotation around the BLUE color.

rotation on a color axis of Bitmap with ColorMatrix

package com.example.androiddrawbitmap;

import java.io.FileNotFoundException;

import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Paint;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;

public class MainActivity extends Activity {

Button btnLoadImage;
ImageView imageResult;
SeekBar rotBar;
TextView rotText;

RadioGroup groupAxis;
RadioButton optAxisRed, optAxisGreen, optAxisBlue;

final int RQS_IMAGE1 = 1;

Uri source;
Bitmap bitmapMaster;
Canvas canvasMaster;

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

btnLoadImage = (Button) findViewById(R.id.loadimage);
imageResult = (ImageView) findViewById(R.id.result);

btnLoadImage.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View arg0) {
Intent intent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, RQS_IMAGE1);
}
});

rotText = (TextView) findViewById(R.id.textRot);
rotBar = (SeekBar) findViewById(R.id.rotbar);
rotBar.setOnSeekBarChangeListener(seekBarChangeListener);

groupAxis = (RadioGroup) findViewById(R.id.axisgroup);
optAxisRed = (RadioButton) findViewById(R.id.axisred);
optAxisGreen = (RadioButton) findViewById(R.id.axisgreen);
optAxisBlue = (RadioButton) findViewById(R.id.axisblue);
groupAxis.setOnCheckedChangeListener(groupAxisOnCheckedChangeListener);

}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);

if (resultCode == RESULT_OK) {
switch (requestCode) {
case RQS_IMAGE1:
source = data.getData();

try {
bitmapMaster = BitmapFactory
.decodeStream(getContentResolver().openInputStream(
source));

optAxisRed.setChecked(true);
rotBar.setProgress(0);

loadBitmapSat();

} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

break;
}
}
}

OnSeekBarChangeListener seekBarChangeListener =
new OnSeekBarChangeListener() {

@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub

}

@Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub

}

@Override
public void onStopTrackingTouch(SeekBar seekBar) {
loadBitmapSat();
}
};

OnCheckedChangeListener groupAxisOnCheckedChangeListener =
new OnCheckedChangeListener() {

@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
loadBitmapSat();
}
};

private void loadBitmapSat() {
if (bitmapMaster != null) {

int progressRot = rotBar.getProgress();

float rotDegree = (float) progressRot;

if (optAxisRed.isChecked()) {
rotText.setText("setRotate: " + "Red: "
+ String.valueOf(rotDegree));
imageResult
.setImageBitmap(updateRot(bitmapMaster, 0, rotDegree));
} else if (optAxisGreen.isChecked()) {
rotText.setText("setRotate: " + "Green: "
+ String.valueOf(rotDegree));
imageResult
.setImageBitmap(updateRot(bitmapMaster, 1, rotDegree));
} else if (optAxisBlue.isChecked()) {
rotText.setText("setRotate: " + "Blue: "
+ String.valueOf(rotDegree));
imageResult
.setImageBitmap(updateRot(bitmapMaster, 2, rotDegree));
}
}
}

private Bitmap updateRot(Bitmap src, int axis, float degrees) {

int w = src.getWidth();
int h = src.getHeight();

Bitmap bitmapResult = Bitmap
.createBitmap(w, h, Bitmap.Config.ARGB_8888);
Canvas canvasResult = new Canvas(bitmapResult);
Paint paint = new Paint();
ColorMatrix colorMatrix = new ColorMatrix();
colorMatrix.setRotate(axis, degrees);
ColorMatrixColorFilter filter = new ColorMatrixColorFilter(colorMatrix);
paint.setColorFilter(filter);
canvasResult.drawBitmap(src, 0, 0, paint);

return bitmapResult;
}
}


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:autoLink="web"
android:text="http://arteluzevida.blogspot.com/"
android:textStyle="bold" />

<Button
android:id="@+id/loadimage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Load Image 1" />

<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent" >

<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >

<ImageView
android:id="@+id/result"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:background="@android:color/background_dark"
android:scaleType="centerInside" />

<TextView
android:id="@+id/textRot"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Rotate Axis" />

<RadioGroup
android:id="@+id/axisgroup"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >

<RadioButton
android:id="@+id/axisred"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:checked="true"
android:text="Red" />

<RadioButton
android:id="@+id/axisgreen"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Green" />

<RadioButton
android:id="@+id/axisblue"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Blue" />
</RadioGroup>

<SeekBar
android:id="@+id/rotbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:max="360"
android:progress="0" />
</LinearLayout>
</ScrollView>

</LinearLayout>


download filesDownload the files.

download filesDownload and try the APK.

Related: Combine ColorMatrixes by calling setConcat().


more: Something about processing images in Android

Adjust saturation of Bitmap with ColorMatrix

android.graphics.ColorMatrix is a 5x4 matrix for transforming the color+alpha components of a Bitmap. The setSaturation(float sat) method of ColorMatrix set the matrix to affect the saturation of colors. A value of 0 maps the color to gray-scale. 1 is identity.

This example demonstrate how to generate a bitmap with adjusted saturation using ColorMatrix.setSaturation().

Adjust saturation of Bitmap with ColorMatrix

package com.example.androiddrawbitmap;

import java.io.FileNotFoundException;

import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Paint;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;

public class MainActivity extends Activity {

Button btnLoadImage;
TextView textSource;
ImageView imageResult;
SeekBar satBar;
TextView satText;

final int RQS_IMAGE1 = 1;

Uri source;
Bitmap bitmapMaster;
Canvas canvasMaster;

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

btnLoadImage = (Button) findViewById(R.id.loadimage);
textSource = (TextView) findViewById(R.id.sourceuri);
imageResult = (ImageView) findViewById(R.id.result);

btnLoadImage.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View arg0) {
Intent intent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, RQS_IMAGE1);
}
});

satText = (TextView) findViewById(R.id.textsat);
satBar = (SeekBar) findViewById(R.id.satbar);
satBar.setOnSeekBarChangeListener(seekBarChangeListener);

}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);

if (resultCode == RESULT_OK) {
switch (requestCode) {
case RQS_IMAGE1:
source = data.getData();

try {
bitmapMaster = BitmapFactory
.decodeStream(getContentResolver().openInputStream(
source));

satBar.setProgress(256);

loadBitmapSat();

} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

break;
}
}
}

OnSeekBarChangeListener seekBarChangeListener = new OnSeekBarChangeListener() {

@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub

}

@Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub

}

@Override
public void onStopTrackingTouch(SeekBar seekBar) {
loadBitmapSat();
}
};

private void loadBitmapSat() {
if (bitmapMaster != null) {

int progressSat = satBar.getProgress();

//Saturation, 0=gray-scale. 1=identity
float sat = (float) progressSat / 256;
satText.setText("Saturation: " + String.valueOf(sat));
imageResult.setImageBitmap(updateSat(bitmapMaster, sat));
}
}

private Bitmap updateSat(Bitmap src, float settingSat) {

int w = src.getWidth();
int h = src.getHeight();

Bitmap bitmapResult =
Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
Canvas canvasResult = new Canvas(bitmapResult);
Paint paint = new Paint();
ColorMatrix colorMatrix = new ColorMatrix();
colorMatrix.setSaturation(settingSat);
ColorMatrixColorFilter filter = new ColorMatrixColorFilter(colorMatrix);
paint.setColorFilter(filter);
canvasResult.drawBitmap(src, 0, 0, paint);

return bitmapResult;
}
}


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:autoLink="web"
android:text="http://arteluzevida.blogspot.com/"
android:textStyle="bold" />

<Button
android:id="@+id/loadimage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Load Image 1" />

<TextView
android:id="@+id/sourceuri"
android:layout_width="match_parent"
android:layout_height="wrap_content" />

<ImageView
android:id="@+id/result"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:background="@android:color/background_dark"
android:scaleType="centerInside" />

<TextView
android:id="@+id/textsat"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Saturation" />
<SeekBar
android:id="@+id/satbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:max="512"
android:progress="256"/>

</LinearLayout>


download filesDownload the files.

download filesDownload and try the APK.



more: Something about processing images in Android

Scale bitmap with inDither and inPreferQualityOverSpeed

The exercise "Load scaled bitmap" demonstrate a simple and standard method to scale bitmap. Additionally, we can set inDither and inPreferQualityOverSpeed options to improve quality of the scaled bitmap.
  • inDither:
    If set, the decoder will attempt to dither the decoded image.
    Dithering is a technique used in computer graphics to create the illusion of color depth in images with a limited color palette (color quantization). ~ reference: Wikipedia, Dither in Digital photography and image processing.
  • inPreferQualityOverSpeed (Added in API level 10) : 
    If set, the decoder will try to decode the reconstructed image to a higher quality even at the expense of the decoding speed. Currently the field only affects JPEG decode, in the case of which a more accurate, but slightly slower, IDCT method will be used instead.

In this exercise, we can set options of inDither and inPreferQualityOverSpeed in scaling bitmap. And also display the INACCURACY processing duration of scaling bitmap in millisecond, for reference only.

Scale bitmap with inDither and inPreferQualityOverSpeed

package com.example.androidscalebitmap;

import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Date;

import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.ToggleButton;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

public class MainActivity extends Activity {

final int RQS_IMAGE1 = 1;

Button btnLoadImage;
ToggleButton optBtnInDither, optBtnInPreferQualityOverSpeed;
TextView textInfo;
ImageView imageResult;

Uri source1;
Date startTime;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnLoadImage = (Button) findViewById(R.id.loadimage);
optBtnInDither = (ToggleButton) findViewById(R.id.optInDither);
optBtnInPreferQualityOverSpeed = (ToggleButton) findViewById(R.id.optInPreferQualityOverSpeed);
textInfo = (TextView) findViewById(R.id.info);
imageResult = (ImageView) findViewById(R.id.result);

btnLoadImage.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View arg0) {
Intent intent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, RQS_IMAGE1);
}
});

optBtnInDither.setOnCheckedChangeListener(
optBtnOnCheckedChangeListener);
optBtnInPreferQualityOverSpeed.setOnCheckedChangeListener(
optBtnOnCheckedChangeListener);
}

OnCheckedChangeListener optBtnOnCheckedChangeListener =
new OnCheckedChangeListener(){

@Override
public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
doScale(source1);
}};

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);

if (resultCode == RESULT_OK) {
switch (requestCode) {
case RQS_IMAGE1:
source1 = data.getData();
optBtnInDither.setChecked(false);
optBtnInPreferQualityOverSpeed.setChecked(false);
doScale(source1);
break;
}
}
}

private void doScale(Uri src){

try {
Bitmap bm = loadScaledBitmap(source1);
imageResult.setImageBitmap(bm);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

private Bitmap loadScaledBitmap(Uri src) throws FileNotFoundException {

// required max width/height
final int REQ_WIDTH = 800;
final int REQ_HEIGHT = 800;

Bitmap bm = null;

if (src != null) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(getContentResolver()
.openInputStream(src), null, options);

// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, REQ_WIDTH,
REQ_HEIGHT);

// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;

//set options according to RadioButton setting
options.inDither = optBtnInDither.isChecked();
//inPreferQualityOverSpeed require API Level 10
options.inPreferQualityOverSpeed = optBtnInPreferQualityOverSpeed.isChecked();

InputStream inputStream = getContentResolver().openInputStream(src);
startTime = new Date();

bm = BitmapFactory.decodeStream(inputStream, null, options);

//INACCURACY processing duration of scaling bitmap in millisecond
long duration = new Date().getTime() - startTime.getTime();
textInfo.setText("duration in ms: " + duration);
}

return bm;
}

public int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;

if (height > reqHeight || width > reqWidth) {

// Calculate ratios of height and width to requested height and
// width
final int heightRatio = Math.round((float) height
/ (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);

// Choose the smallest ratio as inSampleSize value, this will
// guarantee a final image with both dimensions larger than or
// equal to the requested height and width.
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}

return inSampleSize;
}
}


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:autoLink="web"
android:text="http://arteluzevida.blogspot.com/"
android:textStyle="bold" />

<Button
android:id="@+id/loadimage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Load Image 1" />
<ToggleButton
android:id="@+id/optInDither"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:checked="false"
android:textOn="inDither ON"
android:textOff="inDither OFF"/>
<ToggleButton
android:id="@+id/optInPreferQualityOverSpeed"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:checked="false"
android:textOn="inPreferQualityOverSpeed ON"
android:textOff="inPreferQualityOverSpeed OFF"/>
<TextView
android:id="@+id/info"
android:layout_width="match_parent"
android:layout_height="wrap_content" />

<ImageView
android:id="@+id/result"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:background="@android:color/background_dark"
android:scaleType="center" />

</LinearLayout>


download filesDownload the files.


download filesDownload and try the APK.



more: Something about processing images in Android

Adjust HSV(Hue, Saturation and Value) of bitmap

android.graphics.Color class provide colorToHSV() and HSVToColor() methods to convert between ARGB color and HSV components. Such that we can adjust HSV of bitmap.

Adjust HSV(Hue, Saturation and Value) of bitmap

package com.example.androiddrawbitmap;

import java.io.FileNotFoundException;

import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;

public class MainActivity extends Activity {

Button btnLoadImage;
TextView textSource;
ImageView imageResult;
SeekBar hueBar, satBar, valBar;
TextView hueText, satText, valText;
Button btnResetHSV;

final int RQS_IMAGE1 = 1;

Uri source;
Bitmap bitmapMaster;
Canvas canvasMaster;

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

btnLoadImage = (Button) findViewById(R.id.loadimage);
textSource = (TextView) findViewById(R.id.sourceuri);
imageResult = (ImageView) findViewById(R.id.result);

btnLoadImage.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View arg0) {
Intent intent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, RQS_IMAGE1);
}
});

hueText = (TextView) findViewById(R.id.texthue);
satText = (TextView) findViewById(R.id.textsat);
valText = (TextView) findViewById(R.id.textval);
hueBar = (SeekBar) findViewById(R.id.huebar);
satBar = (SeekBar) findViewById(R.id.satbar);
valBar = (SeekBar) findViewById(R.id.valbar);
hueBar.setOnSeekBarChangeListener(seekBarChangeListener);
satBar.setOnSeekBarChangeListener(seekBarChangeListener);
valBar.setOnSeekBarChangeListener(seekBarChangeListener);
btnResetHSV = (Button)findViewById(R.id.resethsv);
btnResetHSV.setOnClickListener(new OnClickListener(){

@Override
public void onClick(View arg0) {
// reset SeekBars
hueBar.setProgress(256);
satBar.setProgress(256);
valBar.setProgress(256);

loadBitmapHSV();
}});
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);

if (resultCode == RESULT_OK) {
switch (requestCode) {
case RQS_IMAGE1:
source = data.getData();

try {
bitmapMaster = BitmapFactory
.decodeStream(getContentResolver().openInputStream(
source));

// reset SeekBars
hueBar.setProgress(256);
satBar.setProgress(256);
valBar.setProgress(256);

loadBitmapHSV();

} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

break;
}
}
}

OnSeekBarChangeListener seekBarChangeListener = new OnSeekBarChangeListener() {

@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub

}

@Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub

}

@Override
public void onStopTrackingTouch(SeekBar seekBar) {
loadBitmapHSV();
}

};

private void loadBitmapHSV() {
if (bitmapMaster != null) {

int progressHue = hueBar.getProgress() - 256;
int progressSat = satBar.getProgress() - 256;
int progressVal = valBar.getProgress() - 256;

/*
* Hue (0 .. 360) Saturation (0...1) Value (0...1)
*/

float hue = (float) progressHue * 360 / 256;
float sat = (float) progressSat / 256;
float val = (float) progressVal / 256;

hueText.setText("Hue: " + String.valueOf(hue));
satText.setText("Saturation: " + String.valueOf(sat));
valText.setText("Value: " + String.valueOf(val));

imageResult.setImageBitmap(updateHSV(bitmapMaster, hue, sat, val));

}
}

private Bitmap updateHSV(Bitmap src, float settingHue, float settingSat,
float settingVal) {

int w = src.getWidth();
int h = src.getHeight();
int[] mapSrcColor = new int[w * h];
int[] mapDestColor = new int[w * h];

float[] pixelHSV = new float[3];

src.getPixels(mapSrcColor, 0, w, 0, 0, w, h);

int index = 0;
for (int y = 0; y < h; ++y) {
for (int x = 0; x < w; ++x) {

// Convert from Color to HSV
Color.colorToHSV(mapSrcColor[index], pixelHSV);

// Adjust HSV
pixelHSV[0] = pixelHSV[0] + settingHue;
if (pixelHSV[0] < 0.0f) {
pixelHSV[0] = 0.0f;
} else if (pixelHSV[0] > 360.0f) {
pixelHSV[0] = 360.0f;
}

pixelHSV[1] = pixelHSV[1] + settingSat;
if (pixelHSV[1] < 0.0f) {
pixelHSV[1] = 0.0f;
} else if (pixelHSV[1] > 1.0f) {
pixelHSV[1] = 1.0f;
}

pixelHSV[2] = pixelHSV[2] + settingVal;
if (pixelHSV[2] < 0.0f) {
pixelHSV[2] = 0.0f;
} else if (pixelHSV[2] > 1.0f) {
pixelHSV[2] = 1.0f;
}

// Convert back from HSV to Color
mapDestColor[index] = Color.HSVToColor(pixelHSV);

index++;
}
}

return Bitmap.createBitmap(mapDestColor, w, h, Config.ARGB_8888);

}

}


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:autoLink="web"
android:text="http://arteluzevida.blogspot.com/"
android:textStyle="bold" />

<Button
android:id="@+id/loadimage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Load Image 1" />

<TextView
android:id="@+id/sourceuri"
android:layout_width="match_parent"
android:layout_height="wrap_content" />

<ImageView
android:id="@+id/result"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:background="@android:color/background_dark"
android:scaleType="centerInside" />

<TextView
android:id="@+id/texthue"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hue" />
<SeekBar
android:id="@+id/huebar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:max="511"
android:progress="256"/>
<TextView
android:id="@+id/textsat"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Saturation" />
<SeekBar
android:id="@+id/satbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:max="511"
android:progress="256"/>
<TextView
android:id="@+id/textval"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Value" />
<SeekBar
android:id="@+id/valbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:max="511"
android:progress="256"/>
<Button
android:id="@+id/resethsv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Reset HSV" />
</LinearLayout>


download filesDownload the files.

download filesDownload and try APK.



more: Something about processing images in Android