Problem saving and loading multiple images in the same file

Hello

I am having a problem, I have a thah program creates a fileOutputSteam and a gzipOutputSteam and finally an imageIO wrote several images, then I do the reverse process, a
FileInputsteam and an inputsteam of gzip, imageIO.read read only image of frist, not the rest.

Can someone help me?
PS: Sorry for my bad English, I'm Spanish

Code:
class Lector {

    // Atributos
    private String ruta;
    private static Collection<Imagen> imagenes;

    /**
     * Clase que carga un fichero .zip lleno de imagenes
     * @param ruta: ruta donde se halla el fichero .zip a cargar
     */
    public Lector(String ruta) {
    }
    /**
     * Constructor sin parametros
     */
    public Lector() {
    }
    /**
     * Metodo que setea el archivo que queremos cargar
     * @param ruta: Ruta del fichero a cargar
     */
    public void setArchivo(String ruta) {
        this.ruta = ruta;
        imagenes = new ArrayList<Imagen>();
    }

    /**
     *
     * @param output: Lugar donde sera representada la salida de la carga de imagenes
     * @return retorna 1 si la carga fue bien y 0 si fue mal
     * @throws FileNotFoundException : excepcion por  no haber encontrado el fichero
     * @throws IOException: excepcion por no poder leer el fichero
     */
    public int cargarImagenes(JTextArea output) throws FileNotFoundException, IOException {
        ZipEntry entrada;
        int contador = 0;
        String archTemp = "temp.jpg";
        FileInputStream fis = new FileInputStream(ruta);
        ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));
        BufferedOutputStream dest = null;
        byte[] data = new byte[9000];

        // Leemos secuencialmente el archivo zip
        while ((entrada = zis.getNextEntry()) != null) {
            File bufferTemporal = new File(archTemp);
            System.out.println("Archivo " + entrada.getName() + " cargado!");
            output.append("Archivo " + entrada.getName() + " cargado!\n");
            if (!entrada.isDirectory()) {
                FileOutputStream fos = new FileOutputStream(bufferTemporal);
                dest = new BufferedOutputStream(fos, 9000);

                while ((contador = zis.read(data, 0, 9000)) != -1) {
                    dest.write(data, 0, contador);
                }
                   //Cerramos los buffers
                dest.flush();
                dest.close();
                fos.flush();
                fos.close();

                FileInputStream fin = new FileInputStream(bufferTemporal);
                BufferedImage bi = ImageIO.read(fin);
                //Guardamos el fichero
                imagenes.add(new Imagen(bi, entrada.getName()));
            }
           bufferTemporal.delete();
        }
 
        // Cerramos los bufferes

        fis.close();
        zis.close();

       

        saveAsGzip("dato.gz");
        loadAsGzip("dato.gz");
        return 1;
    }
    /**
     * Funcion que carga la simagenes de dentro del .zip y las guarda en el objeto Imagen
     * @return retorna 1 si la carga fue exitosa
     * @throws FileNotFoundException: Excepcion por no encontrar el archivo
     * @throws IOException: Excepcion por no poder leer el archivo
     */
    public int cargarImagenes() throws FileNotFoundException, IOException {
        ZipEntry entrada;
        int contador = 0;
        String archTemp = "temp.jpg";
        FileInputStream fis = new FileInputStream(ruta);
        ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));
        BufferedOutputStream dest = null;
        byte[] data = new byte[9000];

        // Leemos secuencialmente el archivo zip
        while ((entrada = zis.getNextEntry()) != null) {
            File bufferTemporal = new File(archTemp);
            System.out.println("Archivo " + entrada.getName() + " cargado!");

            if (!entrada.isDirectory()) {
                FileOutputStream fos = new FileOutputStream(bufferTemporal);
                dest = new BufferedOutputStream(fos, 9000);

                while ((contador = zis.read(data, 0, 9000)) != -1) {
                    dest.write(data, 0, contador);
                }

                dest.flush();
                dest.close();
                fos.flush();
                fos.close();
                java.io.FileInputStream fin = new FileInputStream(bufferTemporal);
                BufferedImage bi = ImageIO.read(fin);

                imagenes.add(new Imagen(bi, entrada.getName()));
            }
           
        }

        // Cerramos los bufferes
        fis.close();
        zis.close();

        dest.flush();
        dest.close();

        
        return 1;
    }
    /**
     * Funcion que retorna el array de peliculas
     * @return retorna el array de peliculas
     */
    public Collection<Imagen> getImagenes() {
        return imagenes;
    }
    public int saveAsGzip(String pathFichero) throws FileNotFoundException, IOException{

        FileOutputStream fos = new FileOutputStream(new File(pathFichero));
     //GZIPOutputStream gzip = new GZIPOutputStream(fos);
        BufferedImage temp2;
        Imagen img;

        Iterator ite = imagenes.iterator();
        while(ite.hasNext()){
            img = (Imagen) ite.next();
            temp2=img.getBufferedImagen();
            
            boolean i= ImageIO.write(temp2, "JPEG", fos);
            System.out.println(i);

        }
        System.out.println();

        //gzip.finish();
        fos.flush();
         
        fos.close();
       
        //gzip.close();

        return 1;
    }
    public int loadAsGzip(String pathFichero) throws FileNotFoundException, IOException{

        imagenes.clear();
        
        FileInputStream fos = new FileInputStream(new File(pathFichero));
     //GZIPInputStream gzip = new GZIPInputStream(fos);
        BufferedImage img;


            for(int i=0;i<=100; i++){
                

             
                img=ImageIO.read(fos);

                
                if (img != null){System.out.println(img);
                imagenes.add(new Imagen(img, String.valueOf(i)));}
                   
                


        
            }




       // gzip.close();
        fos.close();

        return 1;
    }
}
Published by: sabre150 on October 28, 2010 01:43

