【问题标题】:Replace black color in bitmap with red用红色替换位图中的黑色
【发布时间】:2019-03-17 14:26:05
【问题描述】:

如何在 Android 中以编程方式将位图中的黑色替换为红色(或任何其他颜色)(忽略透明度)?我已经可以用一种颜色替换位图中的白色,但它在某种程度上不适用于黑色。 感谢您的帮助。

【问题讨论】:

    标签: android


    【解决方案1】:

    使用以下方法获取位图中的所有像素:

    int [] allpixels = new int [myBitmap.getHeight() * myBitmap.getWidth()];
    
    myBitmap.getPixels(allpixels, 0, myBitmap.getWidth(), 0, 0, myBitmap.getWidth(), myBitmap.getHeight());
    
    for(int i = 0; i < allpixels.length; i++)
    {
        if(allpixels[i] == Color.BLACK)
        {
            allpixels[i] = Color.RED;
        }
    }
    
    myBitmap.setPixels(allpixels,0,myBitmap.getWidth(),0, 0, myBitmap.getWidth(),myBitmap.getHeight());
    

    【讨论】:

    • 感谢您的解决方案。效果很好 - 只是,我的 PNG 似乎有一些透明度,使用这种方法,图形仍然会得到黑色(或灰色)边框,也应该用适当的红色阴影替换。
    • 如何初始化像素[]?
    • 嘿@confucius,我在这里尝试过解决方案。但我想用透明背景替换白色。这里的解决方案适用于更改颜色我可以将任何颜色更改为透明背景。你有什么线索吗?
    • 如何使用十六进制字符串 #FFFFFF 替换为 #000000
    • 请记住,您的 Bitmap 必须是 mutable 才能使 setPixels(...) 不抛出 IllegalStateException
    【解决方案2】:

    这对我有用

        public Bitmap replaceColor(Bitmap src,int fromColor, int targetColor) {
        if(src == null) {
            return null;
        }
        // Source image size
        int width = src.getWidth();
        int height = src.getHeight();
        int[] pixels = new int[width * height];
        //get pixels
        src.getPixels(pixels, 0, width, 0, 0, width, height);
    
        for(int x = 0; x < pixels.length; ++x) {
            pixels[x] = (pixels[x] == fromColor) ? targetColor : pixels[x];
        }
        // create result bitmap output
        Bitmap result = Bitmap.createBitmap(width, height, src.getConfig());
        //set pixels
        result.setPixels(pixels, 0, width, 0, 0, width, height);
    
        return result;
    }
    

    现在设置您的位图

    replaceColor(bitmapImg,Color.BLACK,Color.GRAY  )
    

    为了更好的查看,请查看Link

    【讨论】:

      【解决方案3】:

      @nids:您是否尝试过将您的 Color 替换为 Color.TRANSPARENT ?那应该可以...

      【讨论】:

        猜你喜欢
        • 2017-08-20
        • 1970-01-01
        • 2012-09-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多