Image multi converter

Soyez le premier à donner votre avis sur cette source.

Vue 13 226 fois - Téléchargée 575 fois

Description

Le code est complet. Peut-être qu'il y a l'interface qui mérite une meilleure approche.

Source / Exemple :


//
//  ImageMultiConverter.java
//  ImageMultiConverter
//
//  Created by Mich?le Morier-Genoud on 24.08.06.
//  Copyright (c) 2006 __MyCompanyName__. All rights reserved.
//
//  A simple signed Java applet
//

import com.sun.media.imageio.plugins.tiff.TIFFImageWriteParam;
import com.sun.media.imageio.stream.FileChannelImageInputStream;
import com.sun.media.imageio.stream.FileChannelImageOutputStream;
import java.awt.*;
import java.awt.geom.AffineTransform;
import javax.imageio.event.IIOReadProgressListener;
import javax.imageio.event.IIOReadWarningListener;
import javax.imageio.event.IIOWriteProgressListener;
import javax.imageio.event.IIOWriteWarningListener;
import javax.imageio.metadata.IIOMetadata;
import javax.imageio.plugins.jpeg.JPEGImageWriteParam;
import javax.swing.*;
import javax.swing.event.*;
import java.io.*;
import java.util.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.imageio.*;
import javax.imageio.stream.*;
import installer.*;
import org.jdesktop.jdic.tray.SystemTray;
import org.jdesktop.jdic.tray.TrayIcon;
import sf3.SpritesCacheManager;

public class ImageMultiConverter_Ant extends JApplet implements AntApplet {
    static LibLoader libLoader = new LibLoader(ImageMultiConverter_Ant.class);
    
    private JCheckBox sw_resize_height, sw_resize_width, sw_resize;
    
    private JSpinner sw_resize_height_v;
    
    private HashMap<Integer, JCheckBox> sw_color_option;
    
    private JSpinner sw_compression_quality;
    
    private JSpinner sw_resize_width_v;
    
