An array of BufferedImage is showing null for the values set - java

In the class getPathGiveIcon, am passing an array of strings to getPaths() method. This getPaths() is expected to return an array of ImageIcons. In this process, am trying to create a file out of a every path name in the array of strings but at this line am getting error.
img[i] = ImageIO.read(fa);// in this line the error
Kindly guide me to over come this error...
Here is full code of the getPaths() method.
public class GetPathGiveIcon {
ImageIcon[] iic;
File f = new File(" ");
int i = 0;
public ImageIcon[] getPaths(String[] s)
{
BufferedImage[] img = null;
for(String st : s)
{
System.out.println(st);
}
for(String st : s)
try
{
{
File fa = new File(st);
img[i] = ImageIO.read(fa);
System.out.println(" inside try block the value of every string = " + st);
}
}
catch(Exception e)
{
e.printStackTrace();
}
System.out.println(" Value of I before scaling " + i);
i = 0;
for(BufferedImage bi : img)
{
iic[i] = new ImageIcon(bi);
Image scaled = iic[i].getImage().getScaledInstance(150,150,
Image.SCALE_DEFAULT);
iic[i] = new ImageIcon(scaled);
i++;
}
System.out.println(" Value of I after scaling " + i);
return iic;
}
}

That is because
BufferedImage[] img = null;
You have to initialize img array with
BufferedImage[] img = new BufferedImage[s.length];

i always equals 0 so your code will only fill the first element of your array.
Here is the solution :
BufferedImage[] img = new BufferedImage[s.length];
for(String st : s)
{
try
{
File fa = new File(st);
img[i++] = ImageIO.read(fa);
System.out.println(" inside try block the value of every string = " + st);
}
catch(Exception e)
{
e.printStackTrace();
}
}
edit
Same issue with iic, it has to be initialized
iic = new ImageIcon[img.length];
i = 0;
for(BufferedImage bi : img)
{
iic[i] = new ImageIcon(bi);
// [...]

Related

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

Reading text between quotation marks

Here's a piece of text I'm trying to work with:
lat="52.336575" lon="6.381008">< time>2016-12-19T12:12:27Z< /time>< name>Foto 8 </name>< desc>Dag 4 E&F
Geb 1.4
Hakhoutstoof < /desc>< /wpt>
I'm trying to extract the coördinates between the "" and put the values between the "" into a string, but I can't get it to work...
Here's my code (so far):
public void openFile() {
Chooser = new JFileChooser("C:\\Users\\danie\\Desktop\\");
Chooser.setAcceptAllFileFilterUsed(false);
Chooser.setDialogTitle("Open file");
Chooser.addChoosableFileFilter(new FileNameExtensionFilter("*.gpx",
"gpx"));
int returnVal = Chooser.showOpenDialog(null);
try {
Dummy = new Scanner(Chooser.getSelectedFile());
} catch (FileNotFoundException E) {
System.out.println("Error: " + E);
}
}
public void createDummy() {
Dummy.useDelimiter("<wpt");
if (Dummy.hasNext()) {
String Meta = Dummy.next();
}
Dummy.useDelimiter("\\s[<wpt]\\s|\\s[</wpt>]\\s");
try {
while (Dummy.hasNext()) {
String Test = Dummy.next();
DummyFile = new File("Dummy.txt");
Output = new PrintWriter(DummyFile);
Output.print(Test);
Output.println();
Output.flush();
Output.close();
}
Reader = new FileReader(DummyFile);
Buffer = new BufferedReader(Reader);
TestFile = new File("C:\\Users\\danie\\Desktop\\Test.txt");
Writer = new PrintWriter(TestFile);
String Final;
while ((Final = Buffer.readLine()) != null) {
String WPTS[] = Final.split("<wpt");
for (String STD:WPTS) {
Writer.println(STD);
Writer.flush();
Writer.close();
}
}
} catch (IOException EXE) {
System.out.println("Error: " + EXE);
}
Dummy.close();
}
}
I'm really new to Java :(
I think the following code will do the trick ...
the "string" is only used to test the regex
final String string = "lat=\"52.336575\" lon=\"6.381008\">< time>2016-12-19T12:12:27Z< /time>< name>Foto 8 </name>< desc>Dag 4 E&F \nGeb 1.4 \n" + "Hakhoutstoof < /desc>< /wpt>";
final String latitudeRegex = "(?<=lat=\")[0-9]+\\.[0-9]*";
final Pattern latitudePattern = Pattern.compile(latitudeRegex);
final Matcher latitudeMatcher = latitudePattern.matcher(string);
//finds the next (in this case first) subsequence matching the given regex
latitudeMatcher.find();
String latitudeString = latitudeMatcher.group();
double lat = Double.parseDouble(latitudeString); //group returns the match matched by previous match
System.out.println("lat: " + lat);
to get the longitude, just replace lat by lon in the regex
this site is very useful for creating a regex
https://regex101.com/
you can even create the java code at this site

