Loading image for JAI API - java

I am trying to load an image from my computer into a code to produce a color histogram. My code is compiling but it says that the image is not found, although it is on the Home part of my laptop as 'me.jpg.' Below is the first part of my code, Any tips?
import java.io.*;
import java.awt.image.renderable.ParameterBlock;
import javax.media.jai.*;
public class test {
public test() {
}
public static void main(String[] args) {
PlanarImage image = JAI.create("fileload", "me.jpg"); // Load Image
int [][] imageHistogram = getHistogram(image);
FileWriter writer = null;
File outputFile = new File("test2.txt");

I recommend you store your code and your data (images) in different, proper, places.
Then, open the terminal and set the data directory as the current directory. And invoke the JVM specifying the code directry into the classpath:
java -classpath <directory-of-code> my.class <parameters...>
Update
Also, you could pass the absolute path as a parameter and receive it in your code:
public static void main(String[] args) {
PlanarImage image = JAI.create("fileload", args[0]);
...
And the command line:
java -classpath <directory-of-code> my.class my-home/me.jpg

Related

Even though I added .jar of JAI to Eclipse buildpath , getting "JAI cannot be resolved" error

I'm new to java.
I am trying to use Java Advanced Imaging to read an Image file as explained in here http://www.oracle.com/technetwork/java/iio-141084.html
import java.awt.image.RenderedImage;
import javax.media.jai.JAI;
public class ImageGetterJAI {
public static void main(String[] args)
{
//image source
String imagedir = "C:\\Users\\Emre\\Desktop\\Image\\Grass.tif";
//get the image
RenderedImage image = JAI.create("imageload", imagedir);
}
}
But I get JAI cannot be resolved error. Am I doing a fundamental mistake.
Screenshot of the project is below, hope this helps.

Where does Java save files to?

I ran the below code and created a file. Where can I find it in my filesystem?
import java.io.*;
public class FileReaderDemo {
public static void main(String args[]) throws Exception {
File f = new File ("wayback.txt");
f.createNewFile();
System.out.println(f.exists());
}
}
Add the following to your program, run it and it'll show you the expected location:
System.out.println(f.getCanonicalFile());

How do you open the Windows Command prompt using eclipse with java programming?

I am creating a text based program/ game and someone I know created one that opened the console into the Windows Command prompt. This made it so it could be continually refreshed, making the text clear and having a clean look, rather than the clunky console view, which just adds the text onto it, making a bad medium for a text-based game.
The following may give you an idea:
public static void main(String[] args) throws Exception {
// Since you are using eclipse, bin contains the compiled classes
// This depends on your working directory.
File directory = new File("bin");
// In my case, the main class is Game (in the default package)
ProcessBuilder pb = new ProcessBuilder("cmd", "/c", "java", "Game");
// directory defined above
pb.directory(directory);
// The fun begins!
pb.start();
}
The Game class containing only the following:
import java.util.Scanner;
public class Game {
public static void main(String[] args) {
try (Scanner sc = new Scanner(System.in)) {
System.out.println(sc.nextLine());
}
}
}

Find the name of a File run by a .jar file

I built a .jar file, ex. Test.jar. I open pictures in my computer by this Test.jar file.
How can I receive the absolute path of this picture?
package Run;
import Controll.Controller;
import View.MainFrame;
public class Run {
public static void main(String args[]){
MainFrame view = new MainFrame();
Controller controller = new Controller(view, fileName);
}
}
I write my project by MVC (Model - View - Control) model. The MainFrame class is the view, where i display the picture. The Controller class is the Control where control all works of my project, the constructor of Controller receive twos parameter, one is the View, and another is the fileName (name of the picture that i open by this .jar file). After receiving 2 these parameters, the Controller will display the picture in the View (a Frame).
It means, how can I receive the fileName in the Run.class to pass the parameter fileName into the Controller to work with this file?
You can pass the filename as an argument. It will be received in the args[] array in the main method.
So if you do java Run "/home/something/filename.jpg"
you can access it in the main function
public static void main(String[] args) {
String fileName = args[0];
}

How to resize images in a directory?

This code attempts to resize images in a directory called "imgs". Unfortunately for some reason when I uncomment the listFiles(..) loop ImageIO.read(sourceImageFile) will return null. Yet processing the same file straightaway outside the loop (res("imgs/foto_3.jpg")) works. So apparently, this loop is preventing the files from being read. Solutions?
import java.awt.image.*;
import java.io.*;
import javax.imageio.*;
import static org.imgscalr.Scalr.*;
public class App {
public static void main(String[] args) throws IOException {
// for (File sourceImageFile : new File("imgs").listFiles()) {
// res("imgs/"+sourceImageFile.getName());
// }
res("imgs/foto_3.jpg");
}
public static void res(String arg) throws IOException {
File sourceImageFile = new File(arg);
BufferedImage img = ImageIO.read(sourceImageFile);
BufferedImage thumbnail = resize(img, 500);
thumbnail.createGraphics().drawImage(thumbnail, 0, 0, null);
ImageIO.write(thumbnail, "jpg", new File("resized/" + sourceImageFile.getName()));
}
}
To reproduce the problem you can download the Maven project.
Can you change res to accept a File object rather than a String? Then you could write the following, which is a lot nicer:
for (File sourceImageFile : new File("imgs").listFiles()) {
res(sourceImageFile);
}
As to your original question, try adding some tracing statements or using a debugger to find what exactly gets passed to res.
I am not sure why the file listing iteration would mess with the thumbnail generation, but you mentioned privately to me that you were using imgscalr and were curious what the correct code to batch-process a directory would look like, so I wrote up this example code for you.
The code below will process any directory (imgs is hard-coded to stay consistent with your example code) and write it out to any other directory (resized is used to stay consistent -- feel free to change either directory)
import static org.imgscalr.Scalr.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class ScaleDirExample {
public static void main(String[] args) throws IOException {
File[] images = new File("imgs").listFiles();
for (File f : images) {
System.out.println("Processing: " + f.getName() + "...");
if (f.isDirectory()) {
System.out.println("\tSkipping, file is a directory...");
continue;
} else
process(f);
}
}
private static void process(File file) throws IOException {
// Load image.
BufferedImage image = ImageIO.read(file);
// Resize image.
image = resize(image, 500);
// Save the resized image as the thumbnail.
saveThumbnail(file, image);
}
private static void saveThumbnail(File originalFile, BufferedImage thumbnail)
throws IOException {
String filename = originalFile.getName();
// Determine file extension.
String fileExt = filename.substring(filename.lastIndexOf('.') + 1);
// Save the thumbnail to the resized dir.
ImageIO.write(thumbnail, fileExt, new File("resized/" + filename));
}
}
The call to resize(image, 500) can be modified to match any of the Scalr.resize methods - you can pass filters or improve quality if you want.
Example output from my test setup looks like:
Processing: flower-dog-gimp.jpg...
Processing: flower-dog.jpg...
Processing: logoOXdaComida.png...
Processing: mr-t-thumbnail.jpg...
Processing: mr-t.jpg...
Processing: problem-trans-peter-griffin.png...
Hope that helps!
OK, I figured it out. now it's working.
You (or whoever created the downloadable project u pasted here) are using Mac OS, and it automatically creates a .DS_Store file.
When you try to pass it to the res method, it doesn't know how to handle a non-image file and acts as null.
public static void main(String[] args) throws IOException {
for (File sourceImageFile : new File("imgs").listFiles()) {
if (sourceImageFile.getName().endsWith(".jpg"))
res(sourceImageFile.getAbsolutePath());
}
}
This is the modified void main method. it works, u can refine the if statement for more in depth filtering of wrong files.
Also I changed the argument given to the res method. it looks better now, as getAbsoulutePath returns the name and the path.
Let me know how it worked
One obvious way to debug this to output the specific sourceImageFile that ImageIO.read(..) is returning null on. I suspect its because listFiles will give you a list of all files and directories that are in the image directory. listFiles javadoc. You can prevent that by using a FileFilter that makes sure that listFiles only returns files and additionally files of the right type.
An example of a file filter that only returns file is below:
import java.io.FileFilter
class RegularFilesOnlyFileFilter implements FileFilter {
public boolean accept(File pathName) {
return pathName.isFile();
}
}
The way to use this filter is this - new File("imgs").listFiles(new RegularFilesOnlyFilesFilter())
I've changed res method:
public static void res(File arg) throws IOException {
if (arg.contains(".DS_Store")) {
return;
}
A mac-issue (or should filter non-image files, as was suggested)!

Categories

Resources