Skip to main content

GIF animation fixing zero delay issue

/*
 * My GIF Viewer Version 1.0<br/>
 * viewing animated Gif by either making it the default program <br/>
 * to view it or by dragging the image into the program's frame.<br/>
 * The animation can be controlled either you slow it down by pressing <  <br/>
 * or speed it up by pressing >
 *
 */
package gif;

import java.awt.Toolkit;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Iterator;
import mygifutil.MyGifUtil;
import java.util.List;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.TransferHandler;

/**
 *
 * @author mahmoud.elsonbati@gmail.com
 */
public final class GIF extends JFrame implements MouseMotionListener, KeyListener {

    @Override
    public void setTitle(String title) {
        super.setTitle(title);
    }
    static JLabel label;
    public static File imgFile = null;
    public static int delay = 50;
    private MyGifUtil util;

    @SuppressWarnings("LeakingThisInConstructor")
    public GIF() {
        setTitle("drag image here!");
        this.setSize(400, 400);
        this.setLocation(300, 200);
        label = new JLabel();
        util = new MyGifUtil();
        getContentPane().add(label);
        JComponent cp = (JComponent) getContentPane();
        MyFileTransferHandler handler = new MyFileTransferHandler();
        cp.setTransferHandler(handler);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        addMouseMotionListener(this);
        addKeyListener(this);
        this.setVisible(true);
    }

    @SuppressWarnings("LeakingThisInConstructor")
    public GIF(String arg) {
        setTitle("drag image here!");
        this.setSize(400, 400);
        this.setLocation(300, 200);
        label = new JLabel();
        util = new MyGifUtil();
        imgFile = new File(arg);
        label.setIcon(new ImageIcon(arg));
        getContentPane().add(label);
        JComponent cp = (JComponent) getContentPane();
        MyFileTransferHandler handler = new MyFileTransferHandler();
        cp.setTransferHandler(handler);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        pack();
        addMouseMotionListener(this);
        addKeyListener(this);
        this.setVisible(true);
    }

    /**
     * setting the label image by file name
     * @param img
     */
    public static void setLabelIcon(String img) {
        label.setIcon(new ImageIcon(img));

    }

    /**Setting label image by file content
     *
     * @param data
     */
    public static void setLabel(byte[] data) {
        label.setIcon(new ImageIcon(data));

    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        if (args.length == 0) {
            new GIF();
        }
        if (args.length == 1) {
            new GIF(args[0]);
        }
    }

    /**
     * resize the frame to fit the image size
     * @param e
     */
    @Override
    public void mouseDragged(MouseEvent e) {
        if (label.getIcon() != null) {
            this.pack();
        }
    }

    /**
     * resize the frame to fit the image size
     * @param e
     */
    @Override
    public void mouseMoved(MouseEvent e) {
        if (label.getIcon() != null) {
            this.pack();
        }
    }

    /**
     * handle if user pressed < or >  to control frames delay
     * @param e
     */
    @Override
    public void keyTyped(KeyEvent e) {
       
        //check imgFile for null inputs
        if (imgFile == null) {
            return;
        }
        char key = e.getKeyChar();
        if (key == '<') { //slow down

            delay += 50;

            byte[] bytes = util.convertGIF(imgFile, delay);
            label.setIcon(null);
            label.setIcon(new ImageIcon(bytes));


        }
        if (key == '>') { //speed up
            if (delay <= 0) {
                return;
            }
            delay -= 50;
            System.out.println("delay= " + delay);

            byte[] bytes = util.convertGIF(imgFile, delay);
            label.setIcon(null);
            label.setIcon(new ImageIcon(bytes));
        }
        if (label.getIcon() != null) {
            this.pack();
        }
    }

    @Override
    public void keyPressed(KeyEvent e) {
        this.pack();
    }

    @Override
    public void keyReleased(KeyEvent e) {
        this.pack();
    }
}

/**
 * inner class handles the drag and drop acions
 * @author mahmoud
 */
