【发布时间】:2021-10-21 10:16:02
【问题描述】:
我创建此代码是为了从图像中删除所有半透明颜色并使它们完全不透明。出于某种原因,图像的颜色发生了巨大的变化,即使我只改变了 alpha。附件是代码和图像发生情况的示例。
之前:
之后:
public class Main {
public static void main(String args[]) throws IOException
{
File file = new File("karambitlore.png");
FileInputStream fis = new FileInputStream(file);
BufferedImage image = ImageIO.read(fis);
image = convertToType(image, BufferedImage.TYPE_INT_ARGB);
BufferedImage image2 = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB);
for (int width = 0; width < image.getWidth(); width++)
{
for (int height = 0; height < image.getHeight(); height++)
{
int rgb = image.getRGB(width, height);
boolean transparent = (rgb & 0xFF000000) == 0x0;
boolean opaque = (rgb & 0xFF000000) == 0xFF000000;
if (!transparent && !opaque)
{
rgb = rgb | 0xFF000000;
image2.setRGB(width, height, rgb);
} else
{
image2.setRGB(width, height, image.getRGB(width, height));
}
}
}
fis.close();
ImageIO.write(image2, "png", file);
System.out.println(image.getType());
}
public static BufferedImage convertToType(BufferedImage image, int type) {
BufferedImage newImage = new BufferedImage(image.getWidth(), image.getHeight(), type);
Graphics2D graphics = newImage.createGraphics();
graphics.drawImage(image, 0, 0, null);
graphics.dispose();
return newImage;
}
}
【问题讨论】:
-
我没有看到颜色变化很大。我确实看到第二张图像的边缘没有那么清晰。我猜这是因为抗锯齿效果不佳?不知道如何解决。
-
@camickr 代码只影响那些最外面的部分,因为它们是整个图像上唯一的半透明区域。每个被“rgb = rgb | 0xFF000000”修改的像素都会变色。如果放大图像,您会看到一些不同颜色的像素似乎是凭空出现的
-
这些可能是原始图像中几乎透明的彩色像素。
-
与其让半透明像素完全不透明,不如将它们与背景颜色混合。
-
为了获得更好的结果,您需要实际计算每个半透明像素的 RGB 贡献(这与混合基本相同)。您可能还应该使用一个阈值,比如 50%,并且只使比该阈值更不透明的像素完全不透明(低于阈值应设置为透明)。
标签: java image image-processing