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!
Related
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.
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");
I have been struggling for two days to try and understand the process of copying a file to the SD card in Android. None of the methods I tried thus far seem to work.
My application has a Profile Picture setting. I need to launch an Intent to pick an Image, then I need to copy the Image to a new Path on the SD Card and then return the Uri of the new Image at which point I check the Images Orientation (Samsung Pics seem to be rotated 90 degrees sometimes). I then rotate the Image correctly and then save the Uri to a SharedPreferences File for use in the Application.
This is my Intent Call:
case R.id.ib_userImage:
i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
startActivityForResult(i, 1);
break;
This is my current horrific attempt at the copy function, I have changed it so much I am not very lost.
public static void copyImage(Context context, Uri uri) {
Log.i("ATTENTION", "Inside the Copy Function");
Log.i("ATTENTION", "Trying to copy file: " + uri.toString());
try {
String outputPath = Environment.getExternalStorageDirectory() + "/appname/images/";
File dir = new File(outputPath);
if(!dir.exists()) {
dir.mkdirs();
}
Log.i("ATTENTION", "Destination File Created at: " + dir.toURI().toString());
InputStream in = context.getContentResolver().openInputStream(uri);
OutputStream out = new FileOutputStream(dir);
byte[] buffer = new byte[1024];
while(in.read(buffer) > 0) {
out.write(buffer);
}
out.flush();
out.close();
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Log.i("ATTENTION", "File Copied");
}
Thank you for the help, I will provide any other information you might need.
Update:
I am now getting the Following Exception During the Write Process
java.io.FileNotFoundException: /storage/emulated/0/appname/images: open failed: EISDIR (Is a Directory);
My Understaing is that I specified a Directory with the following code:
String outputPath = Environment.getExternalStorageDirectory() + "/medinfo/images/";
File dir = new File(outputPath);
if(!dir.exists()) {
dir.mkdirs();
}
and then passed it to the OutputStream:
OutputStream out = new FileOutputStream(dir);
and the OutputStream would create the file for me within that Directory.
I didn't think that was actually trying to open the Directory.
Usual problem. Don't ignore the count returned by read().
while ((count = in,read(buffer)) > 0)
{
out.write(buffer, 0, count);
}
EDIT Your directory problem is cured by:
dir.getParentFile().mkdirs();
and removing the redundant existence check. At present you are creating the file itself as a directory.
i have below code that work in some phone and dont work in some other phone.
my code is for saving an image.
String path = Environment.getExternalStorageDirectory().toString();
path += "/";
File fff=new File(path + "/xalopex/Mobile/");
if (!fff.exists())
fff.mkdirs();
path += "xalopex/Mobile/";
path += "lg";
File filename;
try {
filename = new File(path + ".jpg");
FileOutputStream out = new FileOutputStream(filename);
MyImageBitMap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
MediaStore.Images.Media.insertImage(getContentResolver(),
filename.getAbsolutePath(), filename.getName(),
filename.getName());
} catch (Exception e) {
e.printStackTrace();
//this part will run
// e is storage/emulated/0/xalopex/Mobile/lg.jpg open faild:ENOENT (no such file or directory)
}
where i am wrong ?
How i can fix it?
I would hazard a guess and say its because you need to be accessing /storage/emulated/legacy instead of /storage/emulated/0
I could be wrong.. but I see there are no accepted answers so I'll give this a try :)
I'm making a program that takes a screenshot and I want to have it so that i have a JButton with an actionlistener that when pressed it saves the image to a certain folder that if does not already exists it makes.
here is what I thought I should do:
#Override
public void actionPerformed(ActionEvent arg0) {
File dir = new File("C://SnippingTool+/" + date.getDay());
dir.mkdirs();
try {
ImageIO.write(shot, "JPG", dir);
} catch (IOException e) {
e.printStackTrace();
}
}
});
I think it has something to do with my File dir = new File and that I am not saving to to the right place.
Here is my Robot taking a screenshot:
try {
shot = new Robot().createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
} catch (HeadlessException e1) {
e1.printStackTrace();
} catch (AWTException e1) {
e1.printStackTrace();
}
The problem, as I see it is with these two lines...
File dir = new File("C://SnippingTool+/" + date.getDay());
dir.mkdirs();
This now means that the output you are trying to write to is a directory, when ImageIO is expecting a file, this will fail...
Instead try something like...
File output = new File("C://SnippingTool+/" + date.getDay() + ".jpg");
File dir = output.getParentFile();
if (dir.exists() || dir.mkdirs()) {
try {
ImageIO.write(shot, "JPG", output);
} catch (IOException e) {
e.printStackTrace();
}
} else {
System.out.println("Bad Path - " + dir);
}
In response to your comment:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at main$2$2.actionPerformed(main.java:148)
That is at the:
File output = new File(System.getProperty("user.home") +
date.getDay() + ".jpg");
(I changed the "C:\" to System.getProperty("User.home")).
There are only two possible causes of an NPE in that line (wrapped for readability):
If System.getProperty cannot find the named property, it will return a null. Now the "user.home" property should exist ... but "User.home" almost certainly does NOT exist. (Property names are case sensitive!!)
If date is null or date.getDay() returns null. We don't know how you initialized date ... or even what type it is. (Though Date would be a good guess ...)
Both the "user.home" property and the "user.dir" property would work ... though they mean different things.