如何在BufferedImage中用另一种颜色替换颜色 [英] How to replace color with another color in BufferedImage

查看:1538
本文介绍了如何在BufferedImage中用另一种颜色替换颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个有火山的图像文件。其他都是0xFFFF00FF(不透明品红色)。我想用0(透明)替换包含该颜色的每个像素。到目前为止我的方法看起来像这样:

So I have an image file that has a volcano on it. Everything else is 0xFFFF00FF (opaque magenta). I want to replace every pixel that contains that color with 0 (transparent). So far my method looks like this:

public static BufferedImage replace(BufferedImage image, int target, int preferred) {
    int width = image.getWidth();
    int height = image.getHeight();
    BufferedImage newImage = new BufferedImage(width, height, image.getType());
    int color;

    for (int i = 0; i < width; i++) {
        for (int j = 0; j < height; j++) {
            color = image.getRGB(i, j);
            if (color == target) {
                newImage.setRGB(i, j, preferred);
            }
            else {
                newImage.setRGB(i, j, color);
            }
        }
    }

    return newImage;
}

这工作正常,但看起来非常慢。我看到有人这样做了另一种方式,但我不知道发生了什么。

This works fine but seems VERY slow. I have seen someone do this another way, but I have no idea what was going on. If someone knows a better way to do this, I would very much like to hear it.

推荐答案

为了避免迭代像素,我们非常喜欢这样做。 ,请更改底层的 ColorModel 此处是一个示例。下面是作者获取原始BufferedImage并应用新颜色模型的代码段。

To avoid iterating through the pixels, change the underlying ColorModel. Here is an example. Below is the snippet where the author takes the original BufferedImage and applies the new color model.

 private static BufferedImage createImage() {
    int width = 200;
    int height = 200;
    // Generate the source pixels for our image
    // Lets just keep it to a simple blank image for now

    byte[] pixels = new byte[width * height];
    DataBuffer dataBuffer = new DataBufferByte(pixels, width*height, 0);
    SampleModel sampleModel = new SinglePixelPackedSampleModel(
    DataBuffer.TYPE_BYTE, width, height, new int[] {(byte)0xf});
    WritableRaster raster = Raster.createWritableRaster(
    sampleModel, dataBuffer, null);
    return new BufferedImage(createColorModel(0), raster, false, null);
}

private static ColorModel createColorModel(int n) {
    // Create a simple color model with all values mapping to
    // a single shade of gray
    // nb. this could be improved by reusing the byte arrays

    byte[] r = new byte[16];
    byte[] g = new byte[16];
    byte[] b = new byte[16];
    for (int i = 0; i < r.length; i++) {
        r[i] = (byte) n;
        g[i] = (byte) n;
        b[i] = (byte) n;
    }
    return new IndexColorModel(4, 16, r, g, b);
}

private BufferedImage image = createImage();
image = new BufferedImage(createColorModel(e.getX()), image.getRaster(), false, null);

这篇关于如何在BufferedImage中用另一种颜色替换颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