灰显掉BufferedImage

时间:2016-03-11 19:00:09

标签: java graphics2d

我试图将BufferedImage变灰(不将其转换为灰度,只需在顶部添加灰色)。现在,我通过使用另一个图像,使其半透明,然后将其覆盖在原始图像上来实现此目的。这是我现在的代码:

df = df[df['ID'].isin(values)]

有没有其他方法可以在不使用其他图像进行叠加的情况下实现此目的?我可以在原始图像上添加灰色色调吗?我在其他帖子上看过很多建议,但都没有。

感谢。

2 个答案:

答案 0 :(得分:5)

你的方法基本上是做什么的:

  • 加载灰色图像,其中所有像素都具有相同的灰色。
  • 创建新图像。
  • 在该图像上绘制灰色图像,使其半透明。
  • 在想要灰显的图像上绘制半透明的灰色图像。

首先,没有必要创建transparent图像。您可以直接在真实图像上使用合成绘图。

其次,完全灰色的图像与纯矩形没有区别,Graphics2D类有fillRect类绘制填充矩形的方法,可能比绘制图像快很多。

因此,在将原始图片加载并缩放到reImg2后,您可以使用:

    Graphics2D g2d = reImg2.createGraphics();
    g2d.setColor(new Color(20,20,20,128));
    g2d.fillRect(0, 0, reImg2.getWidth(), reImg2.getHeight());
    g2d.dispose();

就是这样,现在reImg2变暗了,您可以将它写入您的文件。使用这些值 - 将20s更改为较低的值以获得较深的灰色或较高的值(最多255)以获得较浅的灰度。将128(50%alpha)更改为更高的值以获得更灰显的图像,或更低的值更少灰显的图像。

答案 1 :(得分:2)

这当然不是最有效的方法(因为你必须遍历图像中的每个像素),但是这段代码会对源图像进行去饱和处理并将结果保存到新文件中。请注意,我已删除缩放代码以尝试简洁:

package com.mypkg;

import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.imageio.ImageIO;

public class Overlay
{
    private static int adjust_saturation(int argb, float factor)
    {
        float[] hsb = new float[3];

        // Extract out the components of the color from the 32 bit integer
        int alpha = (argb >> 24) & 0xff;
        int red   = (argb >> 16) & 0xff;
        int green = (argb >> 8) & 0xff;
        int blue  = argb & 0xff;

        // Converts RGB into HSB and fills the 'hsv' array with 3 elements:
        //
        // hsb[0] = hue
        // hsb[1] = saturation
        // hsb[2] = brightness
        Color.RGBtoHSB(red, green, blue, hsb);

        // Adjust the saturation as desired
        hsb[1] *= factor;

        // Convert back to RGB and return
        return Color.HSBtoRGB(hsb[0], hsb[1], hsb[2]);
    }

    public static void main(String args[])
            throws MalformedURLException, IOException
    {
        URL url = new URL("my-input-file.jpg");
        BufferedImage image = ImageIO.read(url);

        // For every column
        for (int x = 0; x < image.getWidth(); x++) {
            // For every row
            for (int y = 0; y < image.getHeight(); y++) {
                // For each pixel of the image, grab the RGB (alpha, red, green, blue)
                int argb = image.getRGB(x, y);

                // Calculate a desaturated pixel and overwrite the current pixel
                // A value of 0.2 will desaturate by 80%, a value of 1.5 will
                // increase the saturation by 50%, etc.
                image.setRGB(x, y, adjust_saturation(argb, 0.2f));
            }
        }

        ImageIO.write(image, "png", new File("my-output-file.png"));
    }
}

以下是结果,左边是原始的,右边是去饱和的:

enter image description here

相关问题