android - 修改位图非常慢...还有其他方法吗?

标签 android bitmap android-bitmap android-color android-paint

我在这里尝试通过编写以下方法将我当前的位图转换为黑白位图。但由于每个像素的 for 循环,转换需要很长时间。我在这里哪里错了吗?还是有其他方法可以做到这一点?..帮助将不胜感激。谢谢。

我的代码:

public Bitmap convert(Bitmap src) {
       final double GS_RED = 0.299;
        final double GS_GREEN = 0.587;
        final double GS_BLUE = 0.114;
        int A, R, G, B;
        final int width = src.getWidth();
        final int height = src.getHeight();

        int pixels[] = new int[width * height];
        int k = 0;
        Bitmap bitmap = Bitmap.createBitmap(width, height, src.getConfig());
        src.getPixels(pixels, 0, width, 0, 0, width, height);
        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {
                int pixel = pixels[x + y * width];
                A = Color.alpha(pixel);
                R = Color.red(pixel);
                G = Color.green(pixel);
                B = Color.blue(pixel);
                R = G = B = (int) (GS_RED * R + GS_GREEN * G + GS_BLUE * B);
                pixels[x + y * width] = Color.argb(
                        A, R, G, B);
            }
        }

        bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
        return bitmap;
}

最佳答案

您可以使用这种方法轻松地将 rgb 图像转换为灰度图像,而无需遍历所有像素

public Bitmap toGrayscale(Bitmap bmp)
{        
    int originalwidth, originalheight;
    originalheight = bmp.getHeight();
    originalwidth = bmp.getWidth();    

    Bitmap bmpGrayscale = Bitmap.createBitmap(originalwidth, originalheight, 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(bmp, 0, 0, paint);
    return bmpGrayscale;
}

关于android - 修改位图非常慢...还有其他方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47905474/

相关文章:

android - Gradle 错误 : Could not find method android()

Android 应用程序在重新启动时崩溃内存不足

c++ - 最佳绘图方法

java - 如何在android中旋转位图?

android - OpenGLRenderer 试图缩小位图 - 当到达 ViewPager 的末尾时

java - 截取特定 LinearLayout 的屏幕截图

android - 如何在首选项(设置菜单)之间添加分隔线?

android - 无法从 android studio 中的链接加载图像

java - android.database.sqlite.SQLiteDiskIOException

java - Android 将 Ninepatch 资源转换为位图