问题
new to android. I don't think any of the questions on here are the same as mine.
I have images loaded into my res folder. I put them into a drawable folder. How can I get the pixels of an image named bb.png in the res.drawable folder?
I will need a simple explanation on how to get the image file into a variable, and what 'getPixel(...)' command I will need to use. I don't need to display the image, just get the pixel array from it, and check if the pixel is black or white. Any help is appreciated, thanks!
Mike
回答1:
It's actually really easy!
Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.image);
Once, you have a Bitmap
object, there's a couple of options.
bm.getPixel(x,y)
will return an int
that corresponds to an int
in the Color
class, such as Color.BLACK
or Color.WHITE
.
Additionally, bm.copyPixelsToBuffer(Buffer destination)
will copy all of the pixels into a Buffer
object, which you could search pixel-by-pixel.
Check out the documentation for further details.
Bitmap Documentation
Color Documentation
Here is a sample snippet of code, assuming that you have an image in your /res/drawable folder called 'image'.
Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.image);
int pixelColor = bm.getPixel(10,10); //Get the pixel at coordinates 10,10
if(pixelColor == Color.BLACK) {
//The pixel is black
}
else if(pixelColor == Color.WHITE) {
//The pixel was white
}
Obviously, you should be careful about getting pixels. Make sure the pixel exists, and that the coordinate is not bigger than the image. To get the dimensions of a Bitmap
, simply use bm.getHeight()
and bm.getWidth()
, respectively.
来源:https://stackoverflow.com/questions/13314198/how-to-get-pixels-of-an-image-in-res-folder-of-an-android-project