JFileChooser not working when converted to .jar - java

So I'm pretty new to coding and I just started taking comp sci in school this year. In one of my programs I'm trying to use a JFileChooser and JButton so I just copied some code I found online and modified it since I don't know how to use try/catch yet:
JButton button = new JButton("Select File");
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String path;
try {
path = new File(".").getCanonicalPath();
path = path.substring(0, path.length() - 7);
JFileChooser jf = new JFileChooser();
jf.setFileSelectionMode(JFileChooser.FILES_ONLY);
jf.setMultiSelectionEnabled(false);
int returnValue = jf.showOpenDialog(null);
if (returnValue == JFileChooser.APPROVE_OPTION)
{
int n = ptoj.convert(jf.getSelectedFile().getAbsolutePath(), path);
for (int i = 0; i < n; i++)
{
if (i < 10)
{
PictureTester.split(path + "yourFile-0" + i + ".jpg", i);
}
else
{
PictureTester.split(path + "yourFile-" + i + ".jpg", i);
}
}
}
} catch (Exception e1) {
e1.printStackTrace();
}
}
});
j.add(button);
The problem is when I run it in Eclipse, it works perfectly, but when I export it into a .jar file the program opens and it seems like its going to work, but when I try to press the button, nothing happens. It doesn't crash or anything, its just that nothing happens no matter how many times I press the button.
Here is the code to the class that the previous code was getting the method "convert" from:
public class ptoj {
public static int convert(String n, String path) throws Exception{
try (final PDDocument document = PDDocument.load(new File(n))){
PDFRenderer pdfRenderer = new PDFRenderer(document);
for (int page = 0; page < document.getNumberOfPages(); ++page)
{
BufferedImage bim = pdfRenderer.renderImageWithDPI(page, 300, ImageType.RGB);
String fileName;
if (page < 10)
{
fileName = path + "yourFile-0" + page + ".jpg";
}
else
{
fileName = path + "yourFile-" + page + ".jpg";
}
ImageIOUtil.writeImage(bim, fileName, 300);
}
document.close();
return document.getNumberOfPages();
} catch (IOException e){
System.err.println("Exception while trying to create pdf document - " + e);
}
return 0;
}
}

Related

file:// URI scheme in JTextPane with HTML content is not working

