2

我正在尝试将字符串写入图像,因此很难复制文本并通过翻译器运行它。

我的代码工作正常,但我总是得到一个很长的图像 - 我宁愿在写入字符串的地方有一个更易读的框。我的方法“StringDiver”确实添加了“\n”,但在将字符串写入图像时没有帮助。

现在我得到这个输出。

任何提示我能做什么?

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.font.FontRenderContext;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;


public class writeToImage {

/**
 * @param args
 */
public static void main(String[] args) {
    // TODO Auto-generated method stub

    String newString = "Mein Eindruck ist, dass die politische und öffentliche Meinung in Deutschland anfängt, die wirtschaftliche Zerstörung im Inland und in Europa zu erkennen, die auf einen eventuellen Zusammenbruch des Euro folgen würde.";
    String sampleText = StringDivider(newString);

    //Image file name
   String fileName = "Image";

    //create a File Object
    File newFile = new File("./" + fileName + ".jpg");

    //create the font you wish to use
    Font font = new Font("Tahoma", Font.PLAIN, 15);

    //create the FontRenderContext object which helps us to measure the text
    FontRenderContext frc = new FontRenderContext(null, true, true);

    //get the height and width of the text
    Rectangle2D bounds = font.getStringBounds(sampleText, frc);
    int w = (int) bounds.getWidth();
    int h = (int) bounds.getHeight();

    //create a BufferedImage object
   BufferedImage image = new BufferedImage(w, h,   BufferedImage.TYPE_INT_RGB);

    //calling createGraphics() to get the Graphics2D
    Graphics2D g = image.createGraphics();

    //set color and other parameters
    g.setColor(Color.WHITE);
    g.fillRect(0, 0, w, h);
    g.setColor(Color.BLACK);
    g.setFont(font);

   g.drawString(sampleText, (float) bounds.getX(), (float) -bounds.getY());

  //releasing resources
  g.dispose();

    //creating the file
   try {
    ImageIO.write(image, "jpg", newFile);
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
 }

public static String StringDivider(String s){

    StringBuilder sb = new StringBuilder(s);

    int i = 0;
    while ((i = sb.indexOf(" ", i + 30)) != -1) {
        sb.replace(i, i + 1, "\n");
    }

    return sb.toString();



}
}
4

2 回答 2

2
g.drawString(sampleText, (float) bounds.getX(), (float) -bounds.getY());

拆分文本并将每个部分写入图像。

Rectangle2D bounds = font.getStringBounds(sampleText, frc);
int w = (int) bounds.getWidth();
int h = (int) bounds.getHeight();

String[] parts = sampleText.split("\n");
//create a BufferedImage object
BufferedImage image = new BufferedImage(w, h * parts.length,   BufferedImage.TYPE_INT_RGB);

int index = 0;  
for(String part : parts){
    g.drawString(part, 0,  h * index++);
}

前任:

first part:  x=0 ; y=0
second part: x=0 ; y=5
third part:  x=0 ; y=10;

高度文本 = h

于 2012-08-10T11:05:59.773 回答
0

看看LineBreakMeasurer。Javadoc 中的第一个代码示例正是您正在寻找的。

于 2012-08-10T12:19:58.570 回答