如何获得图像的像素在Android项目的res文件夹如何获得、文件夹、像素、图像

2023-09-07 10:13:26 作者:爷鴨扂紅亽

新到Android。我不认为任何对这里的问题是我的一样。

new to android. I don't think any of the questions on here are the same as mine.

我已经加载到我的res文件夹的图像。我把它们放入一个文件夹绘制。我怎样才能在res.drawable文件夹中名为bb.png图像的像素?

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?

我需要什么与getPixel(...)命令,我将需要使用如何获得图像文件到一个变量的简单解释,。我不需要显示图像,从中刚拿到像素阵列,并检查像素是黑色或白色。任何帮助是AP preciated,谢谢!

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!

迈克

推荐答案

这其实真的很简单!

位图BM = BitmapFactory.de codeResource(getResources(),R.drawable.image);

在,你有一个位图对象,有一对夫妇的选择。

Once, you have a Bitmap object, there's a couple of options.

bm.getPixel(X,Y)将返回一个对应于一个 INT 颜色类,如 Col​​or.BLACK Col​​or.WHITE

bm.getPixel(x,y) will return an int that corresponds to an int in the Color class, such as Color.BLACK or Color.WHITE.

此外, bm.copyPixelsToBuffer(缓冲目的地)将所有的像素复制到缓存对象,该对象你可以搜索像素由像素

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.

位图文件

彩色文档

下面是code的示例代码段,假设你在所谓的形象你的/ RES /文件夹绘制有一个形象的。

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
}

显然,你应该小心越来越像素。确保像素存在,并且该坐标不大于图像更大。要获得位图的尺寸,只需使用 bm.getHeight() BM。的getWidth(),分别为。

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.