Can not load image in JavaFx - java

I want to load image and video in JavaFX.The related part of my code is given below where video loading part is okay but Image loading part is not working.Can you give me the solution?
if (serialvalue == 1) {
String infoquery = "select * from information where " + "categoryname like " + "'%" + selectedcategory + "%'";
try {
filename = getFilePathForCorrespodingSerial(infoquery, serialvalue);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("You path for video : " + filename);
System.out.println("my choiche");
//File path = new File("C:\\Users\\User\\Downloads\\RGACD_Directory\\arosh.jpg");
java.io.FileInputStream fis = null;
try {
fis = new FileInputStream("C:\\Users\\User\\Downloads\\RGACD_Directory\\arosh.jpg");
} catch (Exception e) {
e.printStackTrace();
}
im = new ImageView(new Image(fis));
String newpath = "C:\\Users\\User\\Downloads\\RGACD_Directory\\" + filename;
me1 = new Media(new File(newpath).toURI().toString());
mp1 = new MediaPlayer(me1);
mv1.setMediaPlayer(mp1);
mp1.setAutoPlay(true);
}

This works for me.
final ImageView im = new ImageView(
new Image(new File("C:/Users/User/Downloads/RGACD_Directory/arosh.jpg").toURI().toString()));

Can you give us the stack trace.
Try this, put the image file in the package where your java file resides and write the code as:
ImageView icon = new ImageView(new Image(getClass().getResourceAsStream("/main/view/images/inbox.png")));
The main package is just after the src directory.
In my case, My java file is in the view package. Also note that in window we use '\\' as separators and in linux we use backslash (/).

Finally, this works for me:
#FXML
ImageView im;
im.setImage(new Image("file:///C:\\Users\\User\\Downloads\\arosh.png");

Related

Load multiple images with different paths

so i try to load two images from the same path but with different names.
if i copy the path directly from the image everything work fine.
but if i try to build the path from the system only one of them work(img1).
i've try couple of different ways i found in the internet to build the path but the results are the same.
what can cause this problem?
public void loadImages(String nm) {
File f = null;
BufferedImage image = null;
System.out.println("read img:");
String pathName = PICTURE_PATH + this.getMyColor().toString().toLowerCase() + nm;
// read successful this img path.
try {
f = new File(pathName + "North.png");
f.canRead();
System.out.println("\nimg1 path:" + f);
System.out.print("img1 absolute path:" + f.getAbsolutePath());
img1 = ImageIO.read(f);
if (!f.canRead())
throw new IOException("Cant read the first file");
if (!f.exists())
throw new IOException("Cant find the first file");
System.out.println("Successful read img 1");
} catch (IOException e) {
System.out.println("Error:" + e);
}
// got here exception error for this img path.
try {
f = new File(pathName + "East.png");
System.out.println("\nimg2 path:" + f);
System.out.println("img2 absolute path:" + f.getAbsolutePath());
if (!f.canRead())
throw new IOException("Cant read the second file");
if (!f.exists())
throw new IOException("Cant find the second file");
img2 = ImageIO.read(f);
System.out.println("Successful read img 2");
} catch (IOException e) {
System.out.println("Error:" + e);
}
System.out.println("Done.");
}
//this is the relevant output for this function:
//read img:
img1 path:src\icons\‏‏silverCarNorth.png
img1 absolute path:A:\Tools\eclipse\WorkPlace\HW1\src\icons\‏‏silverCarNorth.png
Successful read img 1
img2 path:src\icons\‏‏silverCarEast.png
img2 absolute path:A:\Tools\eclipse\WorkPlace\HW1\src\icons\‏‏silverCarEast.png
Error:java.io.IOException: Cant read the second file
Done.
so its appear the images had some extra characters..
the site not support this kind of characters so i add a print screen from the cmd.
this is the logs from the cmd:
cmd logs
so i had to rename the files and delete the extra characters manually with the windows command line.
and after that everything works just fine!

Can't delete image which is being used by anoher process

i started to use thumbnailator library to make thumbnail in a Spring Boot project
But i'm facing a problem when i try to delete the file, i got an exception telling me the file is being used by another process. I pretty new with Java and i can't figured out where does the problem might come from and what process should i stop/close:
File originalFile = mediaUtils.saveFile(pathOriginal, file);
String path = mediaUtils.resolvePath(imageDir, name, false, image.getCreation());
mediaUtils.saveJPG(originalFile, file.getContentType(), WIDTH_IMAGE_SIZE, path);
String pathThumb = mediaUtils.resolvePath(imageDir, name, true, image.getCreation());
mediaUtils.saveJPG(originalFile, file.getContentType(), WIDTH_IMAGE_SIZE_THUMB, pathThumb);
public File saveFile(String filePath, MultipartFile file) {
try {
Path path = Paths.get(getPath(filePath));
Files.createDirectories(path.getParent());
Files.copy(file.getInputStream(), path);
return new File(path.toString());
} catch (IOException e) {
LOG.error("could not save file", e);
throw new FileException("could not create file: " + getPath(filePath), e);
}
}
private void saveJPG(InputStream imageInputStream, File file, String contentType, int newWidth, String outputPath) {
try {
// verify it is an image
if (!Arrays.asList("image/png", "image/jpeg").contains(contentType)) {
throw new IllegalArgumentException("The file provided is not a valid image or is not supported (should be png or jpeg): " + contentType);
}
// Create input image
BufferedImage inputImage = ImageIO.read(imageInputStream);
newWidth = newWidth > inputImage.getWidth() ? inputImage.getWidth() : newWidth;
double ratio = (double) inputImage.getWidth() / (double) inputImage.getHeight();
int scaledHeight = (int) (newWidth / ratio);
Path path = Paths.get(baseUrl + outputPath + ".jpg");
Thumbnails.of(file)
.size(newWidth, scaledHeight)
.toFile(path.toFile());
LOG.info("writing image to {}", path);
} catch (IOException e) {
LOG.error("could not write image", e);
}
}
Thanks for any advice or help :)
You should make sure to close your inputstreams and files, after you've used them.
Otherwise things like you've mentioned, happen. A process does block your file.
So instead of using simple try-catch-blocks I would recommend to use try-with-resources which will close the underlying streams and files. For example:
try(InputStream imageInputStream = new FileInputStream(...)) {
// do your stuff
}
After the code in the brackets is done or an exception occured, the inputstream will be closed.

How To Copy File From SD to Local Storage on Android

I know with Kit Kat you can only write to your applications package specific directory on SD Cards. I was however under the impression you could still copy files from an SD card to local storage with the:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
I am simply testing if I can copy one file. If I am able to do that I will add the code to search the entire SD card DCIM folder. For now I have the following code (please forgive the messiness of the code, I have written C# and vb.net but java is still very new to me):
String dirPath = getFilesDir().getAbsolutePath() + File.separator + "TCM";
File projDir = new File(dirPath);
if (!projDir.exists())
projDir.mkdirs();
String CamPath = projDir + File.separator + tv2.getText();
File projDir2 = new File(CamPath);
if (!projDir2.exists())
projDir2.mkdirs();
File LocalBuck = new File(projDir2 + File.separator );
String imageInSD = Environment.getExternalStorageDirectory().getAbsolutePath();
File directory1 = new File (sdCard.getAbsolutePath() + "/DCIM");
File directory = new File(directory1 + "/100SDCIM");
File Buckfile = new File(directory, "/BigBuck.jpg");
try {
exportFile(Buckfile, LocalBuck);
} catch (IOException e) {
e.printStackTrace();
}
Here is my code for the export function/application:
private File exportFile(File src, File dst) throws IOException {
//if folder does not exist
if (!dst.exists()) {
if (!dst.mkdir()) {
return null;
}
}
String timeStamp = new SimpleDateFormat("yyyy_MM_dd_HHmmss").format(new Date());
File expFile = new File(dst.getPath() + File.separator + "IMG_" + timeStamp + ".jpg");
FileChannel inChannel = null;
FileChannel outChannel = null;
try {
//Straight to Error Handler
inChannel = new FileInputStream(src).getChannel();
outChannel = new FileOutputStream(expFile).getChannel();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
inChannel.transferTo(0, inChannel.size(), outChannel);
} finally {
if (inChannel != null)
inChannel.close();
if (outChannel != null)
outChannel.close();
}
return expFile;
}
Here is what my emulator looks like:
Looking for: Debug of SD Location
Should Find It?: EmulatorShowingSd
Question: Am I even able to copy a file from the SD card to local storage after KitKat; if so what is wrong in the code causing the exception to be thrown when it tries to access the SD card file?

Trying to create file without succes - file appears elsewhere?

I tried to create 3 empty files in my home directory, using this:
this.mainpath = System.getenv("HOME"+"/");
this.single = new File(mainpath + "sin.r");
this.complete = new File (mainpath + "com.r");
this.ward = new File (mainpath+"w.r");
I was unter the impression that this would give me the files desired. However, if I search my home directory, or any other directory, for this files, none of them exists. What am I doing wrong?
Edit: I just find out: I do get a file, but not in my home directory, but the path to it would be /home/myname/NetBeansProjects/myorojectname/nullsin.r.
However, I specifically wanted to create the file in my home!
Well, my code now reads:
this.mainpath = System.getenv("user.home");
this.mainpath = this.mainpath + "/";
this.single = new File(mainpath + "sin.r");
this.single.createNewFile();
System.out.println(this.single.getAbsolutePath());
this.complete = new File (mainpath + "comp.r");
this.complete.createNewFile();
this.ward = new File (mainpath+"w.r");
this.ward.createNewFile();
The "success" of this, however, is that I get an IOException at the first createNeWFile(): File not found.
as for my code how I tried to write sth into those file, there it is:
FileWriter writer1 = null;
FileWriter writer2 = null;
FileWriter writer3 = null;
try {
writer1 = new FileWriter(single);
writer2 = new FileWriter(complete);
writer3 = new FileWriter(ward);
writer1.write("x = cbind(1,2,3)");
writer2.write("x = cbind(1,2,3)");
writer3.write("x = cbind(1,2,3)");
writer1.flush();
writer2.flush();
writer3.flush();
} catch (IOException ex) {
System.out.println(ex.getStackTrace());
} finally {
try {
writer1.close();
writer2.close();
writer3.close();
} catch (IOException ex) {
System.out.println(ex.getStackTrace());
}
You need to use getProperty() instead
System.getProperty("user.home");
Also, the / should be appended after getting the directory path.
this.mainpath = System.getProperty("user.home");
this.single = new File(mainpath + "/sin.r");
this.complete = new File (mainpath + "/com.r");
this.ward = new File (mainpath+"/w.r");
You can call the "createNewFile"-method for each of the objects you've declared to actually create them.

My working directory, files, and urls

I have a convergence of needs revolving around where my data files are. The current application has all class and data files in a JAR (building using Eclipse IDE).
I've noticed there seem to be a variety of ways in which people get this information. I need the path for where my image files are (graphics). I also need it as a URL o use the toolkit call.
Toolkit tk = frame.getToolkit();
image = tk.getImage(url.toFile());
But I am having trouble with creating the URL or something. I have tried a few different methods. At this point, I keep data files next to class files in the file system. I am adding another function to what I do - strip the /bin directory off when running in debug.
// in class BwServices at init:
try {
rootDataPath = BwServices.class.getProtectionDomain()
.getCodeSource().getLocation().getPath();
rootDataPath = URLDecoder.decode(rootDataPath, "UTF-8");
fileSystemAccess = true;
}
if(rootDataPath.endsWith("/bin/"))
rootDataPath = rootDataPath.substring(0, rootDataPath.length() - 4);
Later on... I go to get images, and some calls don't work, I don't know why
I've tried two things....
// 1
String s = "file://" + rootDataPath + d.toString() + fileName;
url = frame.getClass().getResource(s);
// 2
try {
url = new URL(s);
} catch (MalformedURLException e) {
trace("getImage - can't get url: " + s);
e.printStackTrace();
}
Either of which has problems.
I have calls to get images from different places. The 'frame' is the parent frame throughout the execution, in class BwFrame.
My path comes out like this in any attempts...
rootDataPath: /C:/Users/Markgm/Documents/DEV/workspace/bwp/
So, I'm looking for ways to open either FileInputStream or URLs for the toolkit, for files relative to where the class file is (and with some trick for when in debug). For a client-side app this is what this is. Someday, I might want to run this as an Applet, but I don't know where the image files will have to be. (50x75 playing cards and a few button images) Any help or advice is appreciated!
TIA,
Mark
Toolkit tk = frame.getToolkit();
Don't use Toolkit to load images, since Java 1.4. Use ImageIO.read(String/File/URL) instead, which is a blocking method that ensures the entire image is loaded before returning.
image = tk.getImage(url.toString());
And there is an actual problem. Once you have an URL (or File) object, don't toss it away and use the String representation. Even more importantly, don't provide a String that is supposed to represent a File, but actually represents an URL!
I didn't read the rest of that mess of code snippets (in the question or follow-up 'answer'), you might look to post an SSCCE in future.
I got rid of using URLs at all, which started with the use of pasted code. The behavior of URLs changed, as did everything, when running from a class file versus running from a JAR file. So I have code here that shows some of what I ended up doing, and comments to what happens (class file or jar file), and I also got the adjustment for debug time to work (snipping off bin/ from the end).
// root path - starts with jar file or pathspec
try {
rootDataPath = BwServices.class.getProtectionDomain()
.getCodeSource().getLocation().getPath();
rootDataPath = URLDecoder.decode(rootDataPath, "UTF-8");
if(rootDataPath.endsWith("BwPlayer.jar"))
rootDataPath = rootDataPath.substring(0, rootDataPath.length() - 12);
fileSystemAccess = true;
} catch(SecurityException e) {
trace("No file system access: " + e.getMessage());
messageBox(frame, "BwServices", "Cannot access file system");
rootDataPath = "";
} catch (UnsupportedEncodingException e) {
trace("Jar URL decode exception: "+ e.getMessage());
}
if(rootDataPath.endsWith("/bin/")) // remove bin/ portion if in debug
rootDataPath = rootDataPath.substring(0, rootDataPath.length() - 4);
trace("rootDataPath: "+rootDataPath);
Above: from init() time. Below, a getImage() function, including extra debug-related lines. Note: url.getFile() doesn't directly work for 2 reasons - one is it has the file:/ when out of a jar, and the other because it won't take a full pathspec beneath its pre-stated root /.
static public Image getImage(Directory d, String fileName) {
Image image = null;
String s = d.toString() + fileName;
/*
// Note: Start with / required for this url call (w/o full pathsepc)
URL url = parentFrame.getClass().getResource("/" + s);
if(url == null) {
trace(s + " - null url ");
return null;
}
*/
String file = rootDataPath + s; // url.getFile();
// end note
String t = s = "getImage(" + file + ") ";
Toolkit tk = parentFrame.getToolkit();
if(tk == null)
s = s + "NULL tk ";
else {
try {
// full pathspec needed here
// url.getFile() returns with file:/ when running from the .jar file
// but not when running from .class file (so don't use it)
s = t = "getImage(" + file + ") ";
image = tk.getImage(file); //url.getFile());
MediaTracker media = new MediaTracker(parentFrame);
media.addImage(image, 0);
try {
media.waitForID(0);
} catch(InterruptedException e) {
s = s + e.getMessage();
}
if(image == null) {
// image = null;
s = s + "NULL image ";
} else if(image.getHeight(parentFrame) < 1) {
s = s + "invalid height";
}
} catch (SecurityException e) {
s = s + e.getMessage();
}
}
if(! s.equals(t)) {
s = "file=" + file + "\n" + s;
s = "rootDataPath=" + rootDataPath + "\n" + s;
messageBox(parentFrame, "getImage()", s);
}
return image;
}

Categories