ImageIO.write didn't work? - java

Hello I have problem with followed function that should save forwarded bufferedImage on disk. When I run this code there no exception throwed no problems, BufferedImage is transfered to ImageIO.write(img, ext ,fileToSave) file was created, ext is correct but there no image on my disk! After hours i dont have idea what can go wrong. Maybe permission? But i have it to read/write on disk.
public boolean SaveImage(BufferedImage img)
{
JFileChooser FC=new JFileChooser("C:/");
FC.addChoosableFileFilter(new jpgSaveFilter());
FC.addChoosableFileFilter(new jpegSaveFilter());
FC.addChoosableFileFilter(new PngSaveFilter());
FC.addChoosableFileFilter(new gifSaveFilter());
FC.addChoosableFileFilter(new BMPSaveFilter());
FC.addChoosableFileFilter(new wbmpSaveFilter());
int retrival=FC.showSaveDialog(null);
if (retrival == FC.APPROVE_OPTION)
{
String ext="";
String extension=FC.getFileFilter().getDescription();
if(extension.equals("*.jpg,*.JPG"))
{
ext=".jpg";
}
if(extension.equals("*.png,*.PNG"))
{
ext=".png";
}
if(extension.equals("*.gif,*.GIF"))
{
ext=".gif";
}
if(extension.equals("*.wbmp,*.WBMP"))
{
ext=".wbmp";
}
if(extension.equals("*.jpeg,*.JPEG"))
{
ext=".jpeg";
}
if(extension.equals("*.bmp,*.BMP"))
{
ext=".bmp";
}
File fileToSave = FC.getSelectedFile();
try{
ImageIO.write(img, ext ,fileToSave);
}
catch (IOException e) {
e.printStackTrace();
}
catch(Exception ex)
{
System.out.println(ex.getMessage());
return false;
}
return true;
}
return false;
}
Thanks for help!

The problem is your specifying the file format as the ext
Effectively your saying
ImageIO.write(img, ".jpg" ,fileToSave)
You need to supply it so it evaluates to
ImageIO.write(img, "jpg" ,fileToSave)

Extensions in ImageIO.write should be like "PNG", "JPG". without the point.
And the if (extension.equals("...")) approach is very bad. Make sure you actually provided an extension. IE: at least one of the if's succeeded. Try to print the ext just before writing, to check if it has a correct value.
System.out.println("Extension: " + ext);
Oh, and javax.imageio only supports PNG, JPG, JPEG (and GIF read-only). To get dynamically a list of supported formats, use:
ImageIO.getWriterFormatNames();

mistake may be here: JFileChooser FC=new JFileChooser("C:/");
change the file path to "C:\" (or double backslash)

Related

How can I output a random image when in a jar file?

The below code works when running from my editor but the image fails to load when compiled into a runnable jar file with eclipse.
public static BufferedImage getRandomImage() {
// returns a random image from the Images folder
Random rand = new Random();
URL res = Card.class.getResource("Images"); // located in /src/.../Images
File f = new File(res.getFile());
if (!f.exists()) {
return new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB);
}
File[] files = f.listFiles();
int random = rand.nextInt(files.length);
BufferedImage img = null;
try {
img = ImageIO.read(files[random]);
} catch (IOException e) {
e.printStackTrace();
}
return img;
}
Could someone please suggest how I can modify my code or editor to load the files when compiled.
I have read other methods of accessing files but since I need to select randomly from a folder, I need to use the File class.
There is no safe way to list resources at runtime.
(Some people may suggest approaches which work sometimes, but will not work all the time. Class.getResource is not guaranteed to provide a listing; ProtectionDomain.getCodeSource can return null.)
But you don’t need to. It’s your application; you already know what files you put into it.
The best way is to either hard-code the list of files, or include a simple text file that contains a list of the files.
As an example, assume you created (or generated) a file named image-files.txt in which each line contains the base name of an image file, and embedded that file in your application:
List<String> imageNames;
try (BufferedReader linesReader = new BufferedReader(
new InputStreamReader(
Card.class.getResourceAsStream("image-files.txt"),
StandardCharsets.UTF_8));
Stream<String> lines = linesReader.lines()) {
imageNames = lines.collect(Collectors.toList());
} catch (IOException e) {
throw new UncheckedIOException(e);
}
int random = rand.nextInt(imageNames.length());
String imageName = imageNames.get(random)));
BufferedImage img;
try {
img = ImageIO.read(Card.class.getResource(imageName));
} catch (IOException e) {
throw new UncheckedIOException(e);
}
return img;
Note: The getFile() method of URL does not return a valid filename. It only returns the path portion of a URL. There are many characters which would be illegal in URLs, so the path portion percent-escapes them. If you ignore this fact, the value returned by getFile() will eventually fail.
(The reason for the misleading method name is that the URL class was part of Java 1.0, and in the mid-1990s, all URLs actually referred to physical files.)
I need to use the File class
Each .jar entry is just a subsequence of compressed bytes within a single .jar file, so you will never be able to use File to read such an entry. Class.getResource and Class.getResourceAsStream are the only correct ways to read those entries.
The problem is that you are trying to access a URL of a resource as a file.
with this you can get all the images, and then you can do this:
List<String> arr = getResourceFiles("Images");
String imgPath = arr.get(rand.nextInt(arr.size()));
InputStream stream = Card.class.getResourceAsStream("Images/" + imgPath);
try {
img = ImageIO.read(stream);
} catch (IOException e) {
e.printStackTrace();
}
return img;