OpenCV Error: Image step is wrong using EigenFaceRecognizer in JavaCV

I am trying to achieve EigenFace Recognition in JavaCV and implementing it through this code:-
public static void main(String[] args) {
String trainingDir = "C:/Users/user/Documents/NetBeansProjects/Face/testimg";
IplImage testImage = cvLoadImage("C:/Users/user/Desktop/aa.png");
File root = new File(trainingDir);
FilenameFilter pngFilter = new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(".png");
}
};
File[] imageFiles = root.listFiles(pngFilter);
MatVector images = new MatVector(imageFiles.length);
int[] labels = new int[imageFiles.length];
int counter = 0;
int label;
IplImage img;
IplImage grayImg = null;
try {
for (File image : imageFiles) {
img = cvLoadImage(image.getAbsolutePath(), CV_BGR2GRAY);
int yer = image.getName().indexOf(".");
String isim = image.getName().substring(0, yer);
label = Integer.parseInt(isim);
images.put(counter, img);
labels[counter] = label;
counter++;
}
} catch (Exception e) {
e.printStackTrace();
}
IplImage greyTestImage = IplImage.create(testImage.width(), testImage.height(), IPL_DEPTH_8U, 1);
//FaceRecognizer faceRecognizer = createFisherFaceRecognizer();
FaceRecognizer faceRecognizer = createEigenFaceRecognizer();
//FaceRecognizer faceRecognizer = createLBPHFaceRecognizer()
faceRecognizer.train(images, labels);
cvCvtColor(testImage, greyTestImage, CV_BGR2GRAY);
int predictedLabel = faceRecognizer.predict(greyTestImage);
System.out.println("Predicted label: " + predictedLabel);
}
But each time I run it,It gives me an error
OpenCV Error: Image step is wrong (The matrix is not continuous, thus its number of rows can not be changed) in cv::Mat::reshape, file ........\opencv\modules\core\src\matrix.cpp, line 802
Exception in thread "main" java.lang.RuntimeException: ........\opencv\modules\core\src\matrix.cpp:802: error: (-13) The matrix is not continuous, thus its number of rows can not be changed in function cv::Mat::reshape
I have read some where that it happens when Images are not of same size and not a multiple of 8,but i have all the images of same size and grayscaled too.The code i used for saving detected Face is:-
Mat image_roi = new Mat(frame,rect_Crop);
Imgproc.cvtColor(image_roi, image_roi, Imgproc.COLOR_BGR2GRAY);
Size sz = new Size(240,240);
Imgproc.resize( image_roi, image_roi, sz );
String filename = "testimg\\" +jTextField1.getText() + ".png";
System.out.println(String.format("Writing %s", filename));
Imgcodecs.imwrite(filename, image_roi);
It also gives me
java.lang.NumberFormatException:
for my files don't know why.....???
Please help....!!!!

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

How do I get both of my arrays to be read in?

