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

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.

Related

Why is my class constructor called repeatedly?

Recently I have been working on a program that can convert TeX-generated PDFs to a certain form of text that retains some semantically meaningful style information such as subscripts and superscripts.
When debugging it seems that there might be something very unusual going on with the PDFTextStripper class.
Here is my TeXUtil class that does most of the work.
import com.google.common.base.CharMatcher;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.Hashtable;
import java.util.Stack;
public class TeXUtil {
private Stack<SSStatus> ssstatus;
private boolean accentMode;
private String fs;
private boolean mathMode;
private SymbolDB db;
private Hashtable<String, String> maccDict;
float endY;//Positions
float endX;
float Y;
int height;//Height
//boolean test;
public TeXUtil() throws IOException {
ssstatus = new Stack<SSStatus>();
fs = "rm";
accentMode = false;//as in the state of being right after an accent
mathMode = false;
db = new SymbolDB();
maccDict = new Hashtable<String, String>();
maccDict.put("\\vec","\\vec");
maccDict.put("\\widehat","\\widehat");
maccDict.put("\\widetilde","\\widetilde");
maccDict.put("\\^","\\hat");
maccDict.put("\\v","\\check");
maccDict.put("\\u","\\breve");
maccDict.put("\\`","\\grave");
maccDict.put("\\~","\\tilde");
maccDict.put("\\=","\\bar");
maccDict.put("\\.","\\dot");
maccDict.put("\\","\\ddot");
maccDict.put("\\'","\\acute");
endY = 0;
endX = 0;
Y = 0;
height = 0;
//test = false;
System.out.println("TeXUtil initialized!");
}
private static String fontShortName(PDFont font) {
String[] segments = font.getName().split("\\+");
return segments[segments.length - 1];
}
private static int fontHeight(PDFont font) {
CharMatcher matcher = CharMatcher.inRange('0', '9');
return Integer.parseInt(matcher.retainFrom(fontShortName(font)));
}
private static String fontClass(PDFont font) {
CharMatcher matcher = CharMatcher.inRange('A', 'Z');
return (matcher.retainFrom(fontShortName(font))).toLowerCase();
}
private String textToTeX(String shortFontName, int code) throws JSONException {
JSONObject info = db.getInfo(shortFontName, code);
return info.getString("value");
}
public String fullTextToTeX(PDFont font, int code, float newEndX, float newY, float newEndY){
String shortFontName = fontClass(font);
try {
JSONObject info = db.getInfo(shortFontName, code);
String teXCode = info.getString("value");
StringBuilder preamble1 = new StringBuilder("");
StringBuilder preamble2 = new StringBuilder("");
StringBuilder postamble = new StringBuilder("");
boolean text = info.getBoolean("text");
boolean math = info.getBoolean("math");
boolean tacc = info.getBoolean("tacc");
boolean macc = info.getBoolean("macc");
String newFont = info.getString("font");
int newHeight = fontHeight(font);
//Font change, rm is seen as having no font
if (!newFont.equals(fs)) {
if (!fs.equals("rm"))
preamble1.insert(0, '}');
if (!newFont.equals("rm")) {
preamble2.append('\\');
preamble2.append(newFont);
preamble2.append('{');
}
preamble1.insert(0, " fs = " + fs + " nFs = " + newFont + "\n");
fs = newFont;
}
if (height == 0) {
//preamble2.append(" Meow! am = " + accentMode + " fs = " + fs + " mm = " + mathMode + "\n");
}
//Subscripts/Superscripts
if (height > newHeight && newEndX > endX) {//New subscript/superscript
if (newEndY < endY) {//New superscript
//ssstatus.push(SSStatus.SUP);
preamble2.insert(0, "^{");
}
else if (newY > Y) {//New subscript
//ssstatus.push(SSStatus.SUB);
preamble2.insert(0, "_{");
}
//else {
// System.out.println("Please investigate the situation: texcode = " + teXCode + "endY = " + endY + " Y=" + Y + " endX=" + endX + " newEndY=" + newEndY + " newY=" + newY + " newEndX= " + newEndX);
//}
}
else if (height < newHeight && height != 0) {
//ssstatus.pop();
preamble1.append('}');
}
height = newHeight;
endX = newEndX;
endY = newEndY;
Y = newY;
//Enter or leave math mode
if (mathMode && !math && !macc) {
mathMode = false;
preamble1.append('$');
}
else if (!mathMode && !text && !tacc) {
mathMode = true;
preamble2.insert(0,'$');
}
//Accents
if (accentMode) {//If accent mode is ever entered we need to leave it at once
postamble.append('}');
accentMode = false;
}
if ((mathMode && macc) || (!mathMode && tacc)) {//Right now assume that anything that can be an accent is an accent
postamble.append('{');
if (mathMode)
teXCode = maccDict.get(teXCode);
accentMode = true;
}
if (teXCode.charAt(0) == '\\')
return preamble1.toString() + preamble2.toString() + teXCode + ' ' + postamble.toString();
else
return preamble1.toString() + preamble2.toString() + teXCode + postamble.toString();
}
catch(JSONException e) {
return "\\" + shortFontName + "{" + code + "}";
}
}
}
Here is the main class.
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.text.PDFTextStripper;
import org.apache.pdfbox.text.TextPosition;
import com.google.common.base.CharMatcher;
import org.json.*;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Stack;
public class TEX2TXT {
public static void main(String args[]) throws IOException {
TeXUtil util = new TeXUtil();
//Loading an existing document
File file = new File("/Users/CatLover/Documents/Tex/Examples/c4.pdf");
PDDocument document = PDDocument.load(file);
//Instantiate PDFTextStripper class
PDFTextStripper pdfStripper = new PDFTextStripper() {
protected void writeString(String text, List<TextPosition> textPositions) throws IOException {
TeXUtil util = new TeXUtil();
StringBuilder builder = new StringBuilder();
for(TextPosition position: textPositions) {
float Y = position.getY();
float endY = position.getEndY();
float endX = position.getEndX();
PDFont font = position.getFont();
int[] codes = position.getCharacterCodes();
for(int code: codes) {
builder.append(util.fullTextToTeX(font, code, endX, Y, endY));
}
}
writeString(builder.toString());
}
};
//Retrieving text from PDF document
String text = pdfStripper.getText(document);
System.out.println(text);
//Closing the document
document.close();
}
What's really weird is that TeXUtil is constructed every time any white space between words appear while TeXUtil() should be called only once. I'm not sure why this is the case. Since the PDFs are produced by LaTeX and LaTeX does not put white space characters in PDFs but instead leave space between characters to implicitly represent white spaces this may affect how PDFBox works.
You're constructing a new TeXUtil in the first line of your PDFTextStripper subclass's writeString method. If you just remove that line, it should be able to still reference the util defined in your main method (though depending on the version of java you're using, you may have to make it final).

JFileChooser not working when converted to .jar

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

Crop Face Using Image Detection in Android

I am trying to detect faces and crop the face part in rectangular Image. I have done the face detection Part, but still not finding any help about how to crop the face part. Please have a look on my code..!
public class FaceDetect extends Activity {
private MyImageView mIV;
private Bitmap mFaceBitmap;
private int mFaceWidth = 200;
private int mFaceHeight = 200;
int cropXinit = 0;
int cropYint = 0;
int cropXend = 0;
int cropYend = 0;
Bitmap cropedBitmap;
Bitmap b;
private static final int MAX_FACES = 1;
private static String TAG = "FaceDetect";
private static boolean DEBUG = false;
protected static final int GUIUPDATE_SETFACE = 999;
protected Handler mHandler = new Handler() {
// #Override
public void handleMessage(Message msg) {
mIV.invalidate();
super.handleMessage(msg);
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mIV = new MyImageView(this);
setContentView(mIV, new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
// load the photo
b = ChooseActivity.bitmap;
mFaceBitmap = b.copy(Bitmap.Config.RGB_565, true);
b.recycle();
mFaceWidth = mFaceBitmap.getWidth();
mFaceHeight = mFaceBitmap.getHeight();
mIV.setImageBitmap(mFaceBitmap);
mIV.invalidate();
setFace();
}
public void setFace() {
FaceDetector fd;
FaceDetector.Face[] faces = new FaceDetector.Face[MAX_FACES];
PointF eyescenter = new PointF();
float eyesdist = 0.0f;
int[] fpx = null;
int[] fpy = null;
int count = 0;
try {
fd = new FaceDetector(mFaceWidth, mFaceHeight, MAX_FACES);
count = fd.findFaces(mFaceBitmap, faces);
} catch (Exception e) {
Log.e(TAG, "setFace(): " + e.toString());
return;
}
// check if we detect any faces
if (count > 0) {
fpx = new int[count * 2];
fpy = new int[count * 2];
for (int i = 0; i < count; i++) {
try {
faces[i].getMidPoint(eyescenter);
eyesdist = faces[i].eyesDistance();
// set up left eye location
fpx[2 * i] = (int) (eyescenter.x - eyesdist / 2);
fpy[2 * i] = (int) eyescenter.y;
// set up right eye location
fpx[2 * i + 1] = (int) (eyescenter.x + eyesdist / 2);
fpy[2 * i + 1] = (int) eyescenter.y;
if (DEBUG)
Log.e(TAG,
"setFace(): face "
+ i
+ ": confidence = "
+ faces[i].confidence()
+ ", eyes distance = "
+ faces[i].eyesDistance()
+ ", pose = ("
+ faces[i]
.pose(FaceDetector.Face.EULER_X)
+ ","
+ faces[i]
.pose(FaceDetector.Face.EULER_Y)
+ ","
+ faces[i]
.pose(FaceDetector.Face.EULER_Z)
+ ")" + ", eyes midpoint = ("
+ eyescenter.x + "," + eyescenter.y
+ ")");
} catch (Exception e) {
Log.e(TAG, "setFace(): face " + i + ": " + e.toString());
}
}
}
mIV.setDisplayPoints(fpx, fpy, count * 2, 1);
// if(eyescenter.x -eyesdist >= 0)
// {
// cropXinit = (int) (eyescenter.x -eyesdist) ;
// }
// else
// {
// cropXinit = 0;
// }
// if(eyescenter.x +eyesdist <= mFaceWidth)
// {
// cropXend = (int) (eyescenter.x +eyesdist) ;
// }
// else
// {
// cropXend = mFaceWidth;
// }
// if(eyescenter.y +eyesdist*2 <= mFaceHeight)
// {
// cropYend = (int) (eyescenter.y +eyesdist*2) ;
// }
// else
// {
// cropYend = mFaceHeight;
// }
// if(eyescenter.y -eyesdist >= 0)
// {
// cropYint = (int) (eyescenter.y -eyesdist) ;
// }
// else
// {
// cropYint = 0;
// }
// mIV.setImageBitmap(Bitmap.createBitmap(mFaceBitmap,cropXinit,cropYint,cropXend,cropYend));
}
}
createBitmap(Bitmap source, int x, int y, int width, int height) receives a start X and start Y, and a width and height value, not an end X and end Y. If you change your commented-out code to this it should work:
mIV.setImageBitmap(Bitmap.createBitmap(mFaceBitmap,cropXinit,cropYint,cropXend-cropXinit,cropYend-cropYinit));

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

Java: Please insert "}" to complete classbody

I wrote a little test program but I'm experiencing a syntax error in my closing tags...
Here's the code
public class Test
{
AudioFile file = null;
String vbb = "";
File f;
public Test()
{
openFile();
}
public File openFile()
{
JFileChooser fc = new JFileChooser();
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int result = fc.showOpenDialog(fc);
if(result == JFileChooser.CANCEL_OPTION)
{
return null;
} else {
f = fc.getCurrentDirectory();
return f;
}
}
f = new File(openFile());
File[] files = f.listFiles();
for(File fi : files)
{
try {
file = (AudioFile) AudioFileIO.read(new File(fi.getAbsolutePath()));
MP3AudioHeader ah = (MP3AudioHeader) file.getAudioHeader();
String time = ah.getTrackLengthAsString();
String rate = ah.getBitRate();
boolean vb = ah.isVariableBitRate();
if(vb == false)
{
vbb = "Nee";
} else {
vbb = "Ja";
}
Tag tag = file.getTag();
String artist = tag.getFirst(FieldKey.ARTIST);
String title = tag.getFirst(FieldKey.TITLE);
String album = tag.getFirst(FieldKey.ALBUM);
String genre = tag.getFirst(FieldKey.GENRE);
String temo = tag.getFirst(FieldKey.BPM);
String path = fi.getAbsolutePath();
System.out.println("Duur: " + time + "\nVariabele bitrate: " + vbb + "\nArtiest: " + artist +"\nTitel: " + title
+ "\nAlbum: " + album + "\nGenre: " + genre + "\nBPM: " + temo + "\nBitrate: " + rate + " kbps\nPad: " + path);
} catch (Exception e)
{
System.err.print("FOUT");
}
}
}
The compiler gives an error at the LATEST closing accolade:
"Please insert } to complete classbody"
And also at the last accolade of the "openFile()" method...
Any suggestions?
f = new File(openFile());
File[] files = f.listFiles();
for(File fi : files)
{
//...
}
This whole block of logic is not in a method. It needs to be in a method or constructor.
Where you have
f = new File ...
...
catch ( .. )
{
....
}
You want to wrap that in
public static void main (String args[]) {
....
}
You cannot have a code block in a class definition. At the very top of the class, those variable declarations are declarations of class members with default visibility.
All the code starting with the line
f = new File(openFile());
is outside of any method. This is not legal Java: statements must be enclosed in a block or method body.
everything below
public File openFile()
{
JFileChooser fc = new JFileChooser();
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int result = fc.showOpenDialog(fc);
if(result == JFileChooser.CANCEL_OPTION)
{
return null;
} else {
f = fc.getCurrentDirectory();
return f;
}
}
is not enclosed within a method body but is rather lurking in the class body. remove the outer closing brace above.
Your code is not in a method. It needs to be in a method or a static block. Guessing your intent you can put it in the constructor like :
public class Test
{
AudioFile file = null;
String vbb = "";
File f;
public Test()
{
openFile();
f = new File(openFile());
File[] files = f.listFiles();
for(File fi : files)
{
try {
file = (AudioFile) AudioFileIO.read(new File(fi.getAbsolutePath()));
MP3AudioHeader ah = (MP3AudioHeader) file.getAudioHeader();
String time = ah.getTrackLengthAsString();
String rate = ah.getBitRate();
boolean vb = ah.isVariableBitRate();
if(vb == false)
{
vbb = "Nee";
} else {
vbb = "Ja";
}
Tag tag = file.getTag();
String artist = tag.getFirst(FieldKey.ARTIST);
String title = tag.getFirst(FieldKey.TITLE);
String album = tag.getFirst(FieldKey.ALBUM);
String genre = tag.getFirst(FieldKey.GENRE);
String temo = tag.getFirst(FieldKey.BPM);
String path = fi.getAbsolutePath();
System.out.println("Duur: " + time + "\nVariabele bitrate: " + vbb + "\nArtiest: " + artist +"\nTitel: " + title
+ "\nAlbum: " + album + "\nGenre: " + genre + "\nBPM: " + temo + "\nBitrate: " + rate + " kbps\nPad: " + path);
} catch (Exception e)
{
System.err.print("FOUT");
}
}
}
public File openFile()
{
JFileChooser fc = new JFileChooser();
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int result = fc.showOpenDialog(fc);
if(result == JFileChooser.CANCEL_OPTION)
{
return null;
} else {
f = fc.getCurrentDirectory();
return f;
}
}
}

Categories