Moderator action: added
 tags to source.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        

805814 wrote:
Oh, sorry again, Ii have commented on all of the code not clear in my best English and posted the image of class:

(sigh) OK, it's an improvement, but it is not yet an NBS! I think it would take me less time to write code that is a NBS that try to explain more (perhaps an example is better here?). In all cases, your code still seems to be mixing the two Zip and GZip. I've never dealt with GZip and could not be disturbed from now just for this problem, so I focused on using the Zip classes.

Try this code:

import java.awt.*;
import java.awt.image.*;
import javax.swing.*;
import javax.imageio.*;
import java.util.*;
import java.util.zip.*;
import java.io.*;

/** SSCCE that demonstrates how to:
1) Create some random images.
2) Store them to a Zip File.
3) Restore them from a Zip File
Please study the code carefully, and note how in a single Java source of less
than 100 lines of code, it manages to achieve the entire demo.!
@author Andrew Thompson */
class StoreImagesAsZip {

    static Random random;
    static int size = 60;

    public static BufferedImage getRandomImage() {
        BufferedImage bi = new BufferedImage(size,size,BufferedImage.TYPE_INT_RGB);

        Graphics2D g = bi.createGraphics();
        GradientPaint gp = new GradientPaint(
            (float)random.nextInt(size),
            (float)random.nextInt(size),
            new Color(random.nextInt(255),random.nextInt(255),random.nextInt(255) ),
            (float)random.nextInt(size),
            (float)random.nextInt(size),
            new Color(random.nextInt(255),random.nextInt(255),random.nextInt(255) )
            );
        g.setPaint(gp);
        g.fillRect(0,0,size,size);

        return bi;
    }