I have two arrays the store the values of two lines that are read in from a file. After some processing in my GUI class it should show to rectangles side by side in the middle of the frame. However only one ever shows up. I have tried every way I know how to get the other one to show up but no dice. Here is my code:
public class PortraitFileReader
public static ArrayList<Drawable> readFile(File a) {
File myFile;
ArrayList<Integer> values = new ArrayList<Integer>();
ArrayList<Drawable> couple = new ArrayList<Drawable>();
Man aMan;
Woman aWoman;
Point aPoint;
String input;
String [] array = null;
String [] array2 = null;
try {
myFile = a;
Scanner inFile = new Scanner(myFile);
input = inFile.nextLine();
array = input.split(", ");
while(inFile.hasNext()) {
input = inFile.nextLine();
array2 = input.split(", ");
System.out.println(Arrays.toString(array2));
}
if(array[0].equals("man")) {
for(int i=1; i<array.length-1; i++) {
int current = Integer.parseInt(array[i]);
values.add(current);
System.out.println(values);
}
aPoint = new Point(values.get(0), values.get(1));
aMan = new Man(aPoint, values.get(2), values.get(3), array[5]);
couple.add(aMan);
values.clear();
}
if(array[0].equals("woman")) {
for(int i=1; i<array.length-1; i++) {
int current = Integer.parseInt(array[i]);
values.add(current);
System.out.println(values);
}
aPoint = new Point(values.get(0), values.get(1));
aWoman = new Woman(aPoint, values.get(2), values.get(3), array[5]);
couple.add(aWoman);
values.clear();
}
if(array2[0].equals("man")) {
for(int i=1; i<array2.length-1; i++) {
int current = Integer.parseInt(array[i]);
values.add(current);
System.out.println(values);
}
aPoint = new Point(values.get(0), values.get(1));
aMan = new Man(aPoint, values.get(2), values.get(3), array2[5]);
couple.add(aMan);
values.clear();
}
if(array2[0].equals("woman")) {
for(int i=1; i<array2.length-1; i++) {
int current = Integer.parseInt(array[i]);
values.add(current);
System.out.println(values);
}
aPoint = new Point(values.get(0), values.get(1));
aWoman = new Woman(aPoint, values.get(2), values.get(3), array2[5]);
couple.add(aWoman);
values.clear();
}
}
catch (FileNotFoundException e) {
System.out.println("The file was not found.");
}
return couple;
}
}
This is the data that I'm reading in from the file:
man, 260, 100, 40, 80, Tom
woman, 300, 100, 40, 80, Sally
Any help would be greatly appreciated.
NOTE: the system.out.println's are just there to test if each array had the right values in it.
When you are going through array2 checking if it is a woman, you are actually going through the variable array.
for(int i=1; i<***array2***.length-1; i++) {
int current = Integer.parseInt(****array***[i]);
The same goes for when you are checking if array2 is a man
The effect of this is that you are processing the contents of the first line twice.
Um, I can barely read it, so I rewrote it:
public class PortraitFileReader {
public static ArrayList<Drawable> readFile(File file) {
ArrayList<Drawable> couple = new ArrayList<Drawable>();
try {
Scanner scanner = new Scanner(file);
while(scanner.hasNext()) {
couple.add(parseLine(scanner.nextLine()));
}
}
catch (FileNotFoundException e) {
System.out.println("The file was not found.");
}
return couple;
}
public static Drawable parseLine(String line) {
String [] array = line.split(", ");
String gender = array[0];
int pointX = Integer.parseInt(array[1]);
int pointY = Integer.parseInt(array[2]);
int width = Integer.parseInt(array[3]);
int height = Integer.parseInt(array[4]);
String name = array[5];
if(gender.equals("man")) {
return new Man(new Point(pointX, pointY), width, height, name);
} else {
return new Woman(new Point(pointX, pointY), width, height, name);
}
}
}
Anyway, it looks like either you're not drawing your drawable right, or the input in the file isn't exactly formatted as you expect. The parsing itself seems to make sense....
except that you're always parsing array, and not switching it to parseInt(array2[i]) in the 3rd and 4th block. Which just demonstrates why collapsing these cut and pasted blocks into one method is the sensible way to go.
Inlining everything would look like the above with these edits:
....
Scanner scanner = new Scanner(file);
while(scanner.hasNext()) {
String line = scanner.nextLine();
Drawable person = null;
// everything from parseLine, change return to assignment to person
couple.add(person);
}
....

Categories