hello,
Iv been trying to write a java program to read an image from a list of images in a file I.E:

  • File
  • Filename
  • Image1
  • Filename
  • Image2
  • Filename
  • Image3

The problem i am having is that the filename's are string objects followed by an image. So i was wondering if anyone could point me in the right direction to read the file i have written.

public class imageloader {
    String name;
    BufferedImage image;

    public imageloader(String url) 
    {
        try {

            FileInputStream saveFile = new FileInputStream(url);


            try {

                ObjectInputStream restore = new ObjectInputStream(saveFile);
                this.name = (String) restore.readObject();
                this.image = ImageIO.read(restore);

                System.out.println(this.name);

            } catch (IOException e) {

                e.printStackTrace();
            } catch (ClassNotFoundException e) {

                e.printStackTrace();
            }



        } catch (FileNotFoundException e) {

            e.printStackTrace();
        }


    }

}

This is how i am how i am saving the file

try{  
            FileOutputStream saveFile=new FileOutputStream("testfile");
            ObjectOutputStream save = new ObjectOutputStream(saveFile);
            // Now we do the save.
            save.writeObject(this.name);
            ImageIO.write(image, "png", saveFile);
            // Close the file.
            save.close(); // This also closes saveFile.
            }

Currently it throws no errors, but does not seem to actually read the data back into the buffered image. Any Ideas?

You can't mix object I/O and imageIO in a single file like that. ImageIO writes a single image in the desired format (jpg, png etc). The API doc also says " If there is already a File present, its contents are discarded.", so it's stricly one image per file. ObjectStreams support multiple objects in one file, but they have their own special format to do that. Unfortunately BufferedImages are not Serialisable, so you can't write then to an Object stream.
One possible solution is to convert you Image objects to ImageIcon (and v.v after reading them). ImageIcons can be written to /read from Object streams with writeObject and readObject, and you can have as many as you want, mixed with any other objects, in a single file.

Edited 3 Years Ago by JamesCherrill

thanks, thats what i thought when i tried it originally and found it not to be serializeable. Quite annoying but ill try the image icon thing thanks!

I have done something like what you want, I reading image file then converting them in binary format for storing them in MySQL. Then next part is reading those image from Mysql database and reformat those binary data in imgae format back. I use image icon. you can check this http://cbsecsnip.in tutorial section. May this help you

Edited 3 Years Ago by vishalonne

This question has already been answered. Start a new discussion instead.