How to get the main color of an Imageview?

Asked

Viewed 251 times

0

I wanted to know without having to post my code, how to get the main color of a certain point within a ImageView, for example I have a frame and within that frame has 3 colors, the color on the right is red, the color on the left is blue, and the middle color is black, but I just want to get the middle color without having to return that the color on the left or right is blue/red. How do I do that? If anyone could help me I’d be very grateful.

1 answer

2


To get the color of a given pixel of a Imageview use the method getPixel of Bitmap associated with Imageview.

Code to get center pixel color:

Bitmap bitmap=((BitmapDrawable)imageView.getDrawable()).getBitmap();
//Coordenada x do centro
int x = bitmap.getWidth()/2;
//Coordenada y do centro
int y = bitmap.getHeight()()/2;

int cor = bitmap.getPixel(x,y);

Please note that the coordinates(x,y) must refer to the Bitmap and not to Imageview.
To get the color of any pixel, if the coordinates(x,y) refer to the Imageview, they will have to be converted:

double bitmapWidth = bitmap.getWidth();
double bitmapHeight = bitmap.getHeight();
double imageViewWidth = imageView.getWidth();
double imageViewHeight = imageView.getHeigth();

int bitmapX = (int)(x * (bitmapWidth / imageViewWidht));
int bitmapY = (int)(y * (bitmapHeight / imageViewHeight));
int cor = bitmap.getPixel(bitmapX,bitmapY);
  • Speak man, beauty ? So thank you so much for answering me, could you help me out on one more thing ? I was wondering if after I picked up this color I could use an if to check what color he found in the center, in hexadecimal but if you have another solution other than hexadecimal, I’d appreciate it!

  • This hexadecimal is stored in a string?

  • Color.parseColor(string) returns a int. Behold here the format of string.

  • Yeah, so far so much more I could do like this: if(colorfoto == white){
 //condição
}

  • What value would I have to use instead of white, to define whether the color in the center of the photo is white or not ?

  • if(colorfoto == Color.WHITE){.....}

  • And if it was another kind of color like Snow.

  • If you know Hexadecimal do so: if(colorfoto == Color.parseColor("#FFFAFA")){...}

Show 4 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.