【问题标题】:Fix jagged edges of a BufferedImage made from 2D array修复由 2D 数组制成的 BufferedImage 的锯齿状边缘
【发布时间】:2015-12-23 15:17:49
【问题描述】:

我正在尝试使用存储在 2D 数组中的颜色数据制作 BufferedImages。它有效,但我想知道是否有一种简单的方法可以修复锯齿状的锯齿状边缘。

我猜这可能有一个 API 或一个简单的技巧,但我一直在查看大量 Java 文档无济于事。 Vector Magic 确实可以满足我的要求,但我想学习如何自己编写代码。

【问题讨论】:

  • 图像处理绝非简单。您需要搜索的术语是抗锯齿。

标签: java arrays graphics bufferedimage antialiasing


【解决方案1】:

如果您对“打开”抗锯齿功能的快速方法感兴趣,那么您可以利用 Controlling Rendering Quality 的 Java2D API。您可以通过调用Graphics2D#setRenderingHintsRenderingHints 的形式传递选项。可用的提示之一是请求消除锯齿。

以下代码示例显示了 2 个窗口,它们都绘制了相同的圆,一个关闭了抗锯齿选项,另一个打开了抗锯齿选项。如果您仔细观察,您会发现使用抗锯齿渲染提示生成的锯齿较少。

TestAntiAliasing.java

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class TestAntiAliasingPanel extends JPanel {

    private final RenderingHints rh;

    private TestAntiAliasingPanel(RenderingHints rh) {
        this.rh = rh;
    }

    @Override
    public void paint(Graphics g) {
        BufferedImage bufferedImage = new BufferedImage(400, 400, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = (Graphics2D)bufferedImage.getGraphics();
        g2.setRenderingHints(rh);
        g2.setColor(Color.BLUE);
        g2.fillOval(50, 50, 300, 300);
        g.drawImage(bufferedImage, 50, 50, this);
    }

    public static void main(String[] args) {
        createFrameWithAntiAliasingOption(false);
        createFrameWithAntiAliasingOption(true);
    }

    private static void createFrameWithAntiAliasingOption(boolean antiAliasingOption) {
        RenderingHints rh = new RenderingHints(RenderingHints.KEY_ANTIALIASING,
                antiAliasingOption ? RenderingHints.VALUE_ANTIALIAS_ON :
                RenderingHints.VALUE_ANTIALIAS_OFF);
        JFrame frame = new JFrame();
        frame.getContentPane().add(new TestAntiAliasingPanel(rh));
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(500, 500);
        frame.setVisible(true);
    }
}

使用javac TestAntiAliasingPanel.java 编译,然后使用java TestAntiAliasingPanel 运行。

...但我想学习如何自己编写代码。

如果您真的有兴趣学习如何编写缓冲区操作代码以直接自己进行抗锯齿处理,那么这是一个需要外部研究的大课题。作为起点,Wikipedia has articles on several anti-aliasing algorithms

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多