'Android | Java : Get the color of an edge of an image
I have an image for my app and I put it inside an ImageView.
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?
Solution 1:[1]
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()
Solution 2:[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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ocos |
| Solution 2 | Sambhav. K |

