Android: Highlight effect on image programatically - android

Is there any way to highlight tab icon image programmatically without using separate drawable resource?
I tried using PorterDuffColorFilter but it doesn't look good:
// apply a color mask to the icon to mark it as selected
int selectedIconMaskColor = view.getResources().getColor(R.color.tab_icon_selected);
PorterDuffColorFilter selectedIconFilter = new PorterDuffColorFilter(selectedIconMaskColor,
PorterDuff.Mode.SRC_ATOP);
copyIconDrawable.setColorFilter(selectedIconFilter);
Are there any other alternatives?

I ended up using simple image manipulation class:
import android.graphics.Bitmap;
import android.graphics.Color;
/**
* Image with support for filtering.
*/
public class FilteredImage {
private Bitmap image;
private int width;
private int height;
private int[] colorArray;
/**
* Constructor.
*
* #param img the original image
*/
public FilteredImage(Bitmap img) {
this.image = img;
width = img.getWidth();
height = img.getHeight();
colorArray = new int[width * height];
image.getPixels(colorArray, 0, width, 0, 0, width, height);
applyHighlightFilter();
}
/**
* Get the color for a specified pixel.
*
* #param x x
* #param y y
* #return color
*/
public int getPixelColor(int x, int y) {
return colorArray[y * width + x];
}
/**
* Gets the image.
*
* #return Returns the image.
*/
public Bitmap getImage() {
return image;
}
/**
* Applies green highlight filter to the image.
*/
private void applyHighlightFilter() {
int a;
int r;
int g;
int b;
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
int c = getPixelColor(x, y);
a = Color.alpha(c);
r = Color.red(c);
g = Color.green(c);
b = Color.blue(c);
r = (int) (r * 0.8);
g = (int) (g * 1.6);
b = (int) (b * 0.8);
if (r > 255) {
r = 255;
}
if (r < 0) {
r = 0;
}
if (g > 255) {
g = 255;
}
if (g < 0) {
g = 0;
}
if (b > 255) {
b = 255;
}
if (b < 0) {
b = 0;
}
int resultColor = Color.argb(a, r, g, b);
image.setPixel(x, y, resultColor);
}
}
}
}

I came across this code which works perfectly and performs faster. Hope this'll help future readers.
public static Bitmap highlightImage(Bitmap src) {
// create new bitmap, which will be painted and becomes result image
Bitmap bmOut = Bitmap.createBitmap(src.getWidth() + 96, src.getHeight() + 96, Bitmap.Config.ARGB_8888);
// setup canvas for painting
Canvas canvas = new Canvas(bmOut);
// setup default color
canvas.drawColor(0, PorterDuff.Mode.CLEAR);
// create a blur paint for capturing alpha
Paint ptBlur = new Paint();
ptBlur.setMaskFilter(new BlurMaskFilter(15, BlurMaskFilter.Blur.NORMAL));
int[] offsetXY = new int[2];
// capture alpha into a bitmap
Bitmap bmAlpha = src.extractAlpha(ptBlur, offsetXY);
// create a color paint
Paint ptAlphaColor = new Paint();
ptAlphaColor.setColor(0xFFFFFFFF);
// paint color for captured alpha region (bitmap)
canvas.drawBitmap(bmAlpha, offsetXY[0], offsetXY[1], ptAlphaColor);
// free memory
bmAlpha.recycle();
// paint the image source
canvas.drawBitmap(src, 0, 0, null);
// return out final image
return bmOut;
}

I did this, not best solution but works...
imageView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
imageView.setColorFilter(R.color.button_selection);
doLater(SECOND / 3, new Run() {
#Override
public void run() {
imageView.setColorFilter(0x00000000);
}
});
doClick(imageView);
}
});
And this is for some other view...
view.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
view.getBackground().setColorFilter(R.color.button_selection, Mode.SRC_OVER);
view.getBackground().invalidateSelf();
doLater(SECOND / 3, new Run() {
#Override
public void run() {
view.getBackground().setColorFilter(0x00000000, Mode.SRC_OVER);
view.getBackground().invalidateSelf();
}
});
doClick(view);
}
});

Related

Blur Image On touch Android