    static{
        int pty = Thread.currentThread().getPriority();
        Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
        JFrame frame = UIMessage.displayWaiting("Loading...", null);
        libLoader.setUseCPEnabled(true);
        /* PowerPC libs */
        libLoader.addLib("jdic", "libjdic.jnilib");
        libLoader.addLib("tray", "libtray.jnilib");
        libLoader.loadAll(false);
        /* ix86-compatible libs 
        libLoader.addLib("mlib_jai_mmx", "mlib_jai_mmx.dll");
        libLoader.addLib("mlib_jai", "mlib_jai.dll");
         
        libLoader.addLib("mlib_jai_util", "mlib_jai_util.dll");
        libLoader.addLib("clib_jiio_sse2", "clib_jiio_sse2.dll");
        libLoader.addLib("clib_jiio", "clib_jiio.dll");
        libLoader.addLib("clib_jiio_util", "clib_jiio_util.dll");
         
        libLoader.loadAll(true);
        libLoader.addLib("jdic", "jdic.dll");
        libLoader.load("jdic", false);
        libLoader.addLib("tray", "tray.dll");
        libLoader.load("tray", false);

  • /
try { ImageIO.getReaderMIMETypes(); new UIMessage("JAI/JIIO codecs disabled property is set to " + System.getProperty("com.sun.media.imageio.disableCodecLib"), null); } catch(Exception e) {} finally { frame.setVisible(false); Thread.currentThread().setPriority(pty); } } private Frame owner = null; private JPanel display; JScrollPane scroll; public void setOwner(Frame owner) { this.owner = owner; } static final String message = "Hello World!"; private Font font = new Font("serif", Font.ITALIC + Font.BOLD, 36); private File[] selectedFiles; private LogArea sw_log; private FileChooserPane jfc; private JButton sw_selectFormat, sw_convert; private ImageOutputStream ios; private JProgressBar fileJPB; private JEditorPane sw_html; private StatusPane toggleStep; private JSpinner sw_zoom; private String selectedConversion = ImageIO.getWriterMIMETypes()[0]; private SpritesCacheManager<Object, Object> cache = new SpritesCacheManager<Object, Object>(100); private Thread t; private int iterator = 0; private boolean ignoreMsg = false; private int timerHash = 0; private TrayIcon tray; private SystemTray systemTray; boolean blackAndWhiteEnabled = false; boolean canvasScaleOnlyEnabled = false; float compression_quality = 0.8f; public void init() { cache.setAutoCleanupEnabled(true); // set the default look and feel String laf = UIManager.getSystemLookAndFeelClassName(); try { UIManager.setLookAndFeel(laf); } catch (UnsupportedLookAndFeelException exc) { System.err.println("Warning: UnsupportedLookAndFeel: " + laf); } catch (Exception exc) { System.err.println("Error loading " + laf + ": " + exc); } getContentPane().setLayout(new BorderLayout()); setPreferredSize(new Dimension(500,500)); setSize(getPreferredSize()); Container content = getContentPane(); final InstructionsPane pane = new InstructionsPane(this, 0, 5); toggleStep = new StatusPane(pane); try{ sw_html = new JEditorPane(getClass().getClassLoader().getResource("ads.html")); sw_html.setPreferredSize(new Dimension(300,100)); sw_html.setEditable(false); } catch(IOException e) { JOptionPane.showMessageDialog(this, e.getMessage()); } content.add(sw_html, BorderLayout.NORTH); content.add(pane, BorderLayout.CENTER); content.add(toggleStep, BorderLayout.SOUTH); int step = pane.addStep(); pane.addStepComponent(step, new JTextArea("Go to next step and select the images files you want to convert.")); step = pane.addStep(); final FileChooserPane jfc = new FileChooserPane(owner, ""); jfc.setModeOpen(true); pane.addStepComponent(step, sw_selectFormat = new JButton("Conversion format...")); sw_selectFormat.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { selectedConversion = JOptionPane.showInputDialog(ImageMultiConverter_Ant.this, "What conversion type do you want?", "Convert...", JOptionPane.QUESTION_MESSAGE, null, ImageIO.getWriterMIMETypes(), getSelectedConversion()).toString(); sw_convert.setText("Convert to " + getSelectedConversion()); }}); pane.addInstructionSet(jfc); step = pane.addStep(2); pane.addStepComponent(step, new JLabel("This value will zoom the image to choosen scale (%):"), 1, 2); pane.addStepComponent(step, sw_zoom = new JSpinner(new SpinnerNumberModel(100,1,500,1)), 1, 2); pane.addStepComponent(step, sw_resize_width = new JCheckBox("resize width :")); pane.addStepComponent(step, sw_resize_width_v = new JSpinner(new SpinnerNumberModel(150, 1, 3000, 1))); pane.addStepComponent(step, sw_resize_height = new JCheckBox("resize height :")); pane.addStepComponent(step, sw_resize_height_v = new JSpinner(new SpinnerNumberModel(150, 1, 3000, 1))); pane.addStepComponent(step, new JLabel("compression quality (JPEG only)")); pane.addStepComponent(step, sw_compression_quality = new JSpinner(new SpinnerNumberModel((int)(compression_quality*100), 0, 100, 10))); final HashMap<Integer, Action> color_options = new HashMap<Integer, Action>(); final HashMap<Integer, Boolean> color_options_switch = new HashMap<Integer, Boolean>(); sw_color_option = new HashMap<Integer, JCheckBox>(); final int BLACKANDWHITE = 0; final int CANVASSCALEONLY = 1; color_options.put(BLACKANDWHITE, new AbstractAction("black & white") { public void actionPerformed(ActionEvent e) { blackAndWhiteEnabled = sw_color_option.get(BLACKANDWHITE).isSelected(); ; }}); color_options_switch.put(BLACKANDWHITE, blackAndWhiteEnabled); color_options.put(CANVASSCALEONLY, new AbstractAction("image canvas scale only") { public void actionPerformed(ActionEvent e) { canvasScaleOnlyEnabled = sw_color_option.get(CANVASSCALEONLY).isSelected(); }}); color_options_switch.put(CANVASSCALEONLY, canvasScaleOnlyEnabled); for(Iterator<Integer> i = color_options.keySet().iterator(); i.hasNext(); ) { int aKey = i.next(); sw_color_option.put(aKey, new JCheckBox(color_options.get(aKey))); sw_color_option.get(aKey).setSelected(color_options_switch.get(aKey)); pane.addStepComponent(step, new JLabel(color_options.get(aKey).getValue(Action.NAME).toString())); pane.addStepComponent(step, sw_color_option.get(aKey)); } sw_zoom.setValue(100); sw_resize_width.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { sw_resize_width_v.setEnabled(sw_resize_width.isSelected()); }}); sw_resize_width.setSelected(false); sw_resize_width_v.setEnabled(false); sw_resize_height.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { sw_resize_height_v.setEnabled(sw_resize_height.isSelected()); }}); sw_resize_height_v.setEnabled(false); sw_resize_height.setSelected(false); step = pane.addStep(2); pane.addStepComponent(step, sw_convert = new JButton("Convert to " + getSelectedConversion())); pane.addStepComponent(step, sw_log = new LogArea()); sw_log.setLogStdOutEnabled(true); pane.addStepComponent(step, new JLabel("Conversion progress: "), 1, 2); pane.addStepComponent(step, scroll = new JScrollPane(display = new JPanel(true)), 1, 2, 1.0, 1.0); scroll.setPreferredSize(new Dimension(this.getSize().width, 200)); scroll.validate(); pane.addStepComponent(step, fileJPB = new JProgressBar(0,1), 1, 2, 1.0, 0.0); fileJPB.setDoubleBuffered(true); fileJPB.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { fileJPB.update(fileJPB.getGraphics()); }}); sw_convert.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (jfc.getStatus() == JFileChooser.APPROVE_OPTION) { sw_log.clearLog(); selectedFiles = jfc.getSelectedFiles(); final FileChooserPane jfc_out = new FileChooserPane(null, ""); jfc_out.setMultiSelectionEnabled(false); jfc_out.setModeSave(true); File[] outputDirs = jfc_out.getDirectory(); final String[] outputDir = new String[outputDirs.length]; int i = 0; for(File dir : outputDirs) outputDir[i++] = dir.getPath(); if(outputDir[0] == null) return; if(jfc_out.getStatus() == JFileChooser.APPROVE_OPTION) { final ProgressListener uiprg = new ProgressListener(); final WarningListener uiwarn = new WarningListener(); final JPanel display = ImageMultiConverter_Ant.this.display; cache.clear(); iterator = 0; // images read display.removeAll(); cache.cleanup(); javax.swing.Timer t = new javax.swing.Timer(100, new ActionListener() { public void actionPerformed(ActionEvent e) { int pty = Thread.currentThread().getPriority(); Thread.currentThread().setPriority(Thread.MAX_PRIORITY); Stack<BufferedImage> img = new Stack<BufferedImage>(); Display picture = null; fileJPB.setMaximum(selectedFiles.length-1); int i = iterator; iterator++; if(i > selectedFiles.length - 1) { javax.swing.Timer t; if((t = toggleStep.getActiveTimer(timerHash)).isRunning()) t.stop(); try { tray.displayMessage("ImageMultiConverter", "conversion has completed!", TrayIcon.INFO_MESSAGE_TYPE); } catch(Exception e2) { e2.printStackTrace(); } finally { return; } } File file = selectedFiles[i]; cache.add(i, file); fileJPB.setValue(i++); File inputFile = file; RandomAccessFile raf; ImageReader r = null; ImageInputStream iis = null; RProgressListener rpl = new RProgressListener(); RWarningListener rwl = new RWarningListener(); try{ JTable readersOps = null; Vector readersData = new Vector(); Vector readersDataID = new Vector(); readersDataID.add("format"); readersDataID.add("default read param"); readersDataID.add("reader"); for(Iterator<ImageReader> readers = ImageIO.getImageReaders(iis = new FileChannelImageInputStream((raf = new RandomAccessFile(inputFile, "rws")).getChannel())); readers.hasNext();) { ImageReader r0 = readers.next(); Vector v = new Vector(); v.add(r0.getFormatName()); v.add(r0.getDefaultReadParam().toString()); v.add(r0.toString()); readersData.add(v); } readersOps = new JTable(readersData, readersDataID); if(!ignoreMsg) { new UIMessage(readersOps, ImageMultiConverter_Ant.this.owner); showIgnoreDialog(); } for(Iterator readers = ImageIO.getImageReaders(iis = new FileChannelImageInputStream((raf = new RandomAccessFile(inputFile, "rws")).getChannel())); readers.hasNext(); i++) { try { cache.buffer(raf); r = (ImageReader)readers.next(); r.setInput(iis); cache.buffer(iis); r.addIIOReadProgressListener(rpl); r.addIIOReadWarningListener(rwl); toggleStep.addActiveStream((Closeable)raf.getChannel()); if(r.readerSupportsThumbnails()) { if(r.hasThumbnails(0)) { Image thumb = r.readThumbnail(0,0); picture = new Display(thumb, null); cache.buffer(picture); display.add(picture); display.validate(); scroll.validate(); } } int j = 0; cache.buffer(img); while(r.getNumImages(true) != -1) { img.push(r.read(j++, r.getDefaultReadParam())); new Display(img.peek(), null); } r.dispose(); iis.close(); raf.close(); } catch (IndexOutOfBoundsException ex) { ex.printStackTrace(); } catch(Exception ex) { ex.printStackTrace(); if(!ignoreMsg) { new UIMessage("An unknown error has occured while reading..." + ex.getMessage(), ImageMultiConverter_Ant.this.owner); showIgnoreDialog(); } continue; } finally { // images transformations double zoom = (((SpinnerNumberModel)sw_zoom.getModel()).getNumber().intValue()/100.0); int width = (sw_resize_width_v.isEnabled())?((SpinnerNumberModel)sw_resize_width_v.getModel()).getNumber().intValue():0; int height = (sw_resize_height_v.isEnabled())?((SpinnerNumberModel)sw_resize_height_v.getModel()).getNumber().intValue():0; AffineTransform tx; Stack<BufferedImage> newImg = new Stack<BufferedImage>(); while(!img.empty()) { double zoom_width = 1.0; double zoom_height = 1.0; if(width > 0) { zoom_width = (double)width / img.peek().getWidth(ImageMultiConverter_Ant.this); if(height == 0) zoom_height = zoom_width; } if(height > 0) { zoom_height = (double)height / img.peek().getHeight(ImageMultiConverter_Ant.this); if(width == 0) zoom_width = zoom_height; } // 1st zoom tx = AffineTransform.getScaleInstance(zoom, zoom); cache.buffer(tx); Dimension newDim = new Dimension( (int)Math.floor(img.peek().getWidth(ImageMultiConverter_Ant.this) * tx.getScaleX()), (int)Math.floor(img.peek().getHeight(ImageMultiConverter_Ant.this) * tx.getScaleY()) ); BufferedImage bimg = new BufferedImage( newDim.width, newDim.height, ((blackAndWhiteEnabled)?BufferedImage.TYPE_BYTE_GRAY:BufferedImage.TYPE_4BYTE_ABGR) ); cache.buffer(bimg); new Display(bimg, null); Graphics2D g2 = bimg.createGraphics(); g2.drawImage(img.peek(), tx, ImageMultiConverter_Ant.this); g2.dispose(); // scaled size tx.scale(zoom_width, zoom_height); System.out.println("original : " + img.peek().getWidth(ImageMultiConverter_Ant.this) + "x"+ img.peek().getHeight(ImageMultiConverter_Ant.this) + " zoom : " + zoom_width + "x" + zoom_height); System.out.println(tx.getScaleX()); System.out.println(tx.getScaleY()); Dimension newDim2 = new Dimension( (int)Math.floor(img.peek().getWidth(ImageMultiConverter_Ant.this) * tx.getScaleX()), (int)Math.floor(img.peek().getHeight(ImageMultiConverter_Ant.this) * tx.getScaleY()) ); BufferedImage bimg2 = new BufferedImage( newDim2.width, newDim2.height, ((blackAndWhiteEnabled)?BufferedImage.TYPE_BYTE_GRAY:BufferedImage.TYPE_4BYTE_ABGR) ); cache.buffer(bimg2); new Display(bimg2, null); Graphics2D g22 = bimg2.createGraphics(); if(canvasScaleOnlyEnabled) { g22.translate(newDim2.width/2 - bimg.getWidth(ImageMultiConverter_Ant.this)/2, newDim2.height/2 - bimg.getHeight(ImageMultiConverter_Ant.this)/2); g22.drawImage(bimg, null, ImageMultiConverter_Ant.this); g22.dispose(); } else { g22.drawImage(bimg, tx, ImageMultiConverter_Ant.this); g22.dispose(); } img.pop(); newImg.push(bimg2); } // images conversion String conversion = selectedConversion; String conversion_ext = "." + conversion.substring(conversion.lastIndexOf('/') + 1); // images write File outputFile = new File(outputDir[0] + File.separator + file.getName().substring(0, file.getName().lastIndexOf('.')) + conversion_ext); cache.buffer(outputFile); sw_log.pushNewLog("output file: " + outputFile); //outputFile.createNewFile(); compression_quality = ((SpinnerNumberModel)sw_compression_quality.getModel()).getNumber().floatValue()/100f;; JTable writersOps; Vector writersData = new Vector(); Vector writersDataID = new Vector(); writersDataID.add("conversion type"); writersDataID.add("default writer param"); writersDataID.add("writer"); for(Iterator<ImageWriter> writers = ImageIO.getImageWritersByMIMEType(conversion); writers.hasNext();) { ImageWriter w0 = writers.next(); Vector v = new Vector(); v.add(conversion); v.add(w0.getDefaultWriteParam().toString()); v.add(w0.toString()); writersData.add(v); } writersOps = new JTable(writersData, writersDataID); if(!ignoreMsg) { new UIMessage(writersOps, ImageMultiConverter_Ant.this.owner); showIgnoreDialog(); } for(Iterator writers = ImageIO.getImageWritersByMIMEType(conversion); writers.hasNext();) { sw_log.pushNewLog("conversion " + conversion); ImageWriter w = (ImageWriter)writers.next(); cache.buffer(w); try { w.addIIOWriteProgressListener(uiprg); w.addIIOWriteWarningListener(uiwarn); w.setOutput(ios = new FileChannelImageOutputStream((raf = new RandomAccessFile(outputFile, "rws")).getChannel())); cache.buffer(ios); cache.buffer(raf); toggleStep.addActiveStream((Closeable)raf.getChannel()); while(!newImg.empty()) { IIOMetadata meta = w.getDefaultImageMetadata(new ImageTypeSpecifier((RenderedImage)newImg.peek()),w.getDefaultWriteParam()); ImageWriteParam wparam = w.getDefaultWriteParam(); if(wparam instanceof JPEGImageWriteParam) { ((JPEGImageWriteParam)wparam).setCompressionMode(JPEGImageWriteParam.MODE_EXPLICIT); ((JPEGImageWriteParam)wparam).setCompressionQuality(compression_quality); //((JPEGImageWriteParam)wparam).setCompressionType("JPEG-LS"); }/* else if(conversion.equals("image/bmp")) { ((BMPImageWriteParam)wparam).setCompressionMode(BMPImageWriteParam.MODE_EXPLICIT); ((BMPImageWriteParam)wparam).setCompressionType("BI_RLE8"); } else if(conversion.equals("image/gif")) { wparam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); wparam.setCompressionType("LZW"); } else if(conversion.equals("image/tiff")) { ((TIFFImageWriteParam)wparam).setCompressionMode(TIFFImageWriteParam.MODE_EXPLICIT); ((TIFFImageWriteParam)wparam).setCompressionType("ZLib"); }*/ if(w.canInsertImage(-1)) w.writeInsert(-1, new IIOImage(newImg.peek(), null, meta), wparam); else w.write(meta, new IIOImage((RenderedImage)newImg.peek(), null, meta), wparam); display.add(new Display(newImg.peek(), null)); newImg.pop(); display.validate(); scroll.validate(); } ios.close(); raf.close(); } catch(Exception ex) { ex.printStackTrace(); if(!ignoreMsg) { new UIMessage("An unknown error has occured while writing. See log!", ImageMultiConverter_Ant.this.owner); showIgnoreDialog(); } continue; } finally { w.dispose(); /***/ break; } } } } } catch(Exception ex) { ex.printStackTrace(); new UIMessage(ex.getMessage(), ImageMultiConverter_Ant.this.owner); } }}); timerHash = t.hashCode(); toggleStep.addActiveTimer(t); t.start(); } else return; } if(jfc.getStatus() == JFileChooser.CANCEL_OPTION) return; }}); pane.validate(); } private void showIgnoreDialog() { switch(JOptionPane.showConfirmDialog(ImageMultiConverter_Ant.this, "Ignore further messages?", "Ignore?", JOptionPane.YES_NO_CANCEL_OPTION)){ case JOptionPane.YES_OPTION: ignoreMsg = true; break; case JOptionPane.CANCEL_OPTION: toggleStep.cancelAll(); break; case JOptionPane.NO_OPTION: case JOptionPane.CLOSED_OPTION: ignoreMsg = false; break; default: } } private String getSelectedConversion() { return selectedConversion; } class ProgressListener implements IIOWriteProgressListener { public void imageComplete(ImageWriter imageWriter) { String string; System.out.println(string = "complete."); try{ ImageMultiConverter_Ant.this.tray.displayMessage("ImageMultiConverter", string, TrayIcon.WARNING_MESSAGE_TYPE); } catch (Exception e){ e.printStackTrace(); } } public void imageStarted(ImageWriter imageWriter, int i) { String string; System.out.println(string = "Starting write..."); try{ ImageMultiConverter_Ant.this.tray.displayMessage("ImageMultiConverter", string, TrayIcon.WARNING_MESSAGE_TYPE); } catch (Exception e){ e.printStackTrace(); } } public void imageProgress(ImageWriter imageWriter, float f) { String string; System.out.print(string = "."); } public void thumbnailComplete(ImageWriter imageWriter) { String string; System.out.println(string = "complete."); try{ ImageMultiConverter_Ant.this.tray.displayMessage("ImageMultiConverter", string, TrayIcon.WARNING_MESSAGE_TYPE); } catch (Exception e){ e.printStackTrace(); } } public void thumbnailProgress(ImageWriter imageWriter, float f) { String string; System.out.print(string = "."); } public void thumbnailStarted(ImageWriter imageWriter, int i, int i0) { String string; System.out.println(string = "Starting write..."); try{ ImageMultiConverter_Ant.this.tray.displayMessage("ImageMultiConverter", string, TrayIcon.WARNING_MESSAGE_TYPE); } catch (Exception e){ e.printStackTrace(); } } public void writeAborted(ImageWriter imageWriter) { String string; System.out.print(string = "aborted!"); try{ ImageMultiConverter_Ant.this.tray.displayMessage("ImageMultiConverter", string, TrayIcon.WARNING_MESSAGE_TYPE); } catch (Exception e){ e.printStackTrace(); } } } class WarningListener implements IIOWriteWarningListener { public void warningOccurred(ImageWriter imageWriter, int i, String string) { System.out.println("Error! " + string); try{ ImageMultiConverter_Ant.this.tray.displayMessage("ImageMultiConverter", string, TrayIcon.WARNING_MESSAGE_TYPE); } catch (Exception e){ e.printStackTrace(); } finally { if(!ImageMultiConverter_Ant.this.ignoreMsg) { new UIMessage(string, ImageMultiConverter_Ant.this.owner); ImageMultiConverter_Ant.this.showIgnoreDialog(); } } } } class RProgressListener implements IIOReadProgressListener { /**
  • Reports that a sequence of read operations is beginning.
  • <code>ImageReader
implementations are required to call
  • this method exactly once from their
  • readAll(Iterator)
    method.

  • *
    • @param source the
      ImageReader
      object calling this method.
    • @param minIndex the index of the first image to be read.
    • /

    public void sequenceStarted(ImageReader source, int minIndex) {
    String string;
    System.out.print(string = "Read...");
    try{
    ImageMultiConverter_Ant.this.tray.displayMessage("ImageMultiConverter", string, TrayIcon.WARNING_MESSAGE_TYPE);
    } catch (Exception e){
    e.printStackTrace();
    }

    }

    /**
    • Reports that a sequence of read operationshas completed.
    • ImageReader
      implementations are required to call
    • this method exactly once from their
    • readAll(Iterator)
      method.

    *
    • @param source the
      ImageReader
      object calling this method.
    • /

    public void sequenceComplete(ImageReader source) {
    String string;
    System.out.println(string = "done.");
    try{
    ImageMultiConverter_Ant.this.tray.displayMessage("ImageMultiConverter", string, TrayIcon.WARNING_MESSAGE_TYPE);
    } catch (Exception e){
    e.printStackTrace();
    }
    }

    /**
    • Reports that an image read operation is beginning. All
    • ImageReader
      implementations are required to call
    • this method exactly once when beginning an image read
    • operation.

    *
    • @param source the
      ImageReader
      object calling this method.
    • @param imageIndex the index of the image being read within its
    • containing input file or stream.
    • /

    public void imageStarted(ImageReader source, int imageIndex){
    try {
    System.out.print("Read... (" + source.getFormatName() + ")");
    } catch (Exception ex) {
    ex.printStackTrace();
    }
    }
    /**
    • Reports the approximate degree of completion of the current
    • read
      call of the associated
    • ImageReader
      .

    *
    • <p> The degree of completion is expressed as a percentage
    • varying from
      0.0F
      to
      100.0F
      . The
    • percentage should ideally be calculated in terms of the
    • remaining time to completion, but it is usually more practical
    • to use a more well-defined metric such as pixels decoded or
    • portion of input stream consumed. In any case, a sequence of
    • calls to this method during a given read operation should
    • supply a monotonically increasing sequence of percentage
    • values. It is not necessary to supply the exact values
    • 0
      and
      100
      , as these may be inferred
    • by the callee from other methods.

    *
    • <p> Each particular
      ImageReader
      implementation may
    • call this method at whatever frequency it desires. A rule of
    • thumb is to call it around each 5 percent mark.

    *
    • @param source the
      ImageReader
      object calling this method.
    • @param percentageDone the approximate percentage of decoding that
    • has been completed.
    • /

    public void imageProgress(ImageReader source, float percentageDone) {
    String string;
    System.out.print(string = ".");
    }

    /**
    • Reports that the current image read operation has completed.
    • All
      ImageReader
      implementations are required to
    • call this method exactly once upon completion of each image
    • read operation.

    *
    • @param source the
      ImageReader
      object calling this
    • method.
    • /

    public void imageComplete(ImageReader source){
    String string;
    System.out.println(string = "done.");
    try{
    ImageMultiConverter_Ant.this.tray.displayMessage("ImageMultiConverter", string, TrayIcon.WARNING_MESSAGE_TYPE);
    } catch (Exception e){
    e.printStackTrace();
    }
    }
    /**
    • Reports that a thumbnail read operation is beginning. All
    • ImageReader
      implementations are required to call
    • this method exactly once when beginning a thumbnail read
    • operation.

    *
    • @param source the
      ImageReader
      object calling this method.
    • @param imageIndex the index of the image being read within its
    • containing input file or stream.
    • @param thumbnailIndex the index of the thumbnail being read.
    • /

    public void thumbnailStarted(ImageReader source,
    int imageIndex, int thumbnailIndex){
    try {
    System.out.print("Read... (" + source.getFormatName() + ")");
    } catch (Exception ex) {
    ex.printStackTrace();
    }
    }
    /**
    • Reports the approximate degree of completion of the current
    • getThumbnail
      call within the associated
    • ImageReader
      . The semantics are identical to those
    • of
      imageProgress
      .

    *
    • @param source the
      ImageReader
      object calling this method.
    • @param percentageDone the approximate percentage of decoding that
    • has been completed.
    • /

    public void thumbnailProgress(ImageReader source, float percentageDone){
    String string;
    System.out.print(string = ".");
    }
    /**
    • Reports that a thumbnail read operation has completed. All
    • ImageReader
      implementations are required to call
    • this method exactly once upon completion of each thumbnail read
    • operation.

    *
    • @param source the
      ImageReader
      object calling this
    • method.
    • /

    public void thumbnailComplete(ImageReader source){
    String string;
    System.out.println(string = "done.");
    try{
    ImageMultiConverter_Ant.this.tray.displayMessage("ImageMultiConverter", string, TrayIcon.WARNING_MESSAGE_TYPE);
    } catch (Exception e){
    //e.printStackTrace();
    }
    }
    /**
    • Reports that a read has been aborted via the reader's
    • abort
      method. No further notifications will be
    • given.

    *
    • @param source the
      ImageReader
      object calling this
    • method.
    • /

    public void readAborted(ImageReader source){
    String string;
    System.out.println(string = "canceled!");
    try{
    ImageMultiConverter_Ant.this.tray.displayMessage("ImageMultiConverter", string, TrayIcon.WARNING_MESSAGE_TYPE);
    } catch (Exception e){
    e.printStackTrace();
    }
    }
    }

    class RWarningListener implements IIOReadWarningListener {
    public void warningOccurred(ImageReader source, String warning) {
    try {
    ImageMultiConverter_Ant.this.tray.displayMessage("ImageMultiConverter", warning, TrayIcon.WARNING_MESSAGE_TYPE);
    System.out.println(warning);
    } catch (Exception ex) {
    ex.printStackTrace();
    }
    }

    }

    public static Display makeDisplay(Image image, AffineTransform tx) {
    return new Display(image, tx);
    }

    public ImageMultiConverter_Ant() throws IOException {
    super();
    AppLauncher launcher = new AppLauncher(this, "Image Multi-converter Ant", "© 2006 b23:production GNU/GPL http://b23prodtm.webhop.info", "images/logo.png", new Dimension(500,500), "about.htm");
    }

    public static void main(String[] args) throws IOException {
    new ImageMultiConverter_Ant();
    }

    public JApplet getApplet() {
    return this;
    }
    }
    </code>

    Conclusion :


    S'il y a du nouveau, pensez à publier un commentaire approprié! ;)

    Codes Sources

    A voir également

    Ajouter un commentaire

    Commentaire

    Messages postés
    5348
    Date d'inscription
    dimanche 4 mai 2003
    Statut
    Modérateur
    Dernière intervention
    30 mars 2020
    95
    Salut,

    Bon avant toute chose merci d'enlever les repertoire CVS et __MACOSX de ton zip.

    Le code n'est plus tot bien fait et bien commenté mais ce que je vois de l'utilisation c'est bof bof je m'explique:

    tu créer des petit boutons next et preview c'est beau mais tu n'a aucun controle sur les index vu qu'il est tres facile de leur faire générer un ArrayIndexOutOfBoundsException.

    Apres conversion de l'image des que l'on appui sur le bouton next il y a une jolie exception de levé
    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at installer.InstructionsPane.updateInstructionsStep(InstructionsPane.java:64)
    at installer.InstructionsPane.update(InstructionsPane.java:136)
    at installer.InstructionsPane.nextStep(InstructionsPane.java:112)
    at installer.StatusPane$1.actionPerformed(StatusPane.java:32)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:18
    .......et ca continue

    Concernant ton principe de conversion des images pourquoi pas mais ce n'est absolument pas viable pour les jpg qui doivent etre encodé avec JPEGImageEncoder afin de préserver la qualitée de l'image et ne pas obtenir une image toute cracra comme c'est le cas.

    Dernière petite chose afin d'aider les utilisateur tu peux proposer ton appli dans 2 modes de lancement :
    1 - en applet comme tu le fais
    2 - dans une fenetre pour ce faire rajoute simplement dans la class ImageMultiConverter
    public static void main(String [] args){
    JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setSize(300, 300);
    f.pack();
    f.setLocationRelativeTo(null);
    ImageMultiConverter imc = new ImageMultiConverter();
    imc.init();
    f.setContentPane(imc);
    f.setVisible(true);
    }

    En conclusion en toute modestie je te suggere de revoir ton interface graphique qui n'est vraiment pas pratique et à defaut met tout dans la meme fenetre defois je t'assur ca evite les problème et ca a plus de gueule.

    Vous n'êtes pas encore membre ?

    inscrivez-vous, c'est gratuit et ça prend moins d'une minute !

    Les membres obtiennent plus de réponses que les utilisateurs anonymes.

    Le fait d'être membre vous permet d'avoir un suivi détaillé de vos demandes et codes sources.

    Le fait d'être membre vous permet d'avoir des options supplémentaires.