How to convert multi-line text to image using Java [closed]

这一生的挚爱 提交于 2019-12-26 16:03:10

问题


I want to ask one question regarding my code which is how do I convert a multiple-line text into a single image using BufferReader. I am able to get the image of the text but all the lines of the text are coming as one single string in one line. Enclosing my code. Please review my code and suggest me as soon as possible:

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;
        }
}

回答1:


Hi here I am writing multiple lines on JPanel. And you can write code which create Image from 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();
        }

    }
}


来源:https://stackoverflow.com/questions/27658986/how-to-convert-multi-line-text-to-image-using-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!