0

嗨,我想在 Android 中将普通位图转换为单色位图,我该怎么做。我试图在网上查找,但只能找到

Bitmap bmpMonochrome = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bmpMonochrome);
ColorMatrix ma = new ColorMatrix();
ma.setSaturation(0);
Paint paint = new Paint();
paint.setColorFilter(new ColorMatrixColorFilter(ma));
canvas.drawBitmap(bmpSrc, 0, 0, paint);

我想传递一个位图并作为回报赌单色位图的字节数组。

  public static byte[] toBytes(Bitmap bitmap) {

  }

任何指针或链接请

R

4

2 回答 2

1

根据您的代码片段:

public static byte[] toMonochromeByteArray(Bitmap bitmap) {
    final Bitmap result = Bitmap.createBitmap(
            bitmap.getWidth(), bitmap.getHeight(), bitmap.getConfig());

    final Canvas canvas = new Canvas(result);
    final ColorMatrix saturation = new ColorMatrix();
    saturation.setSaturation(0f);

    final Paint paint = new Paint();
    paint.setColorFilter(new ColorMatrixColorFilter(saturation));
    canvas.drawBitmap(bitmap, 0, 0, paint);

    final ByteArrayOutputStream stream = new ByteArrayOutputStream();
    final Bitmap.CompressFormat compressFormat =
            bitmap.hasAlpha() ? Bitmap.CompressFormat.PNG : Bitmap.CompressFormat.JPEG;
    result.compress(compressFormat, 100, stream);
    result.recycle();

    return stream.toByteArray();
}
于 2019-09-24T17:53:04.610 回答
1

您可以使用 ColorMatrix 类来实现这一点:

ImageView imgview = (ImageView)findViewById(R.id.imageView_grayscale);
imgview.setImageBitmap(bitmap);

// Apply grayscale filter
ColorMatrix matrix = new ColorMatrix();
matrix.setSaturation(0);
ColorMatrixColorFilter filter = new ColorMatrixColorFilter(matrix);
imgview.setColorFilter(filter);

本要点介绍了另一个 ClorMatrix 方法示例。

于 2019-09-24T17:35:22.233 回答