class MyFileTransferHandler extends TransferHandler {

    /**
     * checking file type matching
     * @param arg0
     * @param arg1
     * @return
     */
    @Override
    public boolean canImport(JComponent arg0, DataFlavor[] arg1) {
        for (int i = 0; i < arg1.length; i++) {
            DataFlavor flavor = arg1[i];
            if (flavor.equals(DataFlavor.javaFileListFlavor)) {

                return true;
            }
            if (flavor.equals(DataFlavor.stringFlavor)) {

                return true;
            }

        }
        // Didn't find any that match, so:
        return false;
    }

    /**
     *method for dragging the image file into the frame
     */
    @Override
    public boolean importData(JComponent comp, Transferable t) {
        DataFlavor[] flavors = t.getTransferDataFlavors();

        for (int i = 0; i < flavors.length; i++) {
            DataFlavor flavor = flavors[i];
            try {
                if (flavor.equals(DataFlavor.javaFileListFlavor)) {


                    List l = (List) t.getTransferData(DataFlavor.javaFileListFlavor);
                    Iterator iter = l.iterator();
                    while (iter.hasNext()) {
                        File file = (File) iter.next();
                        GIF.imgFile = file;
                        GIF.delay = 50;

                        GIF.setLabelIcon(file.getCanonicalPath());

                    }
                    return true;
                } else if (flavor.equals(DataFlavor.stringFlavor)) {

                    String fileOrURL = (String) t.getTransferData(flavor);

                    try {
                        URL url = new URL(fileOrURL);

                        return true;
                    } catch (MalformedURLException ex) {
                        System.err.println("Not a valid URL");
                        return false;
                    }


                } else {
                }
            } catch (IOException ex) {
                System.err.println("IOError getting data: " + ex);
            } catch (UnsupportedFlavorException e) {
                System.err.println("Unsupported Flavor: " + e);
            }
        }
        // wrong dragged file
        Toolkit.getDefaultToolkit().beep();
        return false;
    }
}
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package mygifutil;

import com.madgag.gif.fmsware.AnimatedGifEncoder;
import com.sun.imageio.plugins.gif.GIFImageReader;
import com.sun.imageio.plugins.gif.GIFImageReaderSpi;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;

/**
 *
 * @author mahmoud.elsonbati@gmail.com
 */
public class MyGifUtil {
/**
     * takes an image and delay in milli sec and returns the modified image in stream 
     * @param gif
     * @param delay
     * @return 
     */
    public byte[] convertGIF(File gif, int delay)throws NullPointerException {
        if (gif==null)
            throw new NullPointerException();
        byte[] bytes = null;
        AnimatedGifEncoder e = new AnimatedGifEncoder();
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        e.start(os);
        e.setDelay(delay);   // set the delay 
        e.setRepeat(1);


        try {
            List<BufferedImage> frames = getFrames(gif);
            for (BufferedImage frame : frames) {
                e.addFrame(frame);
            }
        } catch (IOException ex) {
            Logger.getLogger(MyGifUtil.class.getName()).log(Level.SEVERE, null, ex);
        }
        e.finish();
        bytes = os.toByteArray();
        try {
            os.close();
        } catch (IOException ex) {
            Logger.getLogger(MyGifUtil.class.getName()).log(Level.SEVERE, null, ex);
        }

        /* InputStream fis = new ByteArrayInputStream(os.toByteArray());
        bytes = new byte[os.toByteArray().length];
        try {
        os.flush();
        fis.read(bytes);
        } catch (IOException ex) {
        Logger.getLogger(MyGifUtil.class.getName()).log(Level.SEVERE, null, ex);
        }
         */
        return bytes;
    }
    /**
     * modify the delay of a given gif and save it to another file
     * @param gifIn
     * @param gifOut
     * @param delay 
     */
    public void convertGIF(String gifIn ,String gifOut ,int delay){
        
        AnimatedGifEncoder e = new AnimatedGifEncoder();
       
        e.start(gifOut);
        e.setDelay(delay);   // set the delay 
        e.setRepeat(1);
        try {
            List<BufferedImage> frames = getFrames(new File(gifIn));
            for (BufferedImage frame : frames) {
                e.addFrame(frame);
            }
        } catch (IOException ex) {
            Logger.getLogger(MyGifUtil.class.getName()).log(Level.SEVERE, null, ex);
        }
        e.finish();

    }

