如何通过Java编辑jpg图像?

and*_*and 13 java netbeans image

我已经加载了一个jpg图像,其中我想绘制字母和圆圈,给定ax,y坐标.

我一直试图弄清楚ImageIcon类的paintIcon

public void paintIcon(Component c,
                      Graphics g,
                      int x,
                      int y)
Run Code Online (Sandbox Code Playgroud)

这种方法是否允许我按照我想要的方式编辑jpg图像?什么是组件c和图形g参数?我会在身体上添加什么来画圆圈或字母?

我正在研究Netbeans 6.5,我有没有内置任务(而不是ImageIcon)?

Mic*_*ers 17

纯Java方式ImageIO用于将图像加载BufferedImage.然后你可以打电话createGraphics()来获得一个Graphics2D对象; 然后,您可以在图像上绘制任何想要的内容.

您可以使用ImageIcon嵌入式a JLabel进行显示,如果您尝试允许用户编辑图像,则可以添加MouseListener和/或a .MouseMotionListenerJLabel


coo*_*ird 12

使用Java GraphicsGraphics2D上下文可以实现在Java中操作图像.

可以使用ImageIO该类来执行加载JPEG和PNG等图像.该ImageIO.read方法接受a File读入并返回a BufferedImage,可用于通过其Graphics2D(或其Graphics超类)上下文操纵图像.

Graphics2D上下文可以用于执行多种图像绘制和操作任务.有关信息和示例,Trail:2D图​​形Java教程将是一个非常好的开始.

以下是一个简化的示例(未经测试),它将打开一个JPEG文件,并绘制一些圆和线(忽略异常):

// Open a JPEG file, load into a BufferedImage.
BufferedImage img = ImageIO.read(new File("image.jpg"));

// Obtain the Graphics2D context associated with the BufferedImage.
Graphics2D g = img.createGraphics();

// Draw on the BufferedImage via the graphics context.
int x = 10;
int y = 10;
int width = 10;
int height = 10;
g.drawOval(x, y, width, height);

g.drawLine(0, 0, 50, 50);

// Clean up -- dispose the graphics context that was created.
g.dispose();
Run Code Online (Sandbox Code Playgroud)

上面的代码将打开一个JPEG图像,并绘制一个椭圆和一条线.一旦执行了这些操作来操作图像,BufferedImage就可以像处理其他任何其他操作一样处理Image它,因为它是它的子类Image.

例如,通过创建ImageIcon使用BufferedImage,可以将图像嵌入到JButtonJLabel:

JLabel l = new JLabel("Label with image", new ImageIcon(img));
JButton b = new JButton("Button with image", new ImageIcon(img));
Run Code Online (Sandbox Code Playgroud)

JLabelJButton都有哪些需要在构造函数ImageIcon,这样可以将图像添加到一个Swing组件的简单方法.


Pab*_*ruz 5

使用库来做到这一点.你可能尝试的是JMagick.