I am new to android and I want to blur image on finger touch.
I have searched some example but I found like based on seek bar value whole image get blurred.
But I want something like I can set radius of finger touch and then based on that touch, that portion of image get blurred.
MYANSWER
MainActivity1.java
here,MainActivity.java file contains bitmap that is passed from MainActivity.java .
public class MainActivity1 extends Activity implements OnClickListener {
// button
private ImageButton opacityBtn;
// custom view
private DrawingView drawView;
private Object bmpimg;
private ImageButton currPaint;
Bitmap b;
private int originalheight;
private int originalwidth;
public Bitmap tem;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main1);
Intent i1 = getIntent();
String img = i1.getStringExtra("imgpath");
Log.e("img", "" + img);
b = BitmapFactory.decodeFile(img);
// get button
opacityBtn = (ImageButton) findViewById(R.id.opacity_btn);
// listen
opacityBtn.setOnClickListener(this);
// custom view instance
// LinearLayout paintLayout = (LinearLayout)findViewById(R.id.paint_colors);
// currPaint = (ImageButton)paintLayout.getChildAt(0);
// currPaint.setImageDrawable(getResources().getDrawable(R.drawable.paint_pressed));
Log.e("mainactivity1", "" + b);
// bmpimg = Bitmap.createScaledBitmap(srcimg, 100, 50, true);
// Display display = getWindowManager().getDefaultDisplay();
// Point size = new Point();
// display.getSize(size);
// int width = size.x;
// int height = size.y;
// tem=Bitmap.createScaledBitmap(b, width,
// height - 200, true);
drawView = (DrawingView) findViewById(R.id.drawing);
// fetching height and width of device
int widthPx = getWindowManager().getDefaultDisplay().getWidth();
int heightPx = getWindowManager().getDefaultDisplay().getHeight();
// set new height and width to custom class drawing view
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) drawView
.getLayoutParams();
if (b.getHeight() < heightPx && b.getWidth() < widthPx) {
params.height = b.getHeight();
params.width = b.getWidth();
} else {
if (b.getHeight() > heightPx && b.getWidth() > widthPx) {
params.height = heightPx;
params.width = widthPx;
} else if (b.getWidth() > widthPx) {
params.width = widthPx;
params.height = b.getHeight();
} else {
params.width = b.getWidth();
params.height = heightPx;
}
}
drawView.setLayoutParams(params);
drawView.setCanvasBitmap(b, b.getHeight(),
b.getWidth(), widthPx, heightPx);
if(b.getHeight()<heightPx&&b.getWidth()<widthPx){
this.originalheight=b.getHeight();
this.originalwidth=b.getWidth();
}else{
if(b.getHeight()>heightPx&&b.getWidth()>widthPx){
this.originalheight=heightPx;
this.originalwidth=widthPx;
}
else if(b.getWidth()>widthPx){
this.originalwidth=widthPx;
this.originalheight=b.getHeight();
}
else{
this.originalwidth=b.getWidth();
this.originalheight=heightPx;
}
}
tem=Bitmap.createScaledBitmap(b, originalwidth,
originalheight, true);
Bitmap bitmap=createBitmap_ScriptIntrinsicBlur(tem,40);
drawView.firstsetupdrawing(bitmap);
// drawView.setScree_w(width);
// drawView.setScreen_h(height);
}
/*
* #Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the
* menu; this adds items to the action bar if it is present.
* getMenuInflater().inflate(R.menu.main, menu); return true; }
*/
/* public void paintClicked(View view) {
//use chosen color
//set erase false
// drawView.setErase(false);
// drawView.setPaintAlpha(100);
// drawView.setBrushSize(drawView.getLastBrushSize());
if(view!=currPaint){
Bitmap bitmap=createBitmap_ScriptIntrinsicBlur(tem,40);
drawView.firstsetupdrawing(bitmap);
// ImageButton imgView = (ImageButton)view;
// String color = view.getTag().toString();
// drawView.setColor(color);
// //update ui
// imgView.setImageDrawable(getResources().getDrawable(R.drawable.paint_pressed));
// currPaint.setImageDrawable(getResources().getDrawable(R.drawable.paint));
// currPaint=(ImageButton)view;
}
}
*/
#Override
public void onClick(View view) {
if (view.getId() == R.id.opacity_btn) {
// launch opacity chooser
final Dialog seekDialog = new Dialog(this);
seekDialog.setTitle("Opacity level:");
seekDialog.setContentView(R.layout.opacity_chooser);
// get ui elements
final TextView seekTxt = (TextView) seekDialog
.findViewById(R.id.opq_txt);
final SeekBar seekOpq = (SeekBar) seekDialog
.findViewById(R.id.opacity_seek);
// set max
seekOpq.setMax(40);
// show current level
int currLevel = drawView.getPaintAlpha();
seekTxt.setText(currLevel + "%");
seekOpq.setProgress(currLevel);
// update as user interacts
seekOpq.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
seekTxt.setText(Integer.toString(progress) + "%");
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
// listen for clicks on ok
Button opqBtn = (Button) seekDialog.findViewById(R.id.opq_ok);
opqBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Bitmap bitmap=createBitmap_ScriptIntrinsicBlur(tem, seekOpq.getProgress());
drawView.setPaintAlpha(seekOpq.getProgress(),bitmap);
seekDialog.dismiss();
}
});
// show dialog
seekDialog.show();
}
}
public Bitmap createBitmap_ScriptIntrinsicBlur(Bitmap src, int radius) {
// TODO Auto-generated method stub
// TODO Auto-generated method stub
// Radius range (0 < r <= 25)
/* if (r <= 1) {
r = 1;
} else if (r > 25) {
r = 25;
}
Bitmap bitmap = Bitmap.createBitmap(src.getWidth(), src.getHeight(),
Bitmap.Config.ARGB_8888);
RenderScript renderScript = RenderScript.create(this);
Allocation blurInput = Allocation.createFromBitmap(renderScript, src);
Allocation blurOutput = Allocation.createFromBitmap(renderScript,
bitmap);
ScriptIntrinsicBlur blur = ScriptIntrinsicBlur.create(renderScript,
Element.U8_4(renderScript));
blur.setInput(blurInput);
blur.setRadius(r);
blur.forEach(blurOutput);
blurOutput.copyTo(bitmap);
renderScript.destroy();
return bitmap;*/
//here i can make radius up to 40 use for it below code
int w = src.getWidth();
int h = src.getHeight();
int[] pix = new int[w * h];
src.getPixels(pix, 0, w, 0, 0, w, h);
for(int r = radius; r >= 1; r /= 2)
{
for(int i = r; i < h - r; i++)
{
for(int j = r; j < w - r; j++)
{
int tl = pix[(i - r) * w + j - r];
int tr = pix[(i - r) * w + j + r];
int tc = pix[(i - r) * w + j];
int bl = pix[(i + r) * w + j - r];
int br = pix[(i + r) * w + j + r];
int bc = pix[(i + r) * w + j];
int cl = pix[i * w + j - r];
int cr = pix[i * w + j + r];
pix[(i * w) + j] = 0xFF000000 |
(((tl & 0xFF) + (tr & 0xFF) + (tc & 0xFF) + (bl & 0xFF) +
(br & 0xFF) + (bc & 0xFF) + (cl & 0xFF) + (cr & 0xFF)) >> 3) & 0xFF |
(((tl & 0xFF00) + (tr & 0xFF00) + (tc & 0xFF00) + (bl & 0xFF00)
+ (br & 0xFF00) + (bc & 0xFF00) + (cl & 0xFF00) + (cr & 0xFF00)) >> 3) & 0xFF00 |
(((tl & 0xFF0000) + (tr & 0xFF0000) + (tc & 0xFF0000) +
(bl & 0xFF0000) + (br & 0xFF0000) + (bc & 0xFF0000) + (cl & 0xFF0000) +
(cr & 0xFF0000)) >> 3) & 0xFF0000;
}
}
}
Bitmap blurred = Bitmap.createBitmap(w, h, src.getConfig());
blurred.setPixels(pix, 0, w, 0, 0, w, h);
return blurred;
}
}
DrawingView.java
Here,DrawingView.java contains canavas so we canput image on canvas and blur it.
public class DrawingView extends View {
// drawing path
private Path drawPath;
// drawing and canvas paint
private Paint drawPaint, canvasPaint;
// initial color
private int paintColor = 0xFFC0C0C0, paintAlpha = 255;
// canvas
private Canvas drawCanvas;
// canvas bitmap
private Bitmap canvasBitmap;
int originalheight,originalwidth;
/**
* #return the scree_w
*/
private BlurMaskFilter blurMaskFilter;
public int scree_w, screen_h;
public void setCanvasBitmap(Bitmap bitmap1, int i, int j, int widthPx, int heightPx) {
this.canvasBitmap = bitmap1;
if(i<heightPx&&j<widthPx){
this.originalheight=i;
this.originalwidth=j;
}else{
if(i>heightPx&&j>widthPx){
this.originalheight=heightPx-1;
this.originalwidth=widthPx-1;
}
else if(j>widthPx){
this.originalwidth=widthPx-1;
this.originalheight=i;
}
else{
this.originalwidth=j;
this.originalheight=heightPx-1;
}
}
}
public void setScree_w(int width) {
// TODO Auto-generated method stub
this.scree_w = width;
}
public void setScreen_h(int height) {
// TODO Auto-generated method stub
this.screen_h = height;
}
// constructor
public DrawingView(Context context, AttributeSet attrs) {
super(context, attrs);
setupDrawing();
}
// prepare drawing
private void setupDrawing() {
drawPath = new Path();
drawPaint = new Paint();
//
drawPaint.setColor(paintColor);
drawPaint.setAntiAlias(true);
drawPaint.setStrokeWidth(30);
drawPaint.setStyle(Paint.Style.STROKE);
drawPaint.setStrokeJoin(Paint.Join.ROUND);
drawPaint.setStrokeCap(Paint.Cap.ROUND);
canvasPaint = new Paint();
// BitmapShader patternBMPshader = new BitmapShader(canvasBitmap,
// Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
// //color and shader
// drawPaint.setColor(0xFFFFFFFF);
// drawPaint.setShader(patternBMPshader);
blurMaskFilter = new BlurMaskFilter( 5,
BlurMaskFilter.Blur.NORMAL);
drawPaint.setMaskFilter(blurMaskFilter);
}
public void firstsetupdrawing( Bitmap bitmap){
drawPath = new Path();
drawPaint = new Paint();
//
// drawPaint.setColor(paintColor);
drawPaint.setAntiAlias(true);
drawPaint.setStrokeWidth(30);
drawPaint.setStyle(Paint.Style.STROKE);
drawPaint.setStrokeJoin(Paint.Join.ROUND);
drawPaint.setStrokeCap(Paint.Cap.ROUND);
canvasPaint = new Paint();
// BitmapShader patternBMPshader = new BitmapShader(canvasBitmap,
// Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
// //color and shader
// drawPaint.setColor(0xFFFFFFFF);
// drawPaint.setShader(patternBMPshader);
blurMaskFilter = new BlurMaskFilter( 5,
BlurMaskFilter.Blur.NORMAL);
drawPaint.setMaskFilter(blurMaskFilter);
drawPaint.setColor(paintColor);
// drawPaint.setAlpha(paintAlpha);
BitmapShader patternBMPshader = new BitmapShader(bitmap,
Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
//color and shader
drawPaint.setColor(0xFFFFFFFF);
drawPaint.setShader(patternBMPshader);
}
// view assigned size
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
// int i=canvasBitmap.getHeight();
// int y=canvasBitmap.getWidth();
Log.e("hiyt wid-------------------------", "" + scree_w
+ "dsgvdfg sunita u will be happy" + screen_h);
canvasBitmap = Bitmap.createScaledBitmap(canvasBitmap,originalwidth+1,originalheight+1, true);
drawCanvas = new Canvas(canvasBitmap);
}
// draw view
#Override
protected void onDraw(Canvas canvas) {
canvas.drawBitmap(canvasBitmap, 0, 0, canvasPaint);
canvas.drawPath(drawPath, drawPaint);
}
// respond to touch interaction
float x = 0, y = 0;
public boolean onTouchEvent(MotionEvent event) {
Log.e("getalph drawing view", "" + getPaintAlpha());
float touchX = 0, touchY = 0;
x = touchX;
y = touchY;
touchX = event.getX();
touchY = event.getY();
// respond to down, move and up events
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
/*
* if (x == touchX && y == touchY) {
*
* drawPath.moveTo(touchX + 1, touchY + 1); } else {
*/
drawPath.moveTo(touchX, touchY);
// }
break;
case MotionEvent.ACTION_MOVE:
/*
* if (x == touchX && y == touchY) {
*
* drawPath.lineTo(touchX + 1, touchY + 1);
*
* } else {
*/
drawPath.lineTo(touchX, touchY);
// }
break;
case MotionEvent.ACTION_UP:
/*
* if (x == touchX && y == touchY) {
*
* drawPath.lineTo(touchX + 1, touchY + 1);
* drawCanvas.drawPath(drawPath, drawPaint); drawPath.reset(); }
*
* else {
*/
drawPath.lineTo(touchX, touchY);
drawCanvas.drawPath(drawPath, drawPaint);
drawPath.reset();
// }
break;
default:
return false;
}
// redraw
invalidate();
return true;
}
// return current alpha
public int getPaintAlpha() {
return Math.round((float) paintAlpha / 255 * 40);
}
// set alpha
public void setPaintAlpha(int newAlpha, Bitmap bitmap) {
paintAlpha = Math.round((float) newAlpha / 40 * 255);
drawPaint.setColor(paintColor);
drawPaint.setAlpha(paintAlpha);
BitmapShader patternBMPshader = new BitmapShader(bitmap,
Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
//color and shader
drawPaint.setColor(0xFFFFFFFF);
drawPaint.setShader(patternBMPshader);
}
public void setColor(String newColor) {
invalidate();
//check whether color value or pattern name
if(newColor.startsWith("#")){
paintColor = Color.parseColor(newColor);
drawPaint.setColor(paintColor);
drawPaint.setShader(null);
}
else{
//pattern
int patternID = getResources().getIdentifier(
newColor, "drawable", "com.example.drawingfun");
//decode
// Bitmap patternBMP = BitmapFactory.decodeResource(getResources(), patternID);
Bitmap patternBMP = BitmapFactory.decodeResource(getResources(),R.drawable.sun);
//create shader
Log.e("drawing view pattern+getalpha", "" + patternBMP+"dsfsdsd"+getPaintAlpha());
BitmapShader patternBMPshader = new BitmapShader(patternBMP,
Shader.TileMode.REPEAT, Shader.TileMode.REPEAT);
//color and shader
drawPaint.setColor(0xFFFFFFFF);
drawPaint.setShader(patternBMPshader);
}
}
}