    /**
     * retrieve the frames of the given gif image
     * @param args the command line arguments
     */
    private List<BufferedImage> getFrames(File gif) throws IOException {

        ArrayList<BufferedImage> frames = new ArrayList<BufferedImage>();
        ImageReader ir = new GIFImageReader(new GIFImageReaderSpi());
        ir.setInput(ImageIO.createImageInputStream(gif));

        for (int i = 0; i < ir.getNumImages(true); i++) {
            frames.add(ir.read(i));
        }


        return frames;
    }

    public static void main(String[] args) {
        System.out.println(
                new MyGifUtil().convertGIF(new File("c:/x.gif"), 100).length);


    }
}

Comments

Popular posts from this blog

itext 2.7.1 writing Arabic and English content in a PDF file

   public void createPdf(String filename) throws IOException, DocumentException {               Document document = new Document();           PdfWriter.getInstance(document, new FileOutputStream(filename));             document.open();             document.add(Chunk.NEWLINE);        FontFactory.register("c:/windows/fonts/tradbdo.ttf", "my_arabic");               Font myArabicFont = FontFactory.getFont("my_arabic" ,BaseFont.IDENTITY_H, BaseFont.EMBEDDED);         PdfPTable table = new PdfPTable(1);         table.getDefaultCell().setNoWrap(false);        // table.setRunDirection(PdfWriter.RUN_DIRECTION_RTL);         PdfPCell text = new PdfPCell(new Phrase("محمود السنباطيthis is أبتثجحخدرزسشصضطظعغفقكلمنهوى", myArabicFont));         text.setRunDirection(PdfWriter.RUN_DIRECTION_RTL);          text.setNoWrap(false);          table.addCell(text);     //Add the table to the document         document.add(table);                  

Installing liferay 6.2 on wildfly 10 app server and oracle 11g database & windows machine

*************************************DATABASE CREATION*********************************************************************************************** DOWNLOAD LIFERAY PORTAL SCRIPTS FROM https://www.liferay.com/downloads/liferay-portal/available-releases Rename the file as liferay.sql put it let say in under c drive , so it will be located like this  c:\liferay.sql from cmd dir c:\ SQLPLUS / AS SYSDBA @liferay.sql lportal lportal it will create the db ..after finishing go to sqlplus again to ggrant the below  to lportal user SQLPLUS / AS SYSDBA grant create session to lportal; grant connect to lportal; grant resource to lportal; *******************************CONFIGURE WILDFLY TO CONNECT TO ORACLE DB *****************************************************************************************************  configure wildfly to connect to oracle db Download the driver: ojdbc[VERSION].jar Create subfolders [WILDFLY_HOME]/modules/system/layers/base/com/oracle/main/ C

Fast Download with progress indication facility using Java NIO

package test; import java.io.FileOutputStream; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; import java.nio.ByteBuffer; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; import java.util.Date; public class DownloadProgressExample {     public static void main( String[] args ) {         new Downloader( "c:/header12.jpg", "http://www.daralshifa.com/images/mainheader/header12.jpg" );     }     private interface RBCWrapperDelegate {          // The RBCWrapperDelegate receives rbcProgressCallback() messages         // from the read loop.  It is passed the progress as a percentage         // if known, or -1.0 to indicate indeterminate progress.         //         // This callback hangs the read loop so a smart implementation will         // spend the least amount of time possible here before returning.         //         // One possible implementation is to push the progress message         // atomic