I want to read all the images in a folder using Java.
When: I press a button in the Java application,
It should:
ask for the directory's path in a popup,
then load all the images from this directory,
then display their names, dimension types and size.
How to proceed?
I have the code for read the image and also for all image in the folder but how the things i told above can be done?
Any suggestion or help is welcome! Please provide reference links!
Untested because not on a machine with a JDK installed, so bear with me, that's all typed-in "as-is", but should get you started (expect a rush of downvotes...)
Loading all the Images from a Folder
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import javax.imageio.ImageIO;
public class Test {
// File representing the folder that you select using a FileChooser
static final File dir = new File("PATH_TO_YOUR_DIRECTORY");
// array of supported extensions (use a List if you prefer)
static final String[] EXTENSIONS = new String[]{
"gif", "png", "bmp" // and other formats you need
};
// filter to identify images based on their extensions
static final FilenameFilter IMAGE_FILTER = new FilenameFilter() {
#Override
public boolean accept(final File dir, final String name) {
for (final String ext : EXTENSIONS) {
if (name.endsWith("." + ext)) {
return (true);
}
}
return (false);
}
};
public static void main(String[] args) {
if (dir.isDirectory()) { // make sure it's a directory
for (final File f : dir.listFiles(IMAGE_FILTER)) {
BufferedImage img = null;
try {
img = ImageIO.read(f);
// you probably want something more involved here
// to display in your UI
System.out.println("image: " + f.getName());
System.out.println(" width : " + img.getWidth());
System.out.println(" height: " + img.getHeight());
System.out.println(" size : " + f.length());
} catch (final IOException e) {
// handle errors here
}
}
}
}
}
APIs Used
This is relatively simple to do and uses only standard JDK-packaged classes:
File
FilenameFilter
BufferedImage
ImageIO
These sessions of the Java Tutorial might help you as well:
Reading/Loading an Image
How to Use Icons
How to Use File Choosers
Possible Enhancements
Use Apache Commons FilenameUtils to extract files' extensions
Detect files based on actual mime-types or content, not based on extensions
I leave UI code up to you. As I'm unaware if this is homework or not, I don't want to provide a full solution. But to continue:
Look at a FileChooser to select the folder.
I assume you already know how to make frames/windows/dialogs.
Read the Java Tutorial How to Use Icons sections, which teaches you how to display and label them.
I left out some issues to be dealt with:
Exception handling
Folders with evil endigs (say you have a folder "TryMeIAmEvil.png")
By combining all of the above, it's pretty easy to do.
javaxt.io.Directory directory = new javaxt.io.Directory("C:\Users\Public\Pictures\Sample Pictures");
directory.getFiles();
javaxt.io.File[] files;
java.io.FileFilter filter = file -> !file.isHidden() && (file.isDirectory() || (file.getName().endsWith(".jpg")));
files = directory.getFiles(filter, true);
System.out.println(Arrays.toString(files));
step 1=first of all make a folder out of webapps
step2= write code to uploading a image in ur folder
step3=write a code to display a image in ur respective jsp,html,jframe what u want
this is folder=(images)
reading image for folder'
Image image = null;
try {
File sourceimage = new File("D:\\images\\slide4.jpg");
image = ImageIO.read(sourceimage);
} catch (IOException e) {
e.printStackTrace();
}
}
Related
I am currently creating a spring boot application that allows the user to store a database of books to organize and search throughout. I have added a feature within the addition portion of the application that uses Tesseract OCR to scan an image of a book cover to extract as much information as it can so the user can copy paste the title and author over to the addition text boxes. I want this to be used by users from their own computers but I'm not sure how to set up the File system so that it can read from the input source instead of the code being changed. Code below...
bookScanner.java
import java.io.File;
import net.sourceforge.tess4j.*;
public class bookScanner {
public String booksScanner() {
File imageFile = new File("\path\to\file\book.jpg");
//Change Datapath based off of computer
ITesseract instance = new Tesseract();
instance.setDatapath("\path\to\file");
try {
String result = instance.doOCR(imageFile);
return result;
}
catch (TesseractException e) {
System.err.println(e.getMessage());
return "";
}
}
}
File imageFile = new File("\path\to\file"); This snippet right here is the problem. I don't want this to be hardcoded because a foreign user may have the image labeled as BookCover and it might be a png or jpeg and it won't scan.
FIXED
I used a file reading system to access and read the newest submitted file and it all works as intended now if anyone has troubles with this later on, here is the following code...
File folder = new File("\path\to\file");
File[] listOfFiles = folder.listFiles();
long lastModifiedTime = Long.MIN_VALUE;
File chosenFile = null;
if (listOfFiles != null) {
for (File file: listOfFiles) {
if (file.lastModified() > lastModifiedTime) {
chosenFile = file;
lastModifiedTime = file.lastModified();
if (chosenFile.isFile()) {
chosenFile = new File("\path\to\file" + file.getName());
System.out.println(chosenFile);
}
}
}
}
I'm trying to load an image from an executable JAR file.
I've followed the information from here, then the information from here.
This is the function to retrieve the images:
public static ImageIcon loadImage(String fileName, Object o) {
BufferedImage buff = null;
try {
buff = ImageIO.read(o.getClass().getResource(fileName));
// Also tried getResourceAsStream
} catch (IOException e) {
e.printStackTrace();
return null;
}
if (buff == null) {
System.out.println("Image Null");
return null;
}
return new ImageIcon(buff);
}
And this is how it's being called:
logo = FileConverter.loadImage("/pictures/Logo1.png", this);
JFrame.setIconImage(logo.getImage());
With this being a simple Object.
I'm also not getting a NullPointerException unless it is being masked by the UI.
I checked the JAR file and the image is at:
/pictures/Logo1.png
This current code works both in eclipse and when it's been exported to a JAR and run in a terminal, but doesn't work when the JAR is double clicked, in which case the icon is the default JFrame icon.
Thanks for you're help. It's probably only me missing something obvious.
I had a similar problem once, which turned out to be down to issues relative addressing and my path being in the wrong place somehow. I dug this out of some old code I wrote that made it use an absolute path. That seemed to fix my problem; maybe it will work for you.
String basePath = (new File(".")).getAbsolutePath();
basePath = basePath.substring(0, basePath.length()-1);
FileConverter.loadImage(basePath+"/pictures/Logo1.png", this);
I'm trying to write a program that copies a website to my harddrive. This is easy enough to do just copying over the source and saving it as an html file, but In doing that you can't access any of the pictures, videos etc offline. I was wondering if there is a way to do this using an input/output stream and if so how exactly to do it...
Thanks so much in advance
If you have URL of the file to be downloaded then you can simply do it using apache commons-io
org.apache.commons.io.FileUtils.copyURLToFile(URL, File);
EDIT :
This code will download a zip file on your desktop.
import static org.apache.commons.io.FileUtils.copyURLToFile;
public static void Download() {
URL dl = null;
File fl = null;
try {
fl = new File(System.getProperty("user.home").replace("\\", "/") + "/Desktop/Screenshots.zip");
dl = new URL("http://example.com/uploads/Screenshots.zip");
copyURLToFile(dl, fl);
} catch (Exception e) {
System.out.println(e);
}
}
I'm having problems displaying icons in a JList that I've made. I'm passing a path to the function getResource() and then storing the resource in a URL object. However, every time I call the getResource() function it returns a null, even though the images exist in the directory.
I've tried looking around on stackoverflow and other sites but I can't find a solution to this problem. I even tried storing the images in multiple locations inside my project directory but to no avail. If it helps, I'm using the Eclipse IDE. So I've stored the files in the /src/, /src/resources/, and the project folder.
Here is my code:
import java.awt.*;
import java.io.*;
import java.net.URL;
import java.util.ArrayList;
import javax.swing.*;
#SuppressWarnings("serial")
public class JListRenderer extends DefaultListCellRenderer
{
private static ArrayList<CakeRecipe> cRecipes;
private ImageIcon[] images;
// Index of cake recipe
private int cakeIndex;
JListRenderer(ArrayList<CakeRecipe> recipes)
{
cRecipes = recipes;
// Initializes an array of ImageIcons FileHander.jpgCounter() counts the amount of JPG's in the folder, FileHandler.getPath() gives you the filepath
images = new ImageIcon[FileHandler.jpgCounter(new File(FileHandler.getPath()))];
for(int i = 0, j = images.length; i < j; i++)
images[i] = createImageIcon("/resources/" + cRecipes.get(cakeIndex).getPhoto()); // cRecipes.get().getPhoto() gives you the filename of the village only (e.g.: photo.jpg)
}
protected static ImageIcon createImageIcon(String path)
{
URL imgURL = JListRenderer.class.getResource(path);
if(imgURL != null)
return new ImageIcon(imgURL);
else
{
System.err.println("Could not find image. Certain menu elements may not display properly");
return null;
}
}
...
Should this code work or am I not using the URL or getResource() properly? The images are in the directory, and I'm passing a path identical to the image's path. Example:
"/resources/photo.jpg"
Any help would be greatly appreciated. Thank you.
EDIT: The problem was with Eclipse. It didn't register the resources in the build path. A simple "Refresh fixed the problem. Thanks for all your help, everyone.
It looks like it should work. I've tried running the following, with a test.txt file in the resources package:
package resourcestest;
import java.io.File;
import java.io.FileReader;
import java.net.URL;
public class Test {
public static void main(String[] args) throws Exception {
final URL test = Test.class.getResource("/");
System.out.println(test);
final URL url = Test.class.getResource("/resources/test.txt");
System.out.println(url);
if(url == null) {
System.out.println("URL is null");
} else {
final File file = new File(url.toURI());
final FileReader reader = new FileReader(file);
final char[] buff = new char[20];
final int l = reader.read(buff);
System.out.println(new String(buff, 0, l));
reader.close();
}
}
}
The first two statements in the main method can be of use to find out what path is considered the relative root at runtime.
I've tried this in NetBeans and Eclipse and in both cases it worked. Now, the real question is, what's your project setup and how do you build? Is there a separate folder for sources and class files or are they put together? Do you use an Ant script or Eclipse build methods?
If you've got the files only in a folder and not in a package, then it's not certain that they're gonna be on the compilation path or on the runtime class path. I suspect the latter may be the case. Try to make sure resources is a package, not a folder. Try creating a jar file from your project, then check its contents to see if your resources were included. Try running from the jar file and see if it makes a difference.
Becasue it's awkward to show all the relevant factors, it may be difficult to identify the problem in your particular situation. Instead, you might start with this working example and compare it with your own implementation.
i am trying to create a text file in a folder (called AMCData). The file is called "File" (for the sake of this example).
I have tried using this code:
public static void OpenFile(String filename)
{
try
{
f = new Formatter("AMCData/" + filename + ".txt");
}
catch(Exception e)
{
System.out.println("error present");
}
}
But before i get the chance to even place any text in it, the catch keeps being triggered..
Could anyone inform me why this is occuring?
more information:
The folder does not exist, i was hoping it would automatically create it
If it doesn't automatically create folders, could you please link me to how to do so?
You're right, a Formatter(String) constructor needs the file to be present or createable. The most likely reason why a file cannot be created is that it references a folder that itself doesn't exist, so you should use the File.mkdirs() method, like this:
new File("AMCData").mkdirs();