How can i implement seek bar to change contrast

I am trying to implement a seek bar to change contrast of an image in android. Anyone Help me to Implement this please.There is any other options for image processing ?
Does anyone know the solution Please help me
Thanks in Advance.
CODE:
public class MainActivity extends ActionBarActivity {
ImageView imViewAndroid;
private SeekBar seekbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
seekbar = (SeekBar) findViewById(R.id.seekbar);
imViewAndroid = (ImageView) findViewById(R.id.imViewAndroid);
seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
imViewAndroid.setImageBitmap(takeContrast(BitmapFactory.decodeResource(getResources(), R.drawable.dicom), 100));
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
}
public Bitmap takeContrast(Bitmap src, double value) {
// src image size
int width = src.getWidth();
int height = src.getHeight();
// create output bitmap with original size
Bitmap bmOut = Bitmap.createBitmap(width, height, src.getConfig());
// color information
int A, R, G, B;
int pixel;
// get contrast value
double contrast = Math.pow((100 + value) / 100, 2);
// scan through all pixels
for(int x = 0; x < width; ++x) {
for(int y = 0; y < height; ++y) {
// get pixel color
pixel = src.getPixel(x, y);
A = Color.alpha(pixel);
// apply filter contrast for every channel R, G, B
R = Color.red(pixel);
R = (int)(((((R / 255.0) - 0.5) * contrast) + 0.5) * 255.0);
if(R < 0) { R = 0; }
else if(R > 255) { R = 255; }
G = Color.red(pixel);
G = (int)(((((G / 255.0) - 0.5) * contrast) + 0.5) * 255.0);
if(G < 0) { G = 0; }
else if(G > 255) { G = 255; }
B = Color.red(pixel);
B = (int)(((((B / 255.0) - 0.5) * contrast) + 0.5) * 255.0);
if(B < 0) { B = 0; }
else if(B > 255) { B = 255; }
// set new pixel color to output bitmap
bmOut.setPixel(x, y, Color.argb(A, R, G, B));
}
}
// return final image
return bmOut;
}
You call the function to change contrast in a wrong place it should be here
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean b) {
// call the method here, default progress is <0, 100>
}
You use very slow function to change the contrast. There are plenty answers already on StackOverflow, have a look at this answer. Search before you ask.
Look at this full implementation on my github.
The above code takes too much time for processing image. If you use my code processing of image takes very less time.
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean b) {
contrastAndBrightnessControler(bitmap,seekbar.getProgress()/10,0.7)
}
public static Bitmap contrastAndBrightnessControler(Bitmap bitmap, float contrast, float brightness)
{
ColorMatrix cmatrix = new ColorMatrix(new float[]
{
contrast, 0, 0, 0, brightness,
0, contrast, 0, 0, brightness,
0, 0, contrast, 0, brightness,
0, 0, 0, 1, 0
});
Bitmap ret =Bitmap.createBitmap(bitmap.getWidth(),bitmap.getHeight(), bitmap.getConfig());
Canvas canvas = new Canvas(ret);
Paint paint = new Paint();
paint.setColorFilter(new ColorMatrixColorFilter(cmatrix));
canvas.drawBitmap(bitmap, 0, 0, paint);
return ret;
}

