2

I have an image for my app and I put it inside an ImageView.

Image

I want to get the colour at the edge of the image, for example, this image edge colour is:#4b0d10

I have a button that can choose images from the gallery, so I can't put the hex code(#4b0d10) in the colors.xml file because the user might choose a different image, and the edge colour will be different from the image above, or the size of the image won't be the same.

How can I do this?

kandroidj
  • 13,784
  • 5
  • 64
  • 76
avs
  • 122
  • 1
  • 12

2 Answers2

3

android.graphics.Bitmap class's getPixel(x: Int, y: Int): Int method gives the color at that pixel.

Find the color at pixel 100, 100

val colorInt = bitmap.getPixel(100, 100)

Use it as you wish, for example changing background color of an image view.

But a pixel's color may not represent the whole image. You may calculate mean of colors in some region of that image. Let's say from top left pixel at (0, 0) -> bottom right pixel at (10, 10).

iv.setBackgroundColor(colorInt)

If you do not have the bitmap object coming from your app's image choose flow, you can extract it from the image view concerned.

// if foreground image
val bitmap = someImageView.drawable.toBitmap()

// or background image
val bitmapBackground = someImageView.background.toBitmap()
ocos
  • 1,901
  • 1
  • 10
  • 12
  • Thanks for the answer, but the app closes when executing the code. – avs Mar 18 '22 at 01:53
  • 3
    You should adapt those code samples to your work. It does not mean that you should use all of them. For example, you will have an exception if pixel coordinates not in image width and height. – ocos Mar 18 '22 at 09:43
  • Yes, I only used "getPixel". I also checked that the pixel coordinates are in the image, I have currently not added image upload. – avs Mar 18 '22 at 23:46
  • I also noticed the code was Kotlin and I transferred to Java. – avs Mar 19 '22 at 00:47
  • What error is logged when the app closes? – Michiel Mar 19 '22 at 12:05
2

The Bitmap class gives you a method called getPixel(int x, int y) and it returns a colour int. Something like 0XFFFFFFF. This is the colour of the part of the image you want. In java, you can get the pixel like this:

int mmColor = mBitmap.getPixel(25,36);
mImageView.setBackground(mmColor);

You can modify the x and y coordinates of the bitmap and get the colour.

But, if you don't have a bitmap image, you can refer these link to get the bitmap from different file formats.

Sambhav Khandelwal
  • 3,585
  • 2
  • 7
  • 38