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

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/o...

windows 7 fix "user profile has failed and loading the default profile"

thanks to microsoft support i fixed that issue in my windows 7 link   http://support.microsoft.com/kb/947215 Symptoms When you log on to a Windows 7-based or a Windows Vista-based computer by using a temporary profile, you receive the following error message: The User Profile Service failed the logon. User profile cannot be loaded. Back to the top  |  Give Feedback Resolution Occasionally, Windows might not read your user profile correctly, such as if your antivirus software is scanning your computer while you try to log on. Before you follow the methods here, try restarting your computer and logging on with your user account again to resolve the issue. If you restart your computer and it does not resolve this issue, use the following methods to resolve this issue. Note  You must be able to log on to an administrator account to fix your user profile or copy your data to a new account. Before you resolve the issue, log on to Windows by u...

oracle drop all tables and sequences in a certain schema

--  please never put a comment starting with " / "  as this character means execute the previous line  BEGIN   FOR i IN (SELECT us.sequence_name               FROM USER_SEQUENCES us) LOOP     EXECUTE IMMEDIATE 'drop sequence '|| i.sequence_name ||'';   END LOOP;     FOR i IN (SELECT ut.table_name               FROM USER_TABLES ut) LOOP     EXECUTE IMMEDIATE 'drop table '|| i.table_name ||' CASCADE CONSTRAINTS ';   END LOOP; END; -- the following character executes the whole block of pl sql code /