Android - Canvas Black when using Flood-Fill

When I implement my flood-fill class it turns my entire Bitmap black. Obviously this is not the desired effect. I've looked at the following threads:
https://stackoverflow.com/questions/24030858/flood-fill-is-coloring-my-entire-screen
Flood Fill Algorithm Resulting in Black Image
flood fill coloring on android
From what I can see I'm doing everything they've come up with in those solutions, however it hasn't led me to a solution for my problem. So to cut to the chase, here's the code with some brief explanations.
XML
I am using a relative layout and positioning (stacking) two ImageViews directly on top of each other. They both have the same image and this creates the illusion of you being able to draw on the image. However, you are in fact simply drawing on a transparent overlay.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
....
<ImageView
android:id="#+id/drawContainer2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_toRightOf="#id/imageMapperSurfaces"
android:contentDescription="#string/image" />
<ImageView
android:id="#+id/drawContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_toRightOf="#id/imageMapperSurfaces"
android:contentDescription="#string/image" />
...
</RelativeLayout>
Canvas
Then I create my Canvas with this code and I make sure to set my layer types correctly.
public void setCanvas() {
if(mFile != null && mFile.exists()) {
mPictureBitmap = BitmapFactory.decodeFile(mFile.getAbsolutePath());
mBitmap = Bitmap.createScaledBitmap(mPictureBitmap, mImageView.getWidth(), mImageView.getHeight(), false);
mPictureBitmap = mBitmap.copy(Bitmap.Config.ARGB_8888, true);
mBitmap = mPictureBitmap.copy(Bitmap.Config.ARGB_8888, true);
mSceneBitmap = mBitmap.copy(Bitmap.Config.ARGB_8888, true);
mBlurBitmap = blurImage(mPictureBitmap);
mCanvas = new Canvas(mBitmap);
mImageView.setImageBitmap(mBitmap);
mImageView2.setImageBitmap(mPictureBitmap);
mBlur.setImageBitmap(mBlurBitmap);
// failure to set these layer types correctly will result in a black canvas after drawing.
mImageView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
mImageView2.setLayerType(View.LAYER_TYPE_HARDWARE, null);
mImageView.bringToFront();
mAllowedToDraw = true;
setImageViewOnTouch();
}
}
Flood-Fill Implementation
I grab the color, pass my params to the flood-fill object, use the flood-fill method, return the bitmap, and finally draw the new bitmap to my canvas.
int targetColor = mSceneBitmap.getPixel((int) event.getX(), (int) event.getY());
FloodFill fill = new FloodFill(mBitmap, targetColor, Color.argb(100, 255, 0, 0));
fill.floodFill((int) event.getX(), (int) event.getY());
Bitmap bmp = fill.getImage();
mCanvas.drawBitmap(bmp, 0, 0, null);
mImageView.invalidate();
Flood-Fill Class
The boiler-plate Flood-fill algorithm.
public class FloodFill {
protected Bitmap mImage = null;
protected int[] mTolerance = new int[] { 0, 0, 0, 0 };
protected int mWidth = 0;
protected int mHeight = 0;
protected int[] mPixels = null;
protected int mFillColor = 0;
protected int[] mStartColor = new int[] { 0, 0, 0, 0 };
protected boolean[] mPixelsChecked;
protected Queue<FloodFillRange> mRanges;
public FloodFill(Bitmap img) {
copyImage(img);
}
public FloodFill(Bitmap img, int targetColor, int newColor) {
useImage(img);
setFillColor(newColor);
setTargetColor(targetColor);
}
public void setTargetColor(int targetColor) {
mStartColor[0] = Color.red(targetColor);
Log.v("Red", "" + mStartColor[0]);
mStartColor[1] = Color.green(targetColor);
Log.v("Green", "" + mStartColor[1]);
mStartColor[2] = Color.blue(targetColor);
Log.v("Blue", "" + mStartColor[2]);
mStartColor[3] = Color.alpha(targetColor);
Log.v("Alpha", "" + mStartColor[3]);
}
public int getFillColor() {
return mFillColor;
}
public void setFillColor(int value) {
mFillColor = value;
}
public int[] getTolerance() {
return mTolerance;
}
public void setTolerance(int[] value) {
mTolerance = value;
}
public void setTolerance(int value) {
mTolerance = new int[] { value, value, value, value };
}
public Bitmap getImage() {
return mImage;
}
public void copyImage(Bitmap img) {
mWidth = img.getWidth();
mHeight = img.getHeight();
mImage = Bitmap.createBitmap(mWidth, mHeight, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(mImage);
canvas.drawBitmap(img, 0, 0, null);
mPixels = new int[mWidth * mHeight];
mImage.getPixels(mPixels, 0, mWidth, 0, 0, mWidth, mHeight);
}
public void useImage(Bitmap img) {
mWidth = img.getWidth();
mHeight = img.getHeight();
mImage = img;
mPixels = new int[mWidth * mHeight];
mImage.getPixels(mPixels, 0, mWidth, 0, 0, mWidth, mHeight);
}
protected void prepare() {
mPixelsChecked = new boolean[mPixels.length];
mRanges = new LinkedList<FloodFillRange>();
}
public void floodFill(int x, int y) {
// Setup
prepare();
if (mStartColor[0] == 0) {
// ***Get starting color.
int startPixel = mPixels[(mWidth * y) + x];
mStartColor[0] = (startPixel >> 16) & 0xff;
mStartColor[1] = (startPixel >> 8) & 0xff;
mStartColor[2] = startPixel & 0xff;
}
LinearFill(x, y);
FloodFillRange range;
while (mRanges.size() > 0) {
range = mRanges.remove();
int downPxIdx = (mWidth * (range.Y + 1)) + range.startX;
int upPxIdx = (mWidth * (range.Y - 1)) + range.startX;
int upY = range.Y - 1;
int downY = range.Y + 1;
for (int i = range.startX; i <= range.endX; i++) {
if (range.Y > 0 && (!mPixelsChecked[upPxIdx]) && CheckPixel(upPxIdx)) LinearFill(i, upY);
if (range.Y < (mHeight - 1) && (!mPixelsChecked[downPxIdx]) && CheckPixel(downPxIdx)) LinearFill(i, downY);
downPxIdx++;
upPxIdx++;
}
}
mImage.setPixels(mPixels, 0, mWidth, 0, 0, mWidth, mHeight);
}
protected void LinearFill(int x, int y) {
int lFillLoc = x;
int pxIdx = (mWidth * y) + x;
while (true) {
mPixels[pxIdx] = mFillColor;
mPixelsChecked[pxIdx] = true;
lFillLoc--;
pxIdx--;
if (lFillLoc < 0 || (mPixelsChecked[pxIdx]) || !CheckPixel(pxIdx)) {
break;
}
}
lFillLoc++;
int rFillLoc = x;
pxIdx = (mWidth * y) + x;
while (true) {
mPixels[pxIdx] = mFillColor;
mPixelsChecked[pxIdx] = true;
rFillLoc++;
pxIdx++;
if (rFillLoc >= mWidth || mPixelsChecked[pxIdx] || !CheckPixel(pxIdx)) {
break;
}
}
rFillLoc--;
FloodFillRange r = new FloodFillRange(lFillLoc, rFillLoc, y);
mRanges.offer(r);
}
protected boolean CheckPixel(int px) {
int red = (mPixels[px] >>> 16) & 0xff;
int green = (mPixels[px] >>> 8) & 0xff;
int blue = mPixels[px] & 0xff;
int alpha = (Color.alpha(mPixels[px]));
return (red >= (mStartColor[0] - mTolerance[0]) && red <= (mStartColor[0] + mTolerance[0])
&& green >= (mStartColor[1] - mTolerance[1]) && green <= (mStartColor[1] + mTolerance[1])
&& blue >= (mStartColor[2] - mTolerance[2]) && blue <= (mStartColor[2] + mTolerance[2])
&& alpha >= (mStartColor[3] - mTolerance[3]) && alpha <= (mStartColor[3] + mTolerance[3]));
}
protected class FloodFillRange {
public int startX;
public int endX;
public int Y;
public FloodFillRange(int startX, int endX, int y) {
this.startX = startX;
this.endX = endX;
this.Y = y;
}
}
}
So that's it, we should have all the pieces to the puzzle but for some reason they aren't working. I'm at a loss and any help is appreciated. Thanks!
I think you're line:
mCanvas.drawBitmap(bmp, 0, 0, null);
might need to be more like
mPaint = new Paint();
mCanvas.drawBitmap(bmp, 0, 0, mPaint);
I am not sure at everything but as far as I can tell you I would try with these solutions:
First:
instead of using decodeFile I rather use decodeInputStream
Second:
As someone has anwsered You better use a Paint() when showing the view
Third:
I am going to ask why do you need that food-fill alghorithm? I think it's too laggy and It looks a little messy to use, why dont you create a new scaled bitmap or something like an opengl effect to do it? because that is the reason why there are graphics cards;

How to programatically apply effects on imageview image in android?

i want to apply various effects on image view image.this image is already sent from main activity.i have the code for effects but don't know the method how to apply it on button click.kindly guide me.
public class PhotoEffect extends Activity implements OnClickListener {
ImageView camphoto;
Bitmap bmp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.photoeffect);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
Bundle extras=getIntent().getExtras();
//b=(Bitmap)extras.get("img");
byte[] byteArray=extras.getByteArray("img");
bmp=BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
camphoto=(ImageView)findViewById(R.id.camimage);
camphoto.setImageBitmap(bmp);
/*if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}*/
}
#Override
public void onClick(View v)
{
Bitmap bitmap = ((BitmapDrawable)camphoto.getDrawable()).getBitmap();
switch (v.getId())
{
case R.id.btnsepia:
//Bitmap bitmap = ((BitmapDrawable)camphoto.getDrawable()).getBitmap();
camphoto.setImageBitmap(createSepiaToningEffect(bitmap, 2, .5, .6, .59));
break;
case R.id.btnhighlight:
camphoto.setImageBitmap(doHighlightImage(bitmap));
break;
}
}
You must define the createSepiaToningEffect function like this returning a Bitmap after processing.
public static Bitmap createSepiaToningEffect(Bitmap src, int depth, double red, double green, double blue) {
int width = src.getWidth();
int height = src.getHeight();
Bitmap bmOut = Bitmap.createBitmap(width, height, src.getConfig());
final double GS_RED = 0.3;
final double GS_GREEN = 0.59;
final double GS_BLUE = 0.11;
int A, R, G, B;
int pixel;
for(int x = 0; x < width; ++x) {
for(int y = 0; y < height; ++y) {
pixel = src.getPixel(x, y);
A = Color.alpha(pixel);
R = Color.red(pixel);
G = Color.green(pixel);
B = Color.blue(pixel);
B = G = R = (int)(GS_RED * R + GS_GREEN * G + GS_BLUE * B);
// apply intensity level for sepid-toning on each channel
R += (depth * red);
if(R > 255) { R = 255; }
G += (depth * green);
if(G > 255) { G = 255; }
B += (depth * blue);
if(B > 255) { B = 255; }
bmOut.setPixel(x, y, Color.argb(A, R, G, B));
}
}
return bmOut;
}