I'm making an image cache in the folder of my application.
I made code for downloading images and checking for their existence.
However, I cannot use them in src attributes for some reason.
I have read these two posts:
jEditorPane handling local images
Display images using JEditorPane
However, in the first question the OP said that he used another method for setting image source, that is not suitable in my case.
And the second article assumes that file:// scheme should be working out of the box without any tricks. But somehow it's not working in my case.
A tried replacing forward slashes with backslashes, replacing spaces with %20 and leaving them as they are, tried file:// and file:/// prefix - nothing is working. I can read my files using ImageIO, but JTextPane HTML renderer does not find them, so I have just error placeholders on screen.
The example of the path to an image:
file:///D:/My%20Documents/NetBeansProjects/XMessenger/cache/http%3A%2F%2Fpopov654.pp.ru%2Fcopybox%2Fphoto.jpg
Here is the code:
private int last_width = 0;
private HashMap<String, Image> imgCache = new HashMap<String, Image>();
private void createTestMessageContent(final JComponent parent) {
String html = "Some <i>text</i><br>And more,<br>And more...<br>And more...<br>And more...<br>And more...<br>And more...<br>" +
"<img src=\"http://popov654.pp.ru/copybox/photo.jpg\" width=\"390\" height=\"260\">" +
"<img src=\"http://popov654.pp.ru/copybox/DSCN2155.jpg\" width=\"390\" height=\"260\">" +
"<img src=\"http://popov654.pp.ru/copybox/DSCN2157.jpg\" width=\"390\" height=\"260\">";
html = "<div style=\"padding: 0px; font-size: 14px; font-family: Tahoma\">" + html + "</div>";
final String orig_html = html;
Matcher m = Pattern.compile("((<img src=\"[^\"]+\")( width=\"\\d+\")?( height=\"\\d+\")?([^>]*>)\\s*)+").matcher(orig_html);
while (m.find()) {
String str = m.group();
Matcher m2 = Pattern.compile("src=\"([^\"]+)\"").matcher(str);
while (m2.find()) {
File f = new File("cache");
if (!f.exists()) {
f.mkdir();
}
String src = m2.group(1);
String cached_name = src.replaceAll("/", "%2F").replaceAll(":", "%3A");
File img = new File("cache/" + cached_name);
System.err.println(img.getAbsolutePath());
if (!img.exists()) {
InputStream in = null;
BufferedInputStream b_in = null;
FileOutputStream fileOutputStream = null;
try {
in = new URL(src).openStream();
b_in = new BufferedInputStream(in);
fileOutputStream = new FileOutputStream("cache/" + cached_name);
byte dataBuffer[] = new byte[1024];
int bytesRead;
while ((bytesRead = in.read(dataBuffer, 0, 1024)) != -1) {
fileOutputStream.write(dataBuffer, 0, bytesRead);
}
//Files.copy(in, Paths.get("cache/" + cached_name), StandardCopyOption.REPLACE_EXISTING);
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
in.close();
b_in.close();
fileOutputStream.close();
} catch (IOException ex) {}
}
} else {
html = html.replaceFirst("src=\"" + src + "\"", "src=\"file:///" + img.getAbsolutePath().replaceAll("\\\\", "/").replaceAll(" ", "%20") + "\"");
}
}
}
final String cached_html = html;
html = html.replaceAll("(<img src=\"[^\"]+\")( width=\"\\d+\")?( height=\"\\d+\")?([^>]*>)", "$1 width=\"390\" height=\"260\" hspace=\"2\" vspace=\"8\" border=\"0\"$4");
System.out.println(html);
msgContent.setText(html);
addHyperlinkListener(msgContent);
//msgContent.setMinimumSize(new Dimension(msgContent.getWidth(), msgContent.getPreferredSize().height + 20));
//setMinimumSize(new Dimension(getWidth(), msgContent.getPreferredSize().height + 160));
setPreferredSize(new Dimension(getWidth(), msgContent.getPreferredSize().height + 148));
initImages();
updateSize();
content2.addComponentListener(new java.awt.event.ComponentListener() {
#Override
public void componentResized(ComponentEvent e) {
int new_width = ((JPanel)e.getSource()).getWidth();
if (new_width != last_width) updateImages(cached_html);
last_width = new_width;
}
#Override
public void componentMoved(ComponentEvent e) {}
#Override
public void componentShown(ComponentEvent e) {}
#Override
public void componentHidden(ComponentEvent e) {}
});
}
private void initImages() {
HTMLDocument doc = (HTMLDocument) msgContent.getStyledDocument();
Element[] imgs = getElementsByTagName(HTML.Tag.IMG, doc);
for (Element img: imgs) {
Element a = img.getParentElement();
try {
String src = (String) img.getAttributes().getAttribute(HTML.Attribute.SRC);
System.out.println("src=" + src);
System.out.println();
Image image = null;
if (!src.startsWith("http://") && !src.startsWith("https://")) {
String path = src;
if (src.startsWith("file:///")) {
path = path.substring(8).replaceAll("%20", " ");
}
image = ImageIO.read(new File(path));
} else {
image = ImageIO.read(new URL(src));
}
imgCache.put(src, image);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
private void updateImages(String orig_html) {
int width = XMessengerApp.getMainWindow().getMessagePaneWidth() - 108;
double default_ratio = 16f / 9;
int img_width = (int) (width * 0.65);
int img_height = (int) ((double)img_width / default_ratio);
int margin = (int) (width * 0.005);
String html = orig_html;
Matcher m = Pattern.compile("((<img src=\"[^\"]+\")( width=\"\\d+\")?( height=\"\\d+\")?([^>]*>)\\s*)+").matcher(orig_html);
while (m.find()) {
String str = m.group();
String str_new = str;
String[] img_strs = str.split(">\\s*<");
if (img_strs.length > 1) {
System.err.println("Image series found of " + img_strs.length + " images");
}
if (img_strs.length > 1) {
img_width = (int)((width - margin * img_strs.length) / img_strs.length * 0.95);
img_height = (int)((double)img_width / default_ratio);
}
for (int i = 0; i < img_strs.length; i++) {
if (i > 0) img_strs[i] = "<" + img_strs[i];
if (i < img_strs.length-1) img_strs[i] = img_strs[i] + ">";
Matcher m2 = Pattern.compile("src=\"([^\"]+)\"").matcher(img_strs[i]);
m2.find();
String src = m2.group(1);
double ratio = default_ratio;
if (imgCache.containsKey(src)) {
Image img = imgCache.get(src);
ratio = (double) img.getWidth(null) / img.getHeight(null);
//System.out.println("Aspect ratio: " + ratio);
}
if (img_strs.length == 1) {
img_height = (int)((double)img_width / ratio);
} else {
img_width = (int)((double)img_height * ratio);
}
//System.out.println("Src: " + src);
String replace = img_strs[i].replaceAll("(<img src=\"[^\"]+\")( width=\"\\d+\")?( height=\"\\d+\")?([^>]*>)", "$1 width=\"" + img_width + "\" height=\"" + img_height + "\" hspace=\"" + margin + "\"vspace=\"8\" border=\"0\"$4");
str_new = str_new.replaceFirst(img_strs[i], replace);
}
if (img_strs.length > 1) {
str_new = "<div style=\"float: left; margin-left: -10px\">" + str_new + "</div>";
}
html = html.replaceFirst(str, str_new);
}
msgContent.setText(html);
}
private void updateSize() {
try {
Dimension d = msgContent.getPreferredSize();
Rectangle r = msgContent.modelToView(msgContent.getDocument().getLength());
d.height = r.y + r.height;
msgContent.setPreferredSize(d);
Dimension d2 = content2.getPreferredSize();
d2.height = r.y + r.height + 200;
content2.setPreferredSize(d2);
JFrame topFrame = (JFrame) SwingUtilities.getWindowAncestor(this);
topFrame.getContentPane().validate();
} catch (Exception ex) {}
}
Found the problem. It seems that I should escape % symbols in my filenames, replacing it with %25, but only if I use that path inside a URL string. When I'm using File() to work with that file it is not needed.

Insert image with apache-poi in a .word file, increase the image size

I am new with Apache and I am checking that the image that I insert with the picture is resized in the word document. I am using the example that comes in the Apache documentation, just modified. The image is considerably enlarged from the original size and when the created .word document is opened, the picture is shown resized on document and I find no explanation, when I am forcing the size the picture should be.
Below is the code used:
public class SimpleImages {
public static void main(String\[\] args) throws IOException, InvalidFormatException {
try (XWPFDocument doc = new XWPFDocument()) {
XWPFParagraph p = doc.createParagraph();
XWPFRun r = p.createRun();
for (String imgFile : args) {
int format;
if (imgFile.endsWith(".emf")) {
format = XWPFDocument.PICTURE_TYPE_EMF;
} else if (imgFile.endsWith(".wmf")) {
format = XWPFDocument.PICTURE_TYPE_WMF;
} else if (imgFile.endsWith(".pict")) {
format = XWPFDocument.PICTURE_TYPE_PICT;
} else if (imgFile.endsWith(".jpeg") || imgFile.endsWith(".jpg")) {
format = XWPFDocument.PICTURE_TYPE_JPEG;
} else if (imgFile.endsWith(".png")) {
format = XWPFDocument.PICTURE_TYPE_PNG;
} else if (imgFile.endsWith(".dib")) {
format = XWPFDocument.PICTURE_TYPE_DIB;
} else if (imgFile.endsWith(".gif")) {
format = XWPFDocument.PICTURE_TYPE_GIF;
} else if (imgFile.endsWith(".tiff")) {
format = XWPFDocument.PICTURE_TYPE_TIFF;
} else if (imgFile.endsWith(".eps")) {
format = XWPFDocument.PICTURE_TYPE_EPS;
} else if (imgFile.endsWith(".bmp")) {
format = XWPFDocument.PICTURE_TYPE_BMP;
} else if (imgFile.endsWith(".wpg")) {
format = XWPFDocument.PICTURE_TYPE_WPG;
} else {
System.err.println("Unsupported picture: " + imgFile +
". Expected emf|wmf|pict|jpeg|png|dib|gif|tiff|eps|bmp|wpg");
continue;
}
r.setText(imgFile);
r.addBreak();
try (FileInputStream is = new FileInputStream(imgFile)) {
BufferedImage bimg = ImageIO.read(new File(imgFile));
int anchoImagen = bimg.getWidth();
int altoImagen = bimg.getHeight();
System.out.println("anchoImagen: " + anchoImagen);
System.out.println("altoImagen: " + anchoImagen);
r.addPicture(is, format, imgFile, Units.toEMU(anchoImagen), Units.toEMU(altoImagen));
}
r.addBreak(BreakType.PAGE);
}
try (FileOutputStream out = new FileOutputStream("C:\\W_Ejm_Jasper\\example-poi-img\\src\\main\\java\\es\\eve\\example_poi_img\\images.docx")) {
doc.write(out);
System.out.println(" FIN " );
}
}
}
}
the image inside the word
the original image is (131 * 216 pixels):
the image is scaled in the word

PDFBox PDFMergerUtility unstable on JavaFX application

My JavaFX application was downloading PDFs from the server, rotate to portrait if the PDF is landscape, and then merge all the PDF files into one single PDF file to print it out.
Everything went fine except the program will randomly stuck at outputting the merged PDF or adding one of the PDF files to PDFMergerUtility(which I am using PDFBox 2.0.11 and tried 2.0.9 also). Because my application requires a ProgressBar and TextArea to show the current action or status, I used a Task in my controller page. When the program hangs, it didn't enter any exception or print any message but completely stops the background action. I have tried small amount of files (<50 files) and large file tests (>1000), but they all have the same results of absolutely normal or randomly hangs.
Below are the code of my controller program:
public class ReadDataPageController implements Initializable {
public long startTime;
public long stopTime;
#FXML
private Button btnNext, btnCancel, btnPrevious;
#FXML
private Label infoLabel, time, total;
#FXML
private ProgressBar progBar;
#FXML
private TextArea textArea;
public Task<String> dlTask() {
return new Task<String>() {
#Override
protected String call() throws Exception {
DownloadUtil dlutil = new DownloadUtil();
StringBuilder textStr = new StringBuilder();
List<String> dlList = mainApp.DL_LIST;
// Download PDF files from FTP
super.updateValue(textStr.append("Preparing files for download...\n").toString());
for (int count = 0; count < dlList.size(); count++) {
String PDFLink = dlList.get(count).getPDFLink();
super.updateTitle("Downloading file" + PDFLink + " ...");
super.updateValue(textStr.append("Got " + PDFLink + "\n").toString());
try {
dlutil.exec(PDFLink);
// downloaded location will be stored inside List DownloadUtil.pdfList
} catch (IndexOutOfBoundsException ex) {
super.updateValue(textStr.append("Link not found for " + PDFLink + "\n").toString());
} catch (Exception ex) {
super.updateValue(textStr.append("Error while downloading " + PDFLink + " :" + ex.getMessage() + "\n").toString());
}
super.updateProgress(count + 1, dlList.size() * 3);
}
super.updateProgress(dlList.size(), dlList.size() * 3);
super.updateTitle("Download action has finished.");
super.updateValue(textStr.append("Download action has finished.\n").toString());
// Rotate downloaded PDFs
super.updateTitle("Preparing files for PDF rotation...");
super.updateValue(textStr.append("Preparing files for PDF rotation...\n").toString());
for (int i = 0; i < dlutil.pdfList.size(); i++) {
try {
String fileName = dlutil.pdfList.get(i);
rotatePDF(new File(fileName));
super.updateValue(textStr.append("Rotating PDF ("+(i+1)+" of "+dlutil.pdfList.size()+")...\n").toString());
} catch (Exception ex) {
super.updateValue(textStr.append("Error:" + ex.getMessage() + "...\n").toString());
ex.printStackTrace();
}
super.updateProgress(dlutil.pdfList.size() + i + 1, dlutil.pdfList.size() * 3);
}
if (PRINT_OPTION == PrintType.PRINT) {
// Merge downloaded PDFs
super.updateValue(textStr.append("Preparing files for PDF merging action...\n").toString());
PDFMergerUtility pdfutil = new PDFMergerUtility();
for (int i = 0; i < dlutil.pdfList.size(); i++) {
try {
String fileName = dlutil.pdfList.get(i);
pdfutil.addSource(fileName);
super.updateTitle("Adding files (" + (i + 1) + "/" + dlutil.pdfList.size() + ")");
} catch (Exception ex) {
super.updateValue(textStr.append("Error:" + ex.getMessage() + "...\n").toString());
ex.printStackTrace();
}
super.updateProgress(dlutil.pdfList.size()*2 + i + 1, dlutil.pdfList.size() * 3);
}
// Output merged pdf
try {
pdfutil.setDestinationFileName("../odt/merge.pdf");
pdfutil.mergeDocuments();
} catch (Exception ex) {
ex.printStackTrace();
}
super.updateTitle("Merged all PDFs.");
}
super.updateProgress(100, 100);
super.updateTitle("All action has been finished.");
super.updateValue(textStr.append("All action has been finished, press Next to choose your printing option.\n").toString());
return textStr.toString();
}
};
}
/**
* Rotates PDF images 90 degree if the PDF is portrait
* #param resource the PDF file path
* #throws InvalidPasswordException
* #throws IOException
*/
public void rotatePDF(File resource) throws InvalidPasswordException, IOException {
try {
PDDocument document = PDDocument.load(resource);
int pageCount = document.getNumberOfPages();
System.out.println("Reading file: "+resource+", total page="+pageCount);
for (int i = 0; i < pageCount; i++) {
PDPage page = document.getDocumentCatalog().getPages().get(i);
PDPageContentStream cs = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.PREPEND,
false, false);
Matrix matrix = Matrix.getRotateInstance(Math.toRadians(90), 0, 0);
cs.transform(matrix);
cs.close();
PDRectangle cropBox = page.getCropBox();
if (cropBox.getWidth() > cropBox.getHeight()) {
System.out.println("ROTATE "+i+"th");
Rectangle rectangle = cropBox.transform(matrix).getBounds();
PDRectangle newBox = new PDRectangle((float) rectangle.getX(), (float) rectangle.getY(),
(float) rectangle.getWidth(), (float) rectangle.getHeight());
page.setCropBox(newBox);
page.setMediaBox(newBox);
document.save(resource);
}
}
document.close();
} catch (Exception ex) {
ex.printStackTrace();
throw ex;
}
}
}
Is there any reason that may cause the PDFMergerUtility unstable, maybe because I used a Task outside or because I missed something crucial?
Bingo! The exception was OutOfMemoryError, and Task from JavaFX made it silence.
I added the following code while initiating the task and it will handle the exceptions:
task.setOnFailed(new EventHandler<WorkerStateEvent>(){
#Override
public void handle(WorkerStateEvent event) {
Throwable th = task.getException();
System.out.println("Error on Task:"+th.getMessage());
th.printStackTrace();
}
});
To avoid OutOfMemoryError, I split the merging job into 100 pages per merging job, and save as multiple merged PDF files.

Wait for Listener to finish the task and get result for another function [Android]

I want to get a file path from my file browser function, but my file browser function has listener, so if i call another function after this file explorer function, it become crash because the path is still empty, here's two function that i want to call :
public void openFileExplorer() {
File mPath = new File(Environment.getExternalStorageDirectory() + "/");
fileDialog = new FileDialog(this, mPath);
fileDialog.addFileListener(new FileDialog.FileSelectedListener() {
public void fileSelected(File file) {
Log.d(getClass().getName(), "selected file " + file.toString());
chosenFile = file.toString();
}
});
fileDialog.showDialog();
}
private void generateMFCC(String path) {
// btnBrowse.setText("Done");
Log.d(getClass().getName(), ": Success");
buffer = mRecorder.ReadWave(path);
data = new float[buffer.length];
for (int i = 0; i < buffer.length; i++) {
data[i] = (float) buffer[i];
}
//Toast.makeText(getApplicationContext(), "Success", Toast.LENGTH_SHORT).show();
preProcess = new PreProcess(data, samplePerFreame, sampleRate);
featureExtract = new FeatureExtract(preProcess.framedSignal, sampleRate, samplePerFreame);
featureExtract.makeMfccFeatureVector();
featureVector = featureExtract.getFeatureVector();
double[][] fv = featureVector.getMfccFeature();
for (int i = 0; i < fv.length; i++) {
test = test + "{" + "\n";
for (int j = 0; j < fv[i].length; j++) {
test = test + Double.toString(fv[i][j]) + ", ";
}
test = test + "}" + "\n";
}}
i call the function like this :
openFileExplorer();
generateMFCC(chosenFile);
but it always gives error before the file explorer dialog open
call generateMFCC from openFileExplorer only.
public void openFileExplorer() {
File mPath = new File(Environment.getExternalStorageDirectory() + "/");
fileDialog = new FileDialog(this, mPath);
fileDialog.addFileListener(new FileDialog.FileSelectedListener() {
public void fileSelected(File file) {
Log.d(getClass().getName(), "selected file " + file.toString());
chosenFile = file.toString();
generateMFCC(chosenFile);
}
});
fileDialog.showDialog();
}
public void openFileExplorer() {
File mPath = new File(Environment.getExternalStorageDirectory() + "/");
fileDialog = new FileDialog(this, mPath);
fileDialog.addFileListener(new FileDialog.FileSelectedListener() {
public void fileSelected(File file) {
Log.d(getClass().getName(), "selected file " + file.toString());
chosenFile = file.toString();
// you should call the function here
generateMFCC(chosenFile);
}
});
fileDialog.showDialog();
}
think that should solve your issue, right now generateMFCC(chosenFile); is called irrespective of file being chosen
*before file is selected

Fonts do not display correctly - Java

I have some words in English that have been translated into Tamil. The task requires me to display them. An example line is given below. The first and second lines are in Tamil while the last is in Bengali.
> unpopular ஜனங்கலால் வெறுக்கப்பட்ட ¤µ£»ªÀ»õu
inactive ஜடமான ö\¯»ØÓ
doctor வைத்தியர் ©¸zxÁº
apart வேறாக uµ
If you notice above, the text in some lines does not render correctly because it is written in custom fonts. The custom font can be downloaded from here. My problem:
1. All Tamil fonts (custom and pre-loaded) have been installed. None of the text displays correctly. Why?
2. Is there a problem with the way that I am loading custom fonts?
3. In the above lines, the second column is pre-loaded font while the third column is written in custom fonts. The third column does not seem like it is Unicode, which is why application of any font also fails. What is going on?
import java.awt.Color;
import java.awt.Font;
import java.awt.FontFormatException;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.imageio.ImageIO;
/* This is the imageMaker class.
* It loads a plain white image, writes text taken from another file
* and creates a new image from it.
*
* Steps:
* 1. A plain white image is loaded.
* 2. Text is taken from a file.
* 3. Text is written to the image.
* 4. New image is created and saved.
*/
public class imgMaker_so {
/**
* #param args
*/
private static String tgtDir = "YOUR_tgt directory to store images goes here";
private static String csvFile = "csv file goes here";
private static int fontSize = 22; //default to a 22 pt font.
private static Font f;
private static String fontName = "WTAM001";
public static void main(String[] args) {
// TODO Auto-generated method stub
//Step 0. Read the image.
//readPlainImage(plainImg);
//Step 0.a: Check if the directory exists. If not, create it.
File tgtDir_file = new File(tgtDir);
if(!tgtDir_file.exists()) { //this directory does not exist.
tgtDir_file.mkdir();
}
Font nf = null;
try {
nf = Font.createFont(Font.TRUETYPE_FONT, new File("C:\\Windows\\Fonts\\" + fontName + ".ttf"));
} catch (FontFormatException | IOException e3) {
// TODO Auto-generated catch block
e3.printStackTrace();
}
if(nf != null) {
f = nf.deriveFont(Font.BOLD, fontSize);
}
if(f == null) {
System.out.println("Font is still null.");
}
//Step 1. Read csv file and get the string.
FileInputStream fis = null;
BufferedReader br = null;
try {
fis = new FileInputStream(new File(csvFile));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String temp = "\u0b85";
System.out.println(temp.length());
for(int i = 0; i < temp.length(); i++) {
System.out.print(temp.charAt(i));
}
//SAMPLE CODE ONLY. CHECK IF IT CAN PRINT A SINGLE CHARACTER IN FONT.
BufferedImage img = new BufferedImage(410, 200, BufferedImage.TYPE_INT_RGB);
Graphics g = img.getGraphics();
g.setColor(Color.WHITE);
g.fillRect(0, 0, 410, 200);
System.out.println("String being printed = " + temp.codePointAt(0));
g.setColor(Color.BLACK);
g.setFont(f);
if(f.canDisplay('\u0b85')) {
System.out.println("Can display code = \u0b85");
} else {
System.out.println("Cannot display code = \u0b85");
}
g.drawString(temp, 10, 35);
//g.drawString(translation, 10, fontWidth); //a 22pt font is approx. 35 pixels long.
g.dispose();
try {
ImageIO.write(img, "jpeg", new File(tgtDir + "\\" + "a.jpg"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("File written successfully to a");
//System.out.println("Cat,,बिल्ली,,,");
if(fis != null) {
try {
br = new BufferedReader(new InputStreamReader(fis, "UTF-8"));
} catch (UnsupportedEncodingException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
System.out.print("Unsupported encoding");
}
String line = null;
if(br != null) {
try {
while((line = br.readLine()) != null) {
if(line != null) {
System.out.println("Line = " + line);
List<String> word_translation = new ArrayList<String>();
parseLine(line, word_translation); //function to parse the line.
//printImages(word_translation);
if(word_translation.size() > 0) {
printImages_temp(word_translation);
}
//now that images have been read, read the plain image afresh.
//readPlainImage(plainImg);
word_translation.clear();
}
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
}
public static void printImages_temp(List<String> list) {
/* Function to print translations contained in list to images.
* Steps:
* 1. Take plain white image.
* 2. Write English word on top.
* 3. Take each translation and print one to each line.
*/
String dest = tgtDir + "\\" + list.get(0) + ".jpg"; //destination file image.
//compute height and width of image.
int img_height = list.size() * 35 + 20;
int img_width = 0;
int max_length = 0;
for(int i = 0; i < list.size(); i++) {
if(list.get(i).length() > max_length) {
max_length = list.get(i).length();
}
}
img_width = max_length * 20;
System.out.println("New dimensions of image = " + img_width + " " + img_height);
BufferedImage img = new BufferedImage(img_width, img_height, BufferedImage.TYPE_INT_RGB);
Graphics g = img.getGraphics();
g.setColor(Color.WHITE);
g.fillRect(0, 0, img_width, img_height);
//image has to be written to another file. Do not write English word, which is why list starts iteration from 1.
for(int i = 1; i < list.size(); i++) {
System.out.println("String being printed = " + list.get(i).codePointAt(0));
g.setColor(Color.BLACK);
g.setFont(f);
g.drawString(list.get(i), 10, (i + 1) * 35);
}
//g.drawString(translation, 10, fontWidth); //a 22pt font is approx. 35 pixels long.
g.dispose();
try {
ImageIO.write(img, "jpeg", new File(dest));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("File written successfully to " + dest);
}
public static void purge(String line) {
//This removes any inverted commas and tabs from the line apart from trimming it.
System.out.println("Line for purging = " + line);
int fromIndex = line.indexOf("\"");
//System.out.println("from index = " + fromIndex);
if(fromIndex != -1) {
line = line.substring((fromIndex + 1));
int toIndex = line.lastIndexOf("\"", line.length() - 1);
if(toIndex != -1) {
line = line.substring(0, (toIndex));
}
}
line.replaceAll("\t", " ");
line.trim();
System.out.println("Line after purging = " + line);
}
public static void parseLine(String line, List<String> result) {
/*
* This function parses the string and gets the different hindi meanings.
*/
//int index = line.indexOf(",");
//int prev_index = 0;
String[] arr = line.split(",");
List<String> l = new ArrayList<String>(Arrays.asList(arr));
for(int i = 0; i < l.size(); i++) {
if(l.get(i).isEmpty()) { //if the string at position i is empty.
l.remove(i);
}
}
for(int i = 0; i < l.size(); i++) { //inefficient copy but should be short.
String ith = l.get(i).trim();
if(!(ith.isEmpty())) { //add a string to result only if it is non-empty.
//in some entries, there are commas. they have been replaced with !?. find them and replace them.
if(ith.contains("!?")) {
//System.out.println(r + " contains !?");
String r = ith.replace("!?", ",");
result.add(r);
} else if(ith.contains("\n")) {
String r = ith.replace("\n", " ");
System.out.println("found new line in " + ith);
result.add(r);
} else {
result.add(ith);
}
}
}
for(int i = 0; i < result.size(); i++) {
System.out.println("Result[" + i + "] = " + result.get(i));
}
//System.out.println("Line being printed = " + line);
}
}
The above text was written by professional translators. So, is there something here that I am missing?
to test the concrete Font with methods in API Font.canDisplay
required to test in Unicode form (for mixing chars from a few languages (Tamil & Bengali))
please can you post and SSCCE, with used Font and can be based on

Categories