Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/364.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用Java将多行文本转换为图像_Java_Image_Image Processing_Bufferedreader - Fatal编程技术网

如何使用Java将多行文本转换为图像

如何使用Java将多行文本转换为图像,java,image,image-processing,bufferedreader,Java,Image,Image Processing,Bufferedreader,我想问一个关于我的代码的问题,那就是如何使用BufferReader将多行文本转换为单个图像。我能够得到文本的图像,但是文本的所有行都是一行中的一个字符串。 附上我的代码。请查看我的代码并尽快向我提出建议: package mypack; import java.awt.Color; import java.awt.Font; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.font.Fon

我想问一个关于我的代码的问题,那就是如何使用BufferReader将多行文本转换为单个图像。我能够得到文本的图像,但是文本的所有行都是一行中的一个字符串。 附上我的代码。请查看我的代码并尽快向我提出建议:

package mypack;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.font.FontRenderContext;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;

import javax.imageio.ImageIO;

public class ImageDemo {
    public static void main(String[] args) throws IOException {

        // reading the String object from a file  to be converted to image
        /*File file = new File("D:/Vivek.txt");
        StringBuilder sb=new StringBuilder();
        BufferedReader reader = new BufferedReader(new FileReader(file));
        while(true)
        {
            String text=reader.readLine();
            System.out.println(text);
            if(text==null)
                break;
            sb.append(text).append(' ');
            sb.append("\n");    
        }
        String text1=sb.toString();
        reader.close();*/



        String text=new String(Files.readAllBytes(Paths.get("D:/Vivek.txt")),    StandardCharsets.UTF_8);
        System.out.println(text);
        // Image file name
        String fileName = "Image";

        // create a File Object
        File newFile = new File("D:/Vivek.jpg");

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

        // 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(text, 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(text, (float) bounds.getX(), (float) -bounds.getY());

        // releasing resources
        g.dispose();
        RenderedImage rImage = (RenderedImage) image;
        // creating the file
        ImageIO.write(rImage, "jpeg", newFile);


        //merging the two buffered images to get a new image with text along with logo.

        //load the source images
        BufferedImage img1=ImageIO.read(new File("D:/Vivek.jpg"));
        BufferedImage img2=ImageIO.read(new File("D:/logo.jpg"));
        BufferedImage joined=joinBufferedImage(img1, img2);
        ImageIO.write(joined, "png", new File("D:/Joined.png"));
        System.out.println("Success");

    }
      public static BufferedImage joinBufferedImage(BufferedImage img1,BufferedImage img2) {

            //do some calculate first
            int offset  = 500;
            int wid = img1.getWidth()+img2.getWidth()+offset;
            int height = Math.max(img1.getHeight(),img2.getHeight())+offset;

            //create a new buffer and draw two image into the new image
            BufferedImage newImage = new BufferedImage(wid,height, BufferedImage.TYPE_INT_ARGB);
            Graphics2D g2 = newImage.createGraphics();
            Color oldColor = g2.getColor();

            //fill background
            g2.setPaint(Color.WHITE);
            g2.fillRect(0, 0, wid, height);

            //draw image
            g2.setColor(oldColor);
            g2.drawImage(img2, null, 0, 0);
            g2.drawImage(img1, null, 170, 150);
            g2.dispose();

            g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            g2.setRenderingHint(RenderingHints.KEY_RENDERING,RenderingHints.VALUE_RENDER_QUALITY);
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
            return newImage;
        }
}

大家好,我在JPanel上写了多行。您可以编写代码从JPanel创建图像

package Stakeoverflow.swingFrame;

import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;

public class MultiLineTextToImage{
    public static void main(String[] args) {
        String text = "Hello";

        /*
           Because font metrics is based on a graphics context, we need to create
           a small, temporary image so we can ascertain the width and height
           of the final image
         */
        int width = 1000;
        int height = 1000;

        BufferedImage img = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2d = img.createGraphics();
        Font font = new Font("Arial", Font.PLAIN, 48);
        g2d.setFont(font);
        FontMetrics fm = g2d.getFontMetrics();

        g2d.dispose();

        img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        g2d = img.createGraphics();
        g2d.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
        g2d.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE);
        g2d.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
        g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
        g2d.setFont(font);
        //fm = g2d.getFontMetrics();
        g2d.setColor(Color.BLACK);
        File file = new File("C:\\Read.text");

        BufferedReader br=null;
        int nextLinePosition=100;
        int fontSize = 48;
        try {
            br = new BufferedReader(new FileReader(file));

            String line;
            while ((line = br.readLine()) != null) {
               g2d.drawString(line, 0, nextLinePosition);
               nextLinePosition = nextLinePosition + fontSize;
            }
        br.close();
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Testing.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Testing.class.getName()).log(Level.SEVERE, null, ex);
        }


        g2d.dispose();
        try {
            ImageIO.write(img, "png", new File("Text.png"));
        } catch (IOException ex) {
            ex.printStackTrace();
        }

    }
}

@Vivek Prakash Mathur如果您喜欢格式化字符串,请点击此链接,感谢Naimish的回复,但我不应该使用swing。因此,请建议我其他解决方案。尽管我尝试了您的代码,但来自文件的文本仍然在一行中。即使使用swing@VivekPrakashMathur对不起,上次不理解,但我修改了我的答案。这次我写的代码只是提供了转换成图像的文件。非常感谢,伙计:)它按照预期工作