    static public void writeImagesToZip(File file, BufferedImage[] images) throws Exception {
        OutputStream os = new FileOutputStream(file);
        ZipOutputStream zos = new ZipOutputStream(os);
        // Zip does nothing for otherwise compressed media formats such as JPEG and PNG
        zos.setLevel( ZipOutputStream.STORED );

        for (int ii=0; ii< images.length; ii++) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(images[ii], "png", baos);

            ZipEntry ze = new ZipEntry( ii + ".png" );
            zos.putNextEntry( ze );
            zos.write( baos.toByteArray() );
            zos.closeEntry();
        }
        zos.flush();
        zos.close();
    }

    static public BufferedImage[] readImagesFromZip(File file) throws Exception {
        ArrayList images = new ArrayList();

        ZipFile zipFile = new ZipFile(file);
        Enumeration en = zipFile.entries();
        while (en.hasMoreElements()) {
            ZipEntry ze = (ZipEntry)en.nextElement();
            InputStream is = zipFile.getInputStream(ze);
            BufferedImage bi = ImageIO.read(is);
            images.add(bi);
        }

        BufferedImage[] imageArray = new BufferedImage[images.size()];
        for (int ii=0; ii

Also note that I now invested a lot of time trying to help you. If you like what I've done, the best way to show that is on the occasion of my responses as "Helpful" or "correct". If the problem is "answered", make sure that mark also.

Tags: Java

Similar Questions

  • Multiple images with the same file name no doubt prevent export

    iMac running OS X El Capitan v10.11.6; Photos 1.5

    I'm trying to export approximately 331 images and I get an error report saying that only 169 of the exported images due to the inability to create files for 159 of the images.  Then the report gives me the names of files of the first 100 images for which files were not created.  After looking at many images that would not create a file, I realized that, in any case, there was at least one, if not several, other images with the SAME EXACT FILE name as the image in question.  I can't change the names of files by right click on "info".  I tried to export the images and change the names of files to export using the sequential option and the option of album name - always having exactly the same problem.  I even tried not to export an image at once and change the name of the file individually or no available. Is there a work around that? I desperately need to export those specific images. I am trying to create a photo album for shown to mothers who choose a family with which you want to place their child/ren for adoption. I'm at my wit's end.  The kicker is I'm moving towards trying to export all my pictures, and that's going to be a HUGE problem in course for me, so I really hope that there is a way around this question somewhat simply. I am a hobby photographer and use the computer for businesses and crafts.  I've seen a few posts that included answers referencing "AppleScript" - I have no idea how to do something like that.

    From here on I will DEFINITELY ensure that my Canon continually numbers the names of image files and automatically resets.  For the other photos other than Canon, is possible to rename images during the import of the lot?

    All advice and help will be GREATLY appreciated!

    Finder has the ability to rename files with various models of lot.  Simply select all the files to rename, right-click one of the selected files, choose 'Rename X points... '. ", and then set the options and click on the button"Rename ".

  • I do I crop multiple images of the same photo in Lightroom 5 so I can export to Photomatix

    How do I crop multiple images of the same photo in Lightroom 5 so I can export to Photomatix.

    If the area covered by the images is the same, I suggest the creation of the HDR image first using the full frame and then later cultures. If you prefer he do it your way, highlight images and turn on auto-sync. Then one of the images of cultures and will apply to all images highlight.

  • Need help to open two images with the same file with different exposures on the screen at the same time in the Photoshop creative cloud (in previous versions we could open two images of the same nef (raw) file and then combine them on the screen with the

    Need help to open two images with the same file with different exposures on the screen at the same time in the Photoshop creative cloud (in previous versions we could open two images of the same nef (raw) file and then combine them on the screen with the move tool. They have become a composite of two layers which could be developed further with the mask tool.

    Hello

    Please go to the preferences > workspace and uncheck the option 'open the document in the tabs '.

    Now you can click on file and choose file > open and open the two images in two different windows which can be arranged side by side.

    Thank you

  • How to display multiple images at the same time in CS6?

    How to display multiple images at the same time in CS6?

    Hello

    If you go to window > reorganize you can choose from several display options. Below, I have chosen two horizontal spaces since I have two images, but you can select other options if you have more than one image.

  • Is it possible to have multiple windows of the same file open?

    Hello

    I was wondering if it is possible to have multiple windows of the same file open at the same time in Windows XP?

    Thank you!

    Dave

    You're welcome, Dave. If you click directly on a file, it will be open only once.  That's why I gave an example of starting with work stations and by navigating to the folder (open indirectly).  You can access a the desktop folder in C:\Documents and Settings\\Desktop.
    Boulder computer Maven
    Most Microsoft Valuable Professional

  • Write a string and an integer and a table all in the same file?

    Hello

    I am currently it several different types of values with LabView.

    I have a shot, a few numbers and several paintings.

    Thus, for example, I have a timestamp of the chain, several values of "integer" amplitude of the signal for example, RMS value, frequency and I have several paintings - table of signal, the FFT (PIC and location) values.

    Basically, I'm trying to find a way to write all the values in a single file. I can write all the individual types to separate files (so I can write the RMS, amplitude and frequency to a single file, some of the tables in the other)
    but is it possible to write a string and an integer and a table all in the same file?

    Pointers would be much appreciated,

    Thank you

    Paula

    Your file will be all text... any format in a table of text, to build as a single table, "table chain worksheet", to write to the file.

    (I'm sure this has been on the forums before... a search it would have thrown upward)

  • Play video and display an image at the same time

    Hi all

    I'm new to JavaFX and I would like to know if it is possible to read a video simultaneously and display an image above him in the same scene.

    In particular, I want the image to display in a fixed position.

    I tried to use a StackPane layout, but I get an error in the following line:

    sp.getChildren().add(mediaPlayer);
    

    because the mediaPlayer object cannot be considered to be a parameter and a node object is necessary

    I also tried to add the video and the image in the same scene as seen below, without success (the video is playing, but the image is not displayed)

    root.getChildren().add(imageView);
    

    Is what I'm trying to do possible? And if so, what methods should I use?

    Thanks in advance for any answer!

    I tried to use a StackPane layout, but I get an error in the following line:

    1. sp.getChildren () .add (mediaPlayer);

    because the mediaPlayer object cannot be considered to be a parameter and a node object is necessary

    Wrap the mediaPlayer in a MediaView and add the media view to the container. Do not use a group as the component root as in the code example in the example, though.

    I also tried to add the video and the image in the same scene as seen below, without success (the video is playing, but the image is not displayed)

    I think it is because you are using a StackPane, that stacks on top of the other nodes (in the Z-order); so if you add the video first it will be hidden by the image. Use a different presentation pane: VBox is the simplest. The tutorial has a summary of all the components of integrated layout .

    If you are going to do something like this:

    public void start(Stage primaryStage) {
         Media media = new Media(...);
         MediaPlayer player = new MediaPlayer(media);
         MediaView mediaView = new MediaView(player);
    
         Image image = new Image(...);
         ImageView imageView = new ImageView(image);
    
         VBox root = new VBox(5);
         root.getChildren().add(mediaView);
         root.getChildren().add(imageView);
    
         Scene scene = new Scene(root);
         primaryStage.setScene(scene);
         primaryStage.show();
    }
    
  • Copy and paste multiple fields at the same time?

    Is it possible to copy and paste several fields at the same time as in the employment history section or reference to an employment application?

    Hello Glenn,.

    You can right click on the domain and select 'Copy field' and can then slide it into position suitable in the document so that in the preview page.

    Let me know if that helps!

    Kind regards

    -Usman

  • How can we prevent the Explorer of research according to the records of multiple copies of the same file?

    Several slightly different copies of the same file, but subfolders will appear in Windows 7 when you perform a global search for files with specific attributes (e.g., size, date, extension).  If you delete a file, you really are by deleting all the files reported.  What are the steps to perform a search and don't report the real file rather than multiple versions of shadow or shortcut of the file?

    Example:
    Research on all files on the C drive beyond 1 GB, I receive a report in which there are 4 files
    games_file. ISO 7,084,400,688 1/1/2011 12:00 am a C:\Documents and settings\COMPUTER\Documents\Stuff\Apps
    games_file. ISO 7,084,400,688 1/1/2011 12:00 am a C:\Documents and settings\COMPUTER\My Documents\Stuff\Apps
    games_file. ISO 7,084,400,688 1/1/2011 12:00 am by C:\Users\COMPUTER\Documents\Stuff\Apps
    games_file. ISO 7,084,400,688 1/1/2011 12:00 am has C:\Users\COMPUTER\My Documents\Stuff\Apps

    WOW - I can save 21 GB deleting 3 files, right?  Nope, it's all the same physical file.  It should be reported as such.

    Hello

    I suggest to check indexed locations and make sure that duplicate records are not explicitly added. If they do, delete or rebuild the search index and check if the problem is still there

    Change advanced indexing options

    http://Windows.Microsoft.com/en-us/Windows7/change-advanced-indexing-options

    If the problem persists, then create a new user account and verify.

    Create a user account

    http://Windows.Microsoft.com/en-us/Windows7/create-a-user-account

    Create a test file in the same location, and check if the same file is returned multiple times.

    If this isn't the case, then follow the steps mentioned in the link to transfer data from the old user account for the new user account.

    Difficulty of a corrupted user profile

    http://Windows.Microsoft.com/en-us/Windows7/fix-a-corrupted-user-profile

  • Scan multiple pages in the same file on the computer

    How can I scan multiple pages on the same computer file on my HP Officejet Pro 8600 Plus?  Currently, it will scan each page to a separate computer file only.  Scan a document and then when asked if I want to scan another page I say Yes and the scanner.  However, they still attend separate computer files.

    Thank you!

    Thank you very much!

  • multiple paths to the same file come in research

    When I search for a file, I get the multiple as paths:

    C:\Users\Bill\My Documents\... file

    and

    C:\Documents and Settings\Bill\My Documents\ drop...

    The "Documents and Settings" folder contains a shortcut arrow.  There is only one folder for each of the folders in the path starting with 'Bill', that is, they are the same file in two ways.  That is this folder shortcut to, do I need, can I get rid of him and still have my files?  Have no idea how it got there.

    This is the direct download link to the usefulness of the junction box , wait approximately 5 seconds or more for the dialog "Save file" to appear, the name of the file is Junction100.zip (622 KB).  This kind of utilities are sometimes reported as virus by AV software, as long as you know the origin of the file and understand what the utility is supposed to do you will be sure to run the file, what is mentioned on the web site of the author:

    Note that this utility has undergone some fake antivirus alerts, including Norton and McAfee. The Manager of coding point of view there is nothing much that we can do about it, it seems as if some suppliers of software antivirus today write code if the trigger-happy it signals to ANY program that makes the fundamental system changes (which this must do, or it would be of no use!) as potential malware. Especially, the best AV products don't produce any these false alerts.

    Otherwise I have no way of knowing what permissions have been changed on your machine and that I have to post a playfile SubInACL to restore the permissions... believe me, the utility from the link above is much easier to use!

    John

  • Multiple copies of the same file

    I don't know it is a simple question, but can I, or rather, how I can have multiple copies of the same pdf file open?  I want to be able to compare pages, for example looking at a figure by reading the description in the text.  I tried the obvious way to open the file again, but it bounced just to the already open window.  Thanks for any help.

    Or try the menu option: window > Split - it will allow you to see the two views of the same document.

  • Scanning multiple images at the same time and you want to save everything in a single file, not separately

    I have the HP Envy 4500 model.  I also have a Windows 7 OS, HP.  My problem is that I put for example five images on the glass for scanning and I find myself with five different jpg files when I want all five images on a SINGLE scanned jpg file.  How to achieve this?  Thank you!

    Hello

    Please use the scanner software on your computer.

    Kind regards.

  • Ability to download multiple images at the same time on Windows?

    I would use Revel for storing my photos, but must be able to download my photos to have a personal backup. I intend to have my updates have taken place since my Android phone, but when I try to download on the site it just allows me to upload one image at a time. Is it possible to download multiple images / my entire library when you run Windows?

    You are right on adoberevel.com, you can only download one photo at a time. Mac app allows the selection of a group of files to download. This feature has been requested for other platforms and is on the wish list for consideration in future versions of revel.

    The other option is of 12 elements. Users who have their pictures put in place in mobile albums in the organizer of items have a current automatic synchronization between the organizer and revel. If you put autoupload in place on your mobile devices, this essentially gets then you a copy on your computer and access to a copy in the cloud on all of your devices.

    Guinot

Maybe you are looking for