How to set a standard image to show if a search for associated image name yields no results?

I am working on a project for my course and have been asked to show an associated image for products in a system, the user can add products, and he enters the name of the image file whilst doing so. the program then finds the image file and displays it with the product information.
I would like to add some additional code so that if there is no image file matching the string input that a standard image is shown. The code I have so far either shows the image file if it is found or does not show anything. can someone show me how to modify it so that it can show a standard image if no associated image file is found. the standard image is simply "no-image-found.jpg". Here is the code:
public void showImage(JLabel imageArea, String image){
BufferedImage img = null;
try {
img = (BufferedImage)ImageIO.read(new File(image));
Image actualimage = img.getScaledInstance(imageArea.getWidth(), imageArea.getHeight(), 0);
imageArea.setIcon(new ImageIcon(actualimage));
}
catch (IOException e) {
System.out.println(e.getMessage());
}
}
any help is very much appreciated, and my sincere apologies if this is a noob question, I am quite new to java.
In the catch, you could load the standard image and show it
Basically check for image existence assuming path is valid otherwise get the standard image. You can have something similar:
public void showImage(JLabel imageArea, String image)
{
BufferedImage img = null;
try
{
file = new File(image);
if (file.exists())
{
img = ImageIO.read(file);
}
else
{
file = new File(standardImagePath);
img = ImageIO.read(file);
}
Image actualimage = img.getScaledInstance(imageArea.getWidth(), imageArea.getHeight(), 0);
imageArea.setIcon(new ImageIcon(actualimage));
}
catch (IOException e)
{
System.out.println(e.getMessage());
}

converting .webp to .jpeg using Java

i want to convert a .webp image to .jpeg. I have used javax.imageio.ImageIO.
but # line no: 19 bImage = ImageIO.read(fis); returns a null for webp images.
Code is working fine if I try to convert .png ,.gif file format..
can any one help?
public static void imageIoWrite() {
BufferedImage bImage = null;
try {
File initialImage = new File("resources/1.webp");
FileInputStream fis = new FileInputStream(initialImage);
bImage = ImageIO.read(fis); //why it returns null?
if (bImage != null) {
ImageIO.write(bImage, "jpg",
new File("resources/NewImage1.jpg"));
System.out.println("Image file written successfully");
} else {
System.out.println("imag is empty");
}
} catch (IOException e) {
System.out.println("Exception occured :" + e.getMessage());
}
}
It seems that ImageIO is not able to read webp images. As you can read in the docs, the method read returns null in this case. I think that you have to use an additional library to read and write webp images.

Load images in jar file

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);

check if the file is of a certain type

I want to validate if all the files in a directory are of a certain type. What I did so far is.
private static final String[] IMAGE_EXTS = { "jpg", "jpeg" };
private void validateFolderPath(String folderPath, final String[] ext) {
File dir = new File(folderPath);
int totalFiles = dir.listFiles().length;
// Filter the files with JPEG or JPG extensions.
File[] matchingFiles = dir.listFiles(new FileFilter() {
public boolean accept(File pathname) {
return pathname.getName().endsWith(ext[0])
|| pathname.getName().endsWith(ext[1]);
}
});
// Check if all the files have JPEG or JPG extensions
// Terminate if validation fails.
if (matchingFiles.length != totalFiles) {
System.out.println("All the tiles should be of type " + ext[0]
+ " or " + ext[1]);
System.exit(0);
} else {
return;
}
}
This works fine if the file name have an extension like {file.jpeg, file.jpg}
This fails if the files have no extensions {file1 file2}.
When I do the following in my terminal I get:
$ file folder/file1
folder/file1: JPEG image data, JFIF standard 1.01
Update 1:
I tried to get the magic numbers of the file to check if it is JPEG:
for (int i = 0; i < totalFiles; i++) {
DataInputStream input = new DataInputStream(
new BufferedInputStream(new FileInputStream(
dir.listFiles()[i])));
if (input.readInt() == 0xffd8ffe0) {
isJPEGFlag = true;
} else {
isJPEGFlag = false;
try {
input.close();
} catch (IOException ignore) {
}
System.out.println("File not JPEG");
System.exit(0);
}
}
I ran into another problem. There are some .DS_Store files in my folder.
Any idea how to ignore them ?
Firstly, file extensions are not mandatory, a file without extension could very well be a valid JPEG file.
Check the RFC for JPEG format, the file formats generally start with some fixed sequence of bytes to identify the format of the file. This is definitely not straight forward, but I am not sure if there is a better way.
In a nutshell you have to open each file, read first n bytes depending on file format, check if they match to file format you expect. If they do, its a valid JPEG file even if it has an exe extension or even if it does not have any extension.
For JPEGs you can do the magic number check in header of the file:
static bool HasJpegHeader(string filename)
{
using (BinaryReader br = new BinaryReader(File.Open(filename, FileMode.Open)))
{
UInt16 soi = br.ReadUInt16();
UInt16 jfif = br.ReadUInt16();
return soi == 0xd8ff && jfif == 0xe0ff;
}
}
More complete method here which covers EXIFF as well: C# How can I test a file is a jpeg?
One good (though expensive) check for validity as an image understood by J2SE is to try to ImageIO.read(File) it. That methods throws some quite helpful exceptions if it does not find an image in the file provided.

Categories

Resources