How to programmatically change contrast of a bitmap in android?

I want to programmatically change the contrast of bitmap. Till now I have tried this.
private Bitmap adjustedContrast(Bitmap src, double value)
{
// image size
int width = src.getWidth();
int height = src.getHeight();
// create output bitmap
Bitmap bmOut = Bitmap.createBitmap(width, height, src.getConfig());
// color information
int A, R, G, B;
int pixel;
// get contrast value
double contrast = Math.pow((100 + value) / 100, 2);
// scan through all pixels
for(int x = 0; x < width; ++x) {
for(int y = 0; y < height; ++y) {
// get pixel color
pixel = src.getPixel(x, y);
A = Color.alpha(pixel);
// apply filter contrast for every channel R, G, B
R = Color.red(pixel);
R = (int)(((((R / 255.0) - 0.5) * contrast) + 0.5) * 255.0);
if(R < 0) { R = 0; }
else if(R > 255) { R = 255; }
G = Color.green(pixel);
G = (int)(((((G / 255.0) - 0.5) * contrast) + 0.5) * 255.0);
if(G < 0) { G = 0; }
else if(G > 255) { G = 255; }
B = Color.blue(pixel);
B = (int)(((((B / 255.0) - 0.5) * contrast) + 0.5) * 255.0);
if(B < 0) { B = 0; }
else if(B > 255) { B = 255; }
// set new pixel color to output bitmap
bmOut.setPixel(x, y, Color.argb(A, R, G, B));
}
}
return bmOut;
}
But this does not work as expected. Please help me in this or provide any other solution to achieve this. Thanks in advance.
Here is complete method:
/**
*
* #param bmp input bitmap
* #param contrast 0..10 1 is default
* #param brightness -255..255 0 is default
* #return new bitmap
*/
public static Bitmap changeBitmapContrastBrightness(Bitmap bmp, float contrast, float brightness)
{
ColorMatrix cm = new ColorMatrix(new float[]
{
contrast, 0, 0, 0, brightness,
0, contrast, 0, 0, brightness,
0, 0, contrast, 0, brightness,
0, 0, 0, 1, 0
});
Bitmap ret = Bitmap.createBitmap(bmp.getWidth(), bmp.getHeight(), bmp.getConfig());
Canvas canvas = new Canvas(ret);
Paint paint = new Paint();
paint.setColorFilter(new ColorMatrixColorFilter(cm));
canvas.drawBitmap(bmp, 0, 0, paint);
return ret;
}
Try this. Your code didn't work because you create only a mutable bitmap and didn't copy the image of source bitmap to the mutable one if i'm not mistaken.
Hope It helps :)
private Bitmap adjustedContrast(Bitmap src, double value)
{
// image size
int width = src.getWidth();
int height = src.getHeight();
// create output bitmap
// create a mutable empty bitmap
Bitmap bmOut = Bitmap.createBitmap(width, height, src.getConfig());
// create a canvas so that we can draw the bmOut Bitmap from source bitmap
Canvas c = new Canvas();
c.setBitmap(bmOut);
// draw bitmap to bmOut from src bitmap so we can modify it
c.drawBitmap(src, 0, 0, new Paint(Color.BLACK));
// color information
int A, R, G, B;
int pixel;
// get contrast value
double contrast = Math.pow((100 + value) / 100, 2);
// scan through all pixels
for(int x = 0; x < width; ++x) {
for(int y = 0; y < height; ++y) {
// get pixel color
pixel = src.getPixel(x, y);
A = Color.alpha(pixel);
// apply filter contrast for every channel R, G, B
R = Color.red(pixel);
R = (int)(((((R / 255.0) - 0.5) * contrast) + 0.5) * 255.0);
if(R < 0) { R = 0; }
else if(R > 255) { R = 255; }
G = Color.green(pixel);
G = (int)(((((G / 255.0) - 0.5) * contrast) + 0.5) * 255.0);
if(G < 0) { G = 0; }
else if(G > 255) { G = 255; }
B = Color.blue(pixel);
B = (int)(((((B / 255.0) - 0.5) * contrast) + 0.5) * 255.0);
if(B < 0) { B = 0; }
else if(B > 255) { B = 255; }
// set new pixel color to output bitmap
bmOut.setPixel(x, y, Color.argb(A, R, G, B));
}
}
return bmOut;
}
We can use seek bar to adjust contrast.
MainActivity.java:
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.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
ImageView imageView;
SeekBar seekbar;
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView) findViewById(R.id.image);
textView = (TextView) findViewById(R.id.label);
seekbar = (SeekBar) findViewById(R.id.seekbar);
seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean b) {
imageView.setImageBitmap(changeBitmapContrastBrightness(BitmapFactory.decodeResource(getResources(), R.drawable.lhota), (float) progress / 100f, 1));
textView.setText("Contrast: "+(float) progress / 100f);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {}
});
seekbar.setMax(200);
seekbar.setProgress(100);
}
public static Bitmap changeBitmapContrastBrightness(Bitmap bmp, float contrast, float brightness) {
ColorMatrix cm = new ColorMatrix(new float[]
{
contrast, 0, 0, 0, brightness,
0, contrast, 0, 0, brightness,
0, 0, contrast, 0, brightness,
0, 0, 0, 1, 0
});
Bitmap ret = Bitmap.createBitmap(bmp.getWidth(), bmp.getHeight(), bmp.getConfig());
Canvas canvas = new Canvas(ret);
Paint paint = new Paint();
paint.setColorFilter(new ColorMatrixColorFilter(cm));
canvas.drawBitmap(bmp, 0, 0, paint);
return ret;
}
}
activity_main.java:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:id="#+id/image"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/label"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="8dp"
android:textAppearance="#android:style/TextAppearance.Holo.Medium" />
<SeekBar
android:id="#+id/seekbar"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
Here is a Renderscript implementation (from the Gradle Example Projects)
ip.rsh
#pragma version(1)
#pragma rs java_package_name(your.app.package)
contrast.rs
#include "ip.rsh"
static float brightM = 0.f;
static float brightC = 0.f;
void setBright(float v) {
brightM = pow(2.f, v / 100.f);
brightC = 127.f - brightM * 127.f;
}
void contrast(const uchar4 *in, uchar4 *out)
{
#if 0
out->r = rsClamp((int)(brightM * in->r + brightC), 0, 255);
out->g = rsClamp((int)(brightM * in->g + brightC), 0, 255);
out->b = rsClamp((int)(brightM * in->b + brightC), 0, 255);
#else
float3 v = convert_float3(in->rgb) * brightM + brightC;
out->rgb = convert_uchar3(clamp(v, 0.f, 255.f));
#endif
}
Java
private Bitmap changeBrightness(Bitmap original RenderScript rs) {
Allocation input = Allocation.createFromBitmap(rs, original);
final Allocation output = Allocation.createTyped(rs, input.getType());
ScriptC_contrast mScript = new ScriptC_contrast(rs);
mScript.invoke_setBright(50.f);
mScript.forEach_contrast(input, output);
output.copyTo(original);
return original;
}
Assumption - ImageView is used to display the bitmap
I did a more enhancement in the Ruslan's answer
Instead of replacing bitmap every time (which makes it slow if you are using seek bar) we can work on the Color Filter of the ImageView.
float contrast;
float brightness = 0;
ImageView imageView;
// SeekBar ranges from 0 to 90
// contrast ranges from 1 to 10
mSeekBarContrast.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
contrast = (float) (i + 10) / 10;
// Changing the contrast of the bitmap
imageView.setColorFilter(getContrastBrightnessFilter(contrast,brightness));
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
ColorMatrixColorFilter getContrastBrightnessFilter(float contrast, float brightness) {
ColorMatrix cm = new ColorMatrix(new float[]
{
contrast, 0, 0, 0, brightness,
0, contrast, 0, 0, brightness,
0, 0, contrast, 0, brightness,
0, 0, 0, 1, 0
});
return new ColorMatrixColorFilter(cm);
}
P.S - Brightness can also be changed along with contrast using this method
I just had the same problem and ended up using the Color Matrix that Ruslan Yanchyshyn describes. I needed to automatically adjust brightness depending on the image, so I used BoofCV to create a histogram from a scaled version of the image - It took way to long to process the whole image. Then I analyzed the histogram - looked at what was the darkest and brightest colors and then created a color matrix which transforms the colors so the darkest colors are 0 and the brightest colors are 255. In this way the new image uses the whole spectrum from dark/black to light/white now.
Ended up writing a small post on how I did it on our company blog here if anyone are interested. http://appdictive.dk/blog/projects/2016/07/26/levels_with_color_matrix/
Maybe you can try this one:
http://xjaphx.wordpress.com/2011/06/21/image-processing-contrast-image-on-the-fly/
Hope that helps! :)
http://android.okhelp.cz/bitmap-set-contrast-and-brightness-android/
have a look at this ,this might solve your problem

Categories

Resources