简体   繁体   中英

Printing String on a picture in Java

I want to write a string on an existing picture in java. The pic is of .jpg format. I have used the below code, the only problem is that the final image has a red shade on it..something like the image lost its true color and is light red. Please help me to rectify this problem.

    BufferedImage img = ImageIO.read(new File("pic1.jpg"));
    int width = img.getWidth();
    int height = img.getHeight();
    BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2d = bufferedImage.createGraphics();
    Font font = new Font("Serif", Font.PLAIN, 96);
    g2d.setFont(font);
    g2d.drawImage(img, 0, 0, null);
    g2d.drawString(text, 100, 250);
    g2d.dispose();

    File file = new File("newimage.jpg");

    ImageIO.write(bufferedImage, "jpg", file);

使用 INT_RGB 而不是 INT_ARGB 你会没事的:

  BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

Write code like this. There is no need to use BufferedImage class to get image graphic object. This just will do what you want.

BufferedImage img = ImageIO.read(new File("pic1.jpg"));
int width = img.getWidth();
int height = img.getHeight();
Graphics g = img.getGraphics();
Font font = new Font("Serif", Font.PLAIN, 96);

g.setFont(font);
g.setColor(Color.WHITE);
g.drawString(text, 100, 250);
g.dispose();

File file = new File("newimage.jpg");
ImageIO.write(bufferedImage, "jpg", file);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM