Writing multiple images to one file using ImageIO

I am having trouble saving and reading multiple images from to/from one file. Here is the best i can come up with:
//this is utilizing an ObjectOutputStream because i need to also save some objects to the file
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("C:\\images.dat"));
oos.writeInt(ImageTable.size());
for(int k = 0; k  < ImageTable.size(); k++)
    ImageIO.write((BufferedImage)ImageTable.get(k), "png", oos);
    oos.flush();
//////////////////////////read function/////////////////////////
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("C:\\images.dat"));
int size = ois.readInt();
for(int k = 0; k < size; k++)
    ImageTable.add(ImageIO.read(ois));
}What it seems to do is read the first image and then place the marker at the end of the file so each consecutive calls to reading the file end up in either null, -1, or an EOF exception (bleh). Does anyone know how i can do this properly?
The code does run and saves something, although it is hard to tell exactly what it is saving since it is all in png format, it also loads the first image properly.

Is it possible to pack the different images in one big image?Conversely, some image formats let you store multiple images in a single image file.
Here's a demo. My results are that I don't have a gif writer, tiff can write sequences (this
is a well-known tiff property), I can trick (?) jpeg into stroring multiple images and I
can't get png to work: three images go in, one comes out.
import java.awt.*;
import java.awt.image.*;
import java.io.*;
import java.net.*;
import java.util.*;
import javax.imageio.*;
import javax.swing.*;
import java.util.List;
public class MultiImageTest {
    public static void main(String[] args) throws IOException {
        URL url1 = new URL("http://today.java.net/jag/bio/JagHeadshot-small.jpg");
        URL url2 = new URL("http://today.java.net/jag/bio/JAG2001small.jpg");
        URL url3 = new URL("http://today.java.net/jag/Image24-small.jpeg");
        BufferedImage[] images = {ImageIO.read(url1), ImageIO.read(url2), ImageIO.read(url3)};
        display(images, "original", 0, 0);
        String[] suffixes = {"gif", "jpeg", "png", "tiff"};
        int x = 30, y = 20;
        for(int j=0; j<suffixes.length; ++j) {
            String suffix = suffixes[j];
            try {
                writeFile(images, suffix);
                display(readFile(suffix), suffix, x, y);
                x += 30;
                y += 20;
            } catch (Exception e) {
                System.err.println(suffix + ": " + e.getMessage());
    static void writeFile(BufferedImage[] images, String suffix) throws IOException {
        Iterator ws = ImageIO.getImageWritersBySuffix(suffix);
        if (!ws.hasNext())
            throw new IOException("no writer for: " + suffix);
        ImageWriter w = (ImageWriter) ws.next();
        File file = new File("temp." + suffix);
        file.delete();
        w.setOutput(ImageIO.createImageOutputStream(file));
        if (w.canWriteSequence()) {
            System.out.println("Using writeToSequence for format " + suffix);
            w.prepareWriteSequence(null);
            for(int j=0; j<images.length; ++j)
                w.writeToSequence(new IIOImage(images[j], null, null), null);
            w.endWriteSequence();
        } else {
            System.out.println("cross fingers for format " + suffix);
            for(int j=0; j<images.length; ++j)
                w.write(images[j]);
    static BufferedImage[] readFile(String suffix) throws IOException {
        Iterator rs = ImageIO.getImageReadersBySuffix(suffix);
        if (!rs.hasNext())
            throw new IOException("no reader for: " + suffix);
        ImageReader r = (ImageReader) rs.next();
        File file = new File("temp." + suffix);
        if (!file.exists())
            throw new IOException("no file: " + file.getName());
        r.setInput(ImageIO.createImageInputStream(file));
        List images = new ArrayList();
        for(int j=0; true; ++j) {
            try {
                images.add(r.read(j));
            } catch (IndexOutOfBoundsException e) {
                break;
        return (BufferedImage[]) images.toArray(new BufferedImage[images.size()]);
    static void display(BufferedImage[] images, String title, int x, int y) {
        JPanel cp = new JPanel(new GridLayout(1,0));
        for(int j=0; j<images.length; ++j)
            cp.add(new JLabel(new ImageIcon(images[j])));
        JFrame f = new JFrame(title);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.getContentPane().add(new JScrollPane(cp));
        f.pack();
        f.setLocation(x, y);
        f.setVisible(true);

Similar Messages

  • How do I add multiple images into one file?

    I'm sure this is something that's been covered in another post (or even in the help portal) but I think my wording in my search terms are not correct or... I don't know, because I just can't find what I'm looking for.
    I want to know how to add multiple images into one file/one image, both horizontally and/or vertically. To give you an idea of what I mean, check out :
    http://www.best10apps.com/apps/comic-story,531596060.html
    If you scroll down, you'll see a heading entitled : Screenshots of Comic Story. Notice how there's 3 pictures (divided by borders). 2 of those pictures are side by side, and 1 of them is below the first 2 pictures.
    I want to know how to add different pictures/images and put them into one picture.

    One way is to create template PSD files and populate them with your images using Photoshops scripts.
    Photo Collage Toolkit UPDATED June 12, added Picture Package Support via PasteImageRoll and BatchPicturePackage scripts.
    The package includes four simple rules to follow when making Photo Collage Template PSD files so they will be compatible with my Photoshop scripts.
    There are eleven scripts in this package they provide the following functions:
    TestCollageTemplate.jsx - Used to test a Photo Collage Template while you are making it with Photoshop.
    CollageTemplateBuilder.jsx - Can build Templates compatible with this toolkit's scripts.
    LayerToAlphaChan.jsx - Used to convert a Prototype Image Layer stack into a template document.
    InteractivePopulateCollage.jsx - Used to interactively populate Any Photo Collage template. Offers most user control inserting pictures and text.
    ReplaceCollageImage.jsx - use to replace a populated collage image Smart Object layer with an other image correctly resized and positioned.
    ChangeTextSize.jsx - This script can be used to change Image stamps text size when the size used by the populating did not work well.
    PopulateCollageTemplate.jsx - Used to Automatically populate a Photo Collage template and leave the populated copy open in Photoshop.
    BatchOneImageCollage.jsx - Used to Automatically Batch Populate Collage templates that only have one image inserted. The Collage or Image may be stamped with text.
    BatchMultiImageCollage.jsx - Used to Automatically Batch Populate Any Photo Collage template with images in a source image folder. Easier to use than the interactive script. Saved collages can be tweaked.
    BatchPicturePackage.jsx - Used to Automatically Batch Populate Any Photo Collage template with an image in a source image folder
    PasteImageRoll.jsx - Paste Images into a document to be print on roll paper.
    Documentation and Examples

  • Scanning multiple pages into one file using MAC

    How do I scan multiple pages and save them into one file or document using a MacBook Pro laptop?  My printer is an HP Photosmart 7520.  When I use this printer and scan from my PC, it does allow me to scan multiple copies and save as one document by just adding pages as I scan.  When I scan with my MacBook Pro, it scans each page, however, I don't get any option or choice to save as one document.  It automatically saves each page as a separate document.

    Try scanning from your Mac. Use Image Capture app in your Applications folder.
    Click once on the scanner on the left side, then click on Show Details along the bottom. Along the right side you will see LOTS of options for scanning and saving.
    One of those is Format, make the Format PDF.  Just below that will be a check box allowing you to scan multiple pages to one file.
    Say thanks by clicking "Kudos" "thumbs up" in the post that helped you.
    I am employed by HP

  • Scanning multiple pages to one file

    I have a C310a All in One printer/scanner.  My computer uses OS X 10.9 and all the drivers are updated.  Is there a way to scan multiple pages to one file.  I have tried the three methods mentioned in the HP bulletin for Mavericks but I can only scan one page to one file extension.

    Welcome to the forums @BPGeneva ,
    I understand you are looking to do a multiple page scan and save it as one file. I will do my best to help! The full driver for the C310a is not available with Mavericks. In having said that,  you can try using Image Capture to scan multi-page documents.
    Click this link and have a look at PrintDoc's suggestion: Re: Scanning multiple pages into one file using MAC
    I hope that helps
    R a i n b o w 7000I work on behalf of HP
    Click the “Kudos Thumbs Up" at the bottom of this post to say
    “Thanks” for helping!
    Click “Accept as Solution” if you feel my post solved your issue, it will help others find the solution!

  • How can I scan multiple pages to one file with MG 7120

    My printer does not have ADF. How can I scan multiple pages to one file on my MG 7120?

    Hi albabynyr,
    There is a program that comes with the printer called the IJ Scan Utility that can assist you with scanning multiple pages into a single file.  To scan using the IJ Scan Utility, please follow these steps:
    1. Start IJ Scan Utility by going to your Start menu, then selecting All Programs, then Canon Utilities, then  IJ Scan Utility (folder), then IJ Scan Utility (program).
    2. In the Canon IJ Scan Utility window that opens, click SETTINGS.... in the bottom right of the window. The Settings dialog box appears.
    3. Click the DOCUMENT SCAN option on the left pane of the window.
    4. In the right pane of the window, locate the SELECT SOURCE field and select the DOCUMENT option.
    5. Set the color mode, document size, and scanning resolution as required in the rest of the fields shown in the window. Click DOCUMENT SCAN ORIENTATION SETTINGS... to specify the orientation of the documents to be scanned.
    6. In the SAVE SETTINGS section of the window, you will select the save format and location of the document you are about to scan.
    a.) In the FILE NAME field, specify the name you would like to give the file. By default the filename will begin with IMG; you can remove IMG and change it to whatever you would like to name the file.
    b.) In the DATA FORMAT field, use the drop-down arrow to select the PDF (Multiple Pages) option.
    c.) In the SAVE IN field, please navigate to the area where you would like the file to be saved once it is scanned in. By default, the file will be saved in the DOCUMENTS folder.
    7. Once all settings have been selected, click the OK button at the bottom of the SETTINGS (DOCUMENT SCAN) window. The IJ Scan Utility main screen appears.
    8. Click the DOCUMENT button. Scanning starts. After a page has scanned, the screen to continue or end scanning appears. If you have more pages to scan, place the next page on the platen and click Scan.  Do this each time a page has completed scanning.  After the last page has been scanned, click Exit. Scanned images are saved in previously selected folder location specified in the SETTINGS... window. Click the CANCEL button to cancel scanning if needed during scanning.
    Hope this helps!
    This didn't answer your question or issue? Please call or email us at one of the methods on the Contact Us page for further assistance.
    Did this answer your question? Please click the Accept as Solution button so that others may find the answer as well.

  • How to scan multiple pages in one file

    I would like to know how to scan multiple pages into one file.  There is no add button that comes up.  I have a HP Officejet 8600 and a macbook pro.  Please help, this would really help me out.

    Open Preview and use its "Import From Scanner" option in the File menu. This will launch the scanning interface, which has some standard and basic scanning controls. If you choose "PDF" as the file format to save as, then you will see an option to scan all images to one file. When you do this, you will scan and edit them individually, but Preview will save them to the same file when saved.

  • Multiple databases in one file: a small snafu

    Hello everyone,
    Opening multiple databases in a single file is an administrative convenience. It is well explained in the manual (see db/docs/ref/am/opensub.html). Normally, there is little difference between databases in their own physical files or grouped together in a single physical file. There is one small sentence in the manual that says the following:
    (begin fragment)
    However, since multiple databases in a file exist in a single physical file, opening two databases in the same file simultaneously requires locking be enabled unless all of the handles are read-only. As the locks for the two databases can only conflict during page allocation, this additional locking is unlikely to affect performance.
    (end fragment).
    I didn't pay attention to it, except the "unlikely to affect performance" part which told me that I wasn't to worry about it. The sun was shining. Life was good.
    And I was wrong. It was one of those "epic bug quests" I had to embark on, only to realise that it may not be a BDB bug, but my carelessnes. Nevertheless, I'm left with an uneasy feeling which I would like to explain here.
    Consider BDB configured as a concurrent data store.
    There are 2 threads. The first thread has the following pseudocode:
    cursor1 = db1->cursor(...)
    while(cursor1->c_get(... DB_NEXT...))
    // 1
    cursor2 = db2->cursor(...)
    while(cursor2->c_get(... DB_NEXT...))
    The second thread does only the following:
    db3->put(...)
    db1, db2 and db3 are all distinct databases. All cursors are read-only (the cursor implicitly used in db3->put is of course a write cursor).
    While the first thread is running, the second thread executes db3->put(...) at "//1".
    Question: what happens?
    Answer 1: if db1, db2 and db3 reside in different physical files, nothing special happens. Everything proceeds as it should.
    Answer 2: if db1, db2 and db3 reside in the same physical file, both threads block "sometimes".
    The "sometimes" used here means "when the put operation in thread 2 needs to allocate a new page".
    Reading the BDB source code is extraordinarily difficult (which says more about my limitations than about the clarity of the code) but here is what happens, as far as I could determine:
    (thread 1) cursor1 needs and acquires a read lock on db1
    (thread 2) db3->put needs a write lock on db2 to allocate a new page. Since db2 is in the same physical file as db1 and thread 1 already has a read lock, thread 2 waits until the read lock is released. Thread 2 blocks.
    (thread 1) cursor 2 needs a read lock on db3. For some reason, BDB detects that the another thread is waiting for a write lock on the physical file, and thread 1 blocks.
    Both threads block waiting on each other to complete.
    I suppose the system is the way it is to avoid starvation, but there you have it: be careful when you're lumping together multiple databases in one file!
    Anyone who can clarify or confirm this is welcome.
    Vincent

    I had experienced a similar problem. I run multiple process. Each one of them starts a transaction that does db->put and db->pget to its own database (which also has a secondary index). When each database is in a separate physical file there is no problem but when I put all databases in a single file the processes start to dead-lock.
    The following combination of options solved the deadlocking problem:
    - use serializable isolation level instead of snapshot, i.e. do not pass DB_TXN_SNAPSHOT to txn_begin
    - do not pass the DB_NO_WAIT option to txn_begin
    - use Btree instead of a Hash
    Hope that helps.

  • Scaning multiple pages into one file on a 4630

    Using HP 4630 printer, windows 8.1, wireless connection.
    Want to scan multiple pages into one file.
    Per user manual, I work from the computer not the printer.
    When first page is scanned am asked if I want to save, I click yes and name file.
    When I scan second page am again asked if I want to save, my file name appears, I am told it already exists and asks if I want  to keep or replace it.
    Whichever one I click, only the second page is saved.
    What am I doing wrong?
    Question: How do I scan mutiple pages into a single document?
    This question was solved.
    View Solution.

    I accept this solution with many thanks!  It was so obvious and I didn't see it.  The User Manual should mention this.

  • How do I scan multiple pages into one document using the CanoScan LiDE 200?

    How do I scan multiple pages into one document using the CanoScan LiDE 200?
    I can't seem to find a way to get them to scan continuously, or a way to stitch them together afterwards.

    Hi dagda24,
    You can scan multiple pages into a single document with the scan to PDF option.  Use the following steps to do so:
    1.  Open MP Navigator.
    2.  Click One Clcik.
    3.  Click Save to PC.
    4.  Change the File Type from PDF to PDF (multiple pages).
    5.  Make any other changes as needed, then click scan.
    Did this answer your question? Please click the Accept as Solution button so that others may find the answer as well.

  • Reading Multiple lines in a file Using File Adapter

    Hi All,
    Iam new to this technology.How to read multiple lines in a file using file adapter.Brief me with the methodology.

    I didn't look at anything else but if you want to write more than one line ever to your file you should change this
    out = new FileOutputStream("Calculation.log");to this...
    out = new FileOutputStream("Calculation.log",true);A quick look at the API reveals the follow constructor FileOutputStream(File file, boolean append) append means should I add on the end of the file or over-write what is there.
    By default you over-write. So in our case we say true instead which says add on to what is there.
    At the end of that little snippet you shoudl be closing that stream as well.
    So where you have
    p.close();You should have
    p.close();
    out.close();

  • Copying a part of image from one file to another

    I am very new to InDesign, 2days old. I have to copy a small part of an image from one file and to paste on the other file. Is it possible? If yes, can you anybody explain me step by step?

    Welcome to the forum.
    Briefly, I would open the image in Photoshop. Crop the area you want. Size it to the finished size at (for printing) 300ppi, save it in the folder where you are going to save your InDesign document. Create a new InDesign document, choose Print for the intent, select the page size, margins, etc. save and name your document. You can place (command/control D) your image. Resizing it and positioning it to suit.
    By using a PSD file you can easily round trip back to Photoshop to make more changes.
    You should get some lessons, such as those on Lynda.com and Trainsimple.com and there are some excellent books available as well - Classroom in a Book and Visual Quickstart Guide.
    Derek

  • How do I save multiple songs as one file?

    How do I save multiple songs as one file?

    Mhoopes wrote:
    How do I save multiple songs as one file?
    There are two ways:
    1.  Put the individual song files into a folder, and then Zip the folder.  This creates a single .zip file.  (Note however, that a .zip file is not playable in a normal player: it is just a "holder" for the song files.)
    2.  Use an audio editor such as Audacity to concatenate the individual song files into a single song file.  This creates a single file can be played in a normal player such as iTunes.
    Technique #2 is the one normally used to create a continuous mix.

  • Problems with multiple idocs in one file ( Inbound file )

    HI,
    Thanks in Advance for your suggestions.. Highly appreciated.
    We have problems with multiple IDocs in one file.
    We are using XIB ( Amtrix ) as Middleware to receive the files.
    Curretenly When the file contains one IDoc then there is no problem. IDoc is created and everything is ok.
    If file contains two IDocs ( for example two messages ORDERS and DELVERY ) then it is creating two IDocs but both IDocs contains ORDERS plus DELIVERY segements information. That is the problem. Some how SAP unable to differentiate the IDocs in the file.. But it knows that how many idocs are there in the file..because it is creating exact number of idocs.
    We are using TRFC port ... Do I need to change it to File port..
    When we have more than one idoc do we need set any parameter in the file ...

    Thanks for the swift response. Always ideas are useful.
    As of now , Middleware cannot split the file.
    Thing is SAP is creating two Idocs with different message types. Problem is First IDoc contains ORDERS message type but also DELIVERY segments as well. Second IDoc with DELIVERY message tyoe but ORDERS segments as well... This is the problem... I think we are missing some field activation in file for EDIDC record.
    As far as I know file port supports the number of IDocs in one file.. Hope TRFC port also supports that

  • Multiple classes in one file bad?

    Hello.
    I've been coding a load of elements recently, one of which is HUD elements for a game. I separated each element (joystick, fuel gauge etc) into a separate class but in one file, by that I mean more than one implementation in a file. Is this bad practise? Should I use one class and simply write methods that return an element, or is it ok to split them up?
    To me, in my head ,it makes more sense to split the up. I just wonder if this is bad practise?

    I did some reading and decided not to use multiple classes in one file, and instead use methods.

  • Insert multiple images in one slide and setting dsiplay time for each

    Hi,
    I am using Adobe Captivate4.
    I could not able to insert multiple images in one slide and set display time for each image.
    Need help in this regard.

    This is not about background image.
    I have 3 images and want to insert in one slide only. I could able to insert image1 for first time, but could not able to insert image2 and image3.
    I have followed the same steps: Insert Menu>Image.

Maybe you are looking for