我正在将.txt文件转换为.bmp(图片)。该.txt文件也可能包含不同语言的单词。当我使用java的BufferedImage转换它时,它会正确转换英文单词而不是其他语言的单词,图像显示其他语言单词的特殊字符。如何启用我的代码将.txt文件转换为.bmp(图像)?
我的.txt文件
SBI Bank |स्टेटबँबँ免费下载 日期|तारीख 时间|वेळ 演示|डेमो 收据|पावती 总|एकूण 量|रक्कम 沉积|जमा
**我的代码**
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import javax.imageio.ImageIO;
public class TextToGraphics {
public static void main(String[] args) {
try {
int imgWid = 300;
int imgHei = 300;
String text = "Hello\nlklkj";
String storeData = "";
String data = "";
File f = new File("/home/vipul/Desktop/123.txt");
BufferedReader br = new BufferedReader(new FileReader(f));
int nextLinePosition=100;
int fontSize = 24;
BufferedImage img = new BufferedImage(1, 1, BufferedImage.TYPE_3BYTE_BGR);
Graphics2D g2d = img.createGraphics();
Font font = new Font("Arial", Font.PLAIN, fontSize);
g2d.setFont(font);
FontMetrics fm = g2d.getFontMetrics();
int width =imgWid;
int height =imgHei;
g2d.dispose();
img = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
g2d = img.createGraphics();
g2d.setPaint(new Color(255, 255, 255));
g2d.fillRect(0, 0, img.getWidth(), img.getHeight());
System.out.println(img.getWidth() + " " + img.getHeight());
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);
while ((data = br.readLine()) != null) {
g2d.drawString(data, 0, nextLinePosition);
nextLinePosition=nextLinePosition+fontSize;
}
g2d.dispose();
ImageIO.write(img, "bmp", new File("/home/vipul/Desktop/123.bmp"));
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
是否有任何选项可以通过更改代码来打印图像中的不同语言单词,或者我必须启用任何字体支持?
请咨询。 在此先感谢!!
答案 0 :(得分:0)
您可能使用错误的编码读取了文件。
尝试替换
Reader reader = new InputStreamReader(new FileInputStream("/home/vipul/Desktop/123.txt"), "utf-8");
BufferedReader br = new BufferedReader(reader);
通过
LocalBroadcastManager
(或使用任何编码而不是utf-8)。