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

问题描述

限时删除!!

我想知道是否有更有效的方法来替换BufferedImage中的颜色。目前我使用以下方法:

I'm wondering if there is a more efficient method for replacing colors in a BufferedImage. At the moment I use the following method:

我填充一个数组,其中包含要替换的颜色和要替换它们的颜色,包括透明度。然后我循环遍历图像中的每个像素。如果它匹配数组中的一种颜色,我将其替换为数组中的新颜色。以下是代码:

I fill an array with colors to be replaced and the colors to replace them with, including transparency. Then I loop through every pixel in the image. If it matches one of the colors in the array I replace it with the new color from the array. Here is the code:

  Graphics2D g2;
  g2 = img.createGraphics();
  int x, y, i,clr,red,green,blue;

  for (x = 0; x < img.getWidth(); x++) {
    for (y = 0; y < img.getHeight(); y++) {

      // For each pixel in the image
      // get the red, green and blue value
      clr = img.getRGB(x, y);
      red = (clr & 0x00ff0000) >> 16;
      green = (clr & 0x0000ff00) >> 8;
      blue = clr & 0x000000ff;

      for (i = 1; i <= Arraycounter; i++) {
        // for each entry in the array
        // if the red, green and blue values of the pixels match the values in the array
        // replace the pixels color with the new color from the array
        if (red == Red[i] && green == Green[i] && blue == Blue[i])
        {
          g2.setComposite(Transparency[i]);
          g2.setColor(NewColor[i]);
          g2.fillRect(x, y, 1, 1);
        }
      }
    }

我正在工作的图像小,20x20像素左右。然而,似乎必须有一种更有效的方法来做到这一点。

The images I'm working with are small, 20x20 pixels or so. Nevertheless It seems there must be a more efficient way to do this.

推荐答案

而不是改变图像像素的值你可以修改底层的ColorModel。这种方式要快得多,无需迭代整个图像,因此可以很好地扩展。

Instead of changing the value of the image pixels you can modify the underlying ColorModel. Much faster that way and no need to iterate over the whole image so it scales well.

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

1403页,肝出来的..

09-06 15:25