gpt4 book ai didi

java - 如何将用户定义的文本放在图像上?

转载 作者:行者123 更新时间:2023-12-02 03:03:31 25 4
gpt4 key购买 nike

我想在图像上获取用户定义的文本,就像我要创建两个文本字段,一个用于名称,第二个用于日期,所以当我输入某人的姓名和日期时,输入后如果我单击“确定”,那么它'将显示在该图像中。

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class billFrame extends JFrame
{
public billFrame()
{
JFrame f1 = new JFrame("Billng Application");
f1.setDefaultCloseOperation(EXIT_ON_CLOSE);
f1.setSize(500,500);
f1.setBounds(30, 50, 500, 700);
f1.setExtendedState(JFrame.MAXIMIZED_BOTH);

ImageIcon icon = new
ImageIcon("C:\\Users\\Dhaval\\Downloads\\shrihari.png");
Image image = icon.getImage();
JPanel panel1;
panel1 = new JPanel()
{
@Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawImage(image, 1400, 0, 500, 700, this);
}

@Override
public Dimension getPreferredSize()
{
return new Dimension(320, 200);
}
};
f1.add(panel1);
panel1.setVisible(true);
panel1.setLayout(null);

JLabel name = new JLabel("Name :");
name.setVisible(true);
name.setLocation(100,100);
name.setSize(100,100);
panel1.add(name);

JTextField namet = new JTextField();
namet.setVisible(true);
namet.setLocation(150, 137);
namet.setSize(200,30);
panel1.add(namet);
f1.setVisible(true);
}
@SuppressWarnings("unchecked")
public static void main(String args[])
{
billFrame bf = new billFrame();
}
}

最佳答案

这是示例:

static void addTextWatermark(String text, File sourceImageFile, File destImageFile) {
try {
BufferedImage sourceImage = ImageIO.read(sourceImageFile);
Graphics2D g2d = (Graphics2D) sourceImage.getGraphics();

// initializes necessary graphic properties
AlphaComposite alphaChannel = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.1f);
g2d.setComposite(alphaChannel);
g2d.setColor(Color.BLUE);
g2d.setFont(new Font("Arial", Font.BOLD, 64));
FontMetrics fontMetrics = g2d.getFontMetrics();
Rectangle2D rect = fontMetrics.getStringBounds(text, g2d);

// calculates the coordinate where the String is painted
int centerX = (sourceImage.getWidth() - (int) rect.getWidth()) / 2;
int centerY = sourceImage.getHeight() / 2;

// paints the textual watermark
g2d.drawString(text, centerX, centerY);

ImageIO.write(sourceImage, "png", destImageFile);
g2d.dispose();

System.out.println("The tex watermark is added to the image.");

} catch (IOException ex) {
System.err.println(ex);
}
}

这是用法

File sourceImageFile = new     File("name.png");
File destImageFile = new File("anothername.png");
addTextWatermark("Text", sourceImageFile, destImageFile);

或者您可以使用库来实现这一点。例如:http://www.gif4j.com

关于java - 如何将用户定义的文本放在图像上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42097592/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com