当我在android中制作照片时,我从相机收到一个字节数组。我想将此array(image)转换为2种颜色-白色和黑色。有任何想法吗?将相机模式更改为单/负不是我的解决方案。
问候。
EDIT1:代码在Java中
答案 0 :(得分:0)
首先,您需要从数组中创建位图:
BitmapFactory.Options options = new BitmapFactory.Options();
options.inMutable = true;
// data is your byte array
Bitmap bmpOriginal = BitmapFactory.decodeByteArray(data, 0, data.length, options);
Canvas canvas = new Canvas(bmpOriginal);
Bitmap bmpGrayscale = toGrayscale(bmpOriginal);
bmpOriginal.recycle(); // free memory immediately, as your bitmap is not garbage collected by now.
然后,您可以将彩色图像bmpOriginal
传递给转换方法
public Bitmap toGrayscale(Bitmap bmpOriginal) {
int width, height;
height = bmpOriginal.getHeight();
width = bmpOriginal.getWidth();
Bitmap bmpGrayscale = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(bmpGrayscale);
Paint paint = new Paint();
ColorMatrix cm = new ColorMatrix();
cm.setSaturation(0);
ColorMatrixColorFilter f = new ColorMatrixColorFilter(cm);
paint.setColorFilter(f);
c.drawBitmap(bmpOriginal, 0, 0, paint);
return bmpGrayscale;
}
以上代码将为您提供灰度位图。它只是将零饱和度滤镜应用于图像。由于饱和度是颜色的纯度,因此纯度越低-色差就越小。应用上述滤镜后,您获得的唯一区别就是亮度。最亮的是白色,最暗的是黑色。如果要将其转换回字节数组,可以尝试如下操作:
Bitmap bmpGrayscale = intent.getExtras().get("data");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmpGrayscale.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
bmpGrayscale.recycle(); // free memory immediately, as your bitmap is not garbage collected by now.