Animated GIF image gets distorted while playing.

Hi,
I have some animated gif images which I need to show in a jLabel and a jTextPane. But some of these images are getting distorted while playing in the two components, though these images are playing properly in Internet Explorer. I am using the methods insertIcon() of jTextPane and setIcon() of jLabel to add or set the gif images in the two components. Can you please suggest any suitable idea of how I can get rid of this distortion? Thanks in advance.

In the code below is a self contained JComponent that paints a series of BufferedImages as an animation. You can pause the animation, and you specify the delay. It also has two static methods for loading all the frames from a File or a URL.
Feel free to add functionality to it, like the ability to display text or manipulate the animation. You may wan't the class to extend JLabel instead of JComponent. Just explore around with the painting. If you have any questions, then feel free to post.
The downside to working with an array of BufferedImages, though, is that they consume more memory then a single Toolkit gif image.
import javax.swing.JComponent;
import java.awt.image.BufferedImage;
import java.awt.Graphics;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
public class JAnimationLabel extends JComponent {
    /**The default animation delay.  100 milliseconds*/
    public static final int DEFAULT_DELAY = 100;
    private BufferedImage[] images;
    private int currentIndex;
    private int delay;
    private boolean paused;
    private boolean exited;
    private final Object lock = new Object();
    //the maximum image width and height in the image array
    private int maxWidth;
    private int maxHeight;
    public JAnimationLabel(BufferedImage[] animation) {
        if(animation == null)
            throw new NullPointerException("null animation!");
        for(BufferedImage frame : animation)
            if(frame == null)
                throw new NullPointerException("null frame in animation!");
        images = animation;
        delay = DEFAULT_DELAY;
        paused = false;
        for(BufferedImage frame : animation) {
            maxWidth = Math.max(maxWidth,frame.getWidth());
            maxHeight = Math.max(maxHeight,frame.getHeight());
        setPreferredSize(new java.awt.Dimension(maxWidth,maxHeight));
    //This method is called when a component is connected to a native
    //resource.  It is an indication that we can now start painting.
    public void addNotify() {
        super.addNotify();
        //Make anonymous thread run animation loop.  Alternative
        //would be to make the AnimationLabel class extend Runnable,
        //but this would allow innapropriate use.
        exited = false;
        Thread runner = new Thread(new Runnable() {
            public void run() {
                runAnimation();
        runner.setDaemon(true);
        runner.start();
    public void removeNotify() {
        exited = true;
        super.removeNotify();
    /**Returns the animation delay in milliseconds.*/
    public int getDelay() {return delay;}
    /**Sets the animation delay between two
     * consecutive frames in milliseconds.*/
    public void setDelay(int delay) {this.delay = delay;}
    /**Returns whether the animation is currently paused.*/
    public boolean isPaused() {
        return exited?true:paused;}
    /**Makes the animation paused or resumes the painting.*/
    public void setPaused(boolean paused) {
        synchronized(lock) {
            this.paused = paused;
            lock.notify();
    private void runAnimation() {
        while(!exited) {
            repaint();
            if(delay > 0) {
                try{Thread.sleep(delay);}
                catch(InterruptedException e) {
                    System.err.println("Animation Sleep interupted");
            synchronized(lock) {
                while(paused) {
                    try{lock.wait();}
                    catch(InterruptedException e) {}
    public void paintComponent(Graphics g) {
        if(g == null) return;
        java.awt.Rectangle bounds = g.getClipBounds();
        //center image on label
        int x = (getWidth()-maxWidth)/2;
        int y = (getHeight()-maxHeight)/2;
        g.drawImage(images[currentIndex], x, y,this);
        if(bounds.x == 0 && bounds.y == 0 &&
           bounds.width == getWidth() && bounds.height == getHeight()) {
             //increment frame for the next time around if the bounds on
             //the graphics object represents a full repaint
             currentIndex = (currentIndex+1)%images.length;
        }else {
            //if partial repaint then we do not need to
            //increment to the the next frame
}

Similar Messages

  • Problem with animated gif image getting displayed

    My problem is that my animated image does not get displayed properly. I am extending JButton and the button already contains a static image. I want to display the animated image over the static one for some reason. If I replace the animated image with a static gif, then there is no problem.
    Here is the code that I am using
    Icon anim = new ImageIcon((new ImageLoader()).getImage("/graphics/busy.gif"));
    // thread to call displayAnim method
    class ColorThread extends Thread {
    ColorThread() {
    public void run() {
    while (AnimFlag) {
    try {
    displayAnim();
    Thread.sleep(400);
    } catch (InterruptedException e) {
    public void displayAnim()
    repaint();
    public void paint(Graphics g)
    super.paint(g);
    int x=5;
    int y=0;
    if ( AnimFlag) {
    anim.paintIcon(this,g,x,y);

    This code is working fine for JRE 1.2 and the animation is displayed. The problem is with JRE 1.3. when there is no animation, neither is there any image getting displayed.

  • Animated gif changes color palette while playing

    Hi everyone,
    I've been creating animted gifs using Matlab and the ImageMagick suite (convert). If I open the gifs in Preview, the color comes out fine in each frame; however i I use Quicktime (which is necessary, that's what we use for presentations) the color palette will change as the frames play.
    I just got the newest version of Quicktime, hoping that it would solve the problem, but it didn't. Any ideas?

    I'm not familiar to the software but I can guess what is happening.
    Too many colors. A GIF is 8 bit (256 colors) but some of them are not used by all software. Windows and Mac's are different.
    Does the software offer a way to reduce the number of colors used? Can you get it down to 8 bit? Can you discard unused colors with some other software?
    Have you considered building an image sequence movie? These allow many different images formats and support up to 32 bit formats (millions of colors).
    QuickTime Pro ($30) can import a series of images as a movie. The file size is much smaller than any video format used today (just the total of the images file size).

  • Problem at displaying animated gif images !!!!!!!!!!!!

    hello everyone......i am trying to display an animated gif image..............so till far i have no issues on this....
    but i face problem when :
    i have created a class called SimpleGame which extends JPanel....
    public class SimpleGame extends JPanel
    //code
    public void paintComponent(Graphics g)
    //code to draw image
    }now i have written another class with main method
    public class MyGame extends SimpleGame
    public MyGame()
            JFrame frame=new JFrame();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(800, 600);
            frame.setUndecorated(true);
            frame.setLocationRelativeTo(null);
            frame.getContentPane().add(this);
            frame.setVisible(true);
            this.repaint();
    }so image gets displayed but only one frame of animated image......image that is displayed is static.....since it is a animated gif,,,,,so some how animation is not rendered......only one frame is displayed......
    why is it happening ??
    if i try to display animated image from a single class i mean my paintComponent method and main method is at same class then i do not face problem.....
    but if my paint method is in another class and i am using that method from another class then animation does not get rendered.........
    any help !!!!! please...........

    class SimpleGame extends JPanel
    Image img=new ImageIcon("y.gif");
    public void paintComponent(Graphics g)
    g.drawImage(img,150,150,this);
    }main class//
    class MyGame extends SimpleGame
    public MyGame()
            JFrame frame=new JFrame();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(800, 600);
            frame.setUndecorated(true);
            frame.setLocationRelativeTo(null);
            frame.getContentPane().add(this);
            frame.setVisible(true);
            this.repaint();
    public static void main(String[] args)
    new MyGame();
    }my image gets displayed.......but only single frame of a animated image....animation is not happening..........

  • Where can I find video training to make animated GIF images?

    I would like to get more info on how to make animated GIF images with my Photoshop for my WordPress blog here  http://www.getfreewordpressthemesnow.com

    Hello Bill,
    you could have a look at http://helpx.adobe.com/photoshop/using/creating-frame-animations.html >>> ... till save the animation
    and at the end: Adobe also recommends >>> http://helpx.adobe.com/photoshop/using/saving-files-graphics-formats.html#save_in_gif_form at
    If the German language is no problem for you, you could use http://praxistipps.chip.de/photoshop-animiertes-gif-erstellen_1485
    Hans-Günter

  • Animated Gif Image does not render correctly on screen

    I have added animated gif image to the scene it does not render correctely.it shakes on the screen. plz give me any suggestion
    i use following code
    Image logo= new Image(getClass().getResourceAsStream("images/image.gif"));
    logoLabel.setGraphic(new ImageView(logo));

    Hello user,
    I think gif are rendered smoothly.
    Are you sure you are not making many object of same images everytime?
    Thanks.
    Narayan

  • Animated gif image

    Hi
    I like to create an animated gif image from a given set of images with java. I like to do this with the given set of java api as I do not want to use a commercial graphics library. Can anyone provide me with a sample example.
    Thanks

    Hi
    I like to resize a gif image. Currently i am using the following code but the resized image is not smooth.
    public BufferedImage resizeImage(BufferedImage img, int newW, int newH)
              int w = img.getWidth();
              int h = img.getHeight();
              BufferedImage dimg = new BufferedImage(newW, newH, img.getType());
              Graphics2D g = dimg.createGraphics();
              g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
              g.drawImage(img, 0, 0, newW, newH, 0, 0, w, h, null);
              g.dispose();
              return dimg;
    Is there a way to resize a gif image in a smooth way as the example given in the gif4j library
    Thanks

  • Animated GIF Image on a JPanel.

    How can I display an animated GIF image on a JPanel? It should animate after displaying.
    Regards

    I think this code should display an animated GIF image on a JPanel.
    -Mani
    import javax.swing.*;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.awt.*;
    public class Animation {
    public static void main(String args[]) {
    JLabel imageLabel = new JLabel();
    JLabel headerLabel = new JLabel();
    JFrame frame = new JFrame("JFrame Animation");
    JPanel jPanel = new JPanel();
    //Add a window listner for close button
    frame.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    // add the header label
    headerLabel.setFont(new java.awt.Font("Comic Sans MS", Font.BOLD, 16));
    headerLabel.setText("Animated Image!");
    jPanel.add(headerLabel, java.awt.BorderLayout.NORTH);
    //frame.getContentPane().add(headerLabel, java.awt.BorderLayout.NORTH);
    // add the image label
    ImageIcon ii = new ImageIcon("d:/dog.gif");
    imageLabel.setIcon(ii);
    jPanel.add(imageLabel, BorderLayout.CENTER);
    frame.getContentPane().add(jPanel, java.awt.BorderLayout.CENTER);
    frame.pack();
    frame.setVisible(true);
    }

  • In Edit mode the image gets distorted as if a graphics card error...

    When I enter edit mode, many times the image gets distorted and is unrecognizable. The image is covered in red or green lines like when a driver or graphic card is having problems. I can view the image if I use the shift key or exit edit mode.
    Have the latest version of both OS and iPhoto. Am considering a complete reinstall of the OS and Software but would like to avoid if possible.

    Welcome to the Apple Discussions.
    Well you can avoid the hassle of re-installing because it won't help. This is a bug that affects some users of 10.6 and iPhoto, Aperture and/or Preview. Currently there is no solution.
    iPhoto menu -> Provide iPhoto Feedback
    and let them know that you too have the issue.
    Regards
    TD

  • When using the smart brush tool, my image gets distorted.  Is there anyway to fix this?

    When using the smart brush tool, my image gets distorted.  Is there anyway to fix this?

    What preset have you selected?
    Can you post a screenshot showing the distortion.
    Cheers,
    Neale
    Insanity is hereditary, you get it from your children
    If this post or another user's post resolves the original issue, please mark the posts as correct and/or helpful accordingly. This helps other users with similar trouble get answers to their questions quicker. Thanks.

  • Hi, I have downloaded some avi files and mov files. i am not getting audio while playing the movie. i tried to play with iTunes, QT, DivX player. but I am getting audio in mp4 files. can u help me to fix this

    Hi, I have downloaded some avi files and mov files. i am not getting audio while playing the movie. i tried to play with iTunes, QT, DivX player. but I am getting audio in mp4 files. can u help me to fix this

    First, back up all data and then uninstall "DivX" according to the developer's instructions.
    Then try this:
    VideoLAN - Download official VLC media player for Mac OS X

  • Firefox gets Stuck while Playing Facebook Games and Working in Another Tab

    Firefox gets stuck while playing facebook games (restaurant city) and side by side working in another tab or window of firefox. Switching between tabs takes time and on facebook scrolling doesn't remain smooth it gets stuck again and again while scrolling the page.
    Also, in earlier versions it was a great feature that when once a game is loaded then when i open it second time it was loaded immediately without any complete loading but now every time you play the same game it will load completely which happens generally when we reinstall firefox so that our saved cookies gets destroyed.
    ON THE OTHER HAND OPERA 10.6 LOADS FACEBOOK GAMES SMOOTHLY NO HANGS NO STUCKS NO FREEZES EVEN DOING OTHER WORK AND THE GAME ALSO LOADS IMMEDIATELY THE NEXT TIME WHEN IT IS OPENED.
    == This happened ==
    Every time Firefox opened
    == The 3.6 versions came up

    same things happen to me also the cache system is so slow it even download the flash player game after 3 or 4 days completely and hang is always the error when ever i use the fire fox also there is one more thing some time computer is not opening any site what ever u type mozilla is disconnected from IP what ever he issue is but if u close the firefox and start again it is working for a while after some time it may happen again time is not counted over this matter so i m sure this is the trouble from fire fox coz other browsers are working in the same time while mozila sucks

  • My iphone 6 is getting stucked while playing music and the voice getting down in between

    My iphone 6 is getting stucked while playing music and the voice getting down in between

    Hi Nision,
    The webpage linked below provides details on how to set up service for your iPhone.
    Service Answer Center - iPhone
    http://support.apple.com/kb/index?page=servicefaq&product=iphone
    Sincerely,
    Allen

  • How combine a jpeg image & animated gif image & save  it as GIF ?

    i have an jpeg image, & also aminated gif image, how do i place the animated gif image over (in the center of the image) a jpeg image & save it as gif file ??

    First thing you need to do is stop thinking in terms of file formats once the files are in photoshop they are all the same. The exception being vector vs raster. But in this instance the process is rteally the same so 6 on one hand a half a dozen on the other. Or as some would say Tomatoe, tomahtoe(mispelled on purpose).
    The jpeg I would assume is the background image and the gif image is the fore ground object. Open the jpeg, and then place the gif file. As long as the fore ground object has transparency, your job is pretty much done. If not, then it will be up to you to mask what you want to keep vs what you don't and apply that selection to the foregrounds layer as a mask.
    Google the net or skim the users manual for the keywords - mask, selections, quickmask, pen tool, paths. Each of these can in one way or another take care of your issue.
    It would be worth your time to also go through the numerous videos about photoshop and see how its done.
    Either go to adobe tv,
    Itunes podcasts
    or one of the following web sites:
    http://kelbytv.com/
    http://creativesuitepodcast.com/

  • I finished making an animated .gif image in FireWorks. My question is, how do I convert it into video so that when I edit video, that every video editing program recognizes it? Long story short, How do I convert animated .gif files into video formats?

    I worked in Adobe FireWorks to make the animated .gif. What program do I use to convert the file from .gif to any video format: .mp4, .m4v, .avi, .wmv, etc. I want to convert it into video format, so that QuickTime Player plays the video, I can insert it into iMovie '11 and edit, and also insert it into Final Cut Pro X and edit video.

    Thanks for getting back with me so promptly.  It has taken me this time to connect with the proper people to find out the information you requested.
    The camera used to film the class was a Panasonic AG-HMC40P, owned by a local cable TV station; they use Kodak video encoding software, and a SD card was used to store the video.   The file extension is .mts, and the mime file is MPEG 2 transport.  He said I probably need an AVCHD converter, and the Mac app store lists 8 of those options, 4 free and 4 for up to $9.99.  He said I'll also need a converter for later plans of posting on YouTube or on the website, and while some of those in the app store might work for the later needs, he knows one app called "Compressor" that would work for the uploading later.  He also suggested I could try renaming the .mts file to .MP2T, but he wasn't sure that would work.
    They don't work with Macs at the studio, but I had thought I could have some lessons there in editing, and apply what I learned to my iMac and iMovie.
    First, though, I have to be able to see it and review it!
    Thanks again!

Maybe you are looking for

  • How will the Apple iMessage work?

    Hello everyone!!!!! I am just wondering how the imessage will work?  Will there be a user name/password? Do I need to have my iphone contacts mobile number listed under "iPhone" vs. "mobile" ? I contacted Apple last night but they are very closed mou

  • IPod distortion issues following PC upgrade

    I had to replace my PC in a hurry when the hard drive died, so bought a Packard Bell Windows 7 beastie. Yeah, laugh it up. The first time I synced my iPod (an 8GB second generation Nano, a little over three years old) everything worked perfectly, wit

  • Can`t open any DVD files, not playing CD's and DVD's

    Ok, about a week ago I left my MacBook with a music CD playing. When I returned, my MacBook didn't showed the cd. I've tried ejecting the disc and playing it again, but it seemed that computers always have something against me! Now, after too much at

  • P67A-G45 3T drive only formatting to 746Gig

    P67A-G45 3T drive only formatting to 746Gig Converted partition to GPT, still 746Gig.  Saw other posts for firmware update to UEFI, but could not find that in my downloads for this motherboard.  About a year ago I updated my BIOS, and Live 6 Utility

  • Log archieving off

    how to make log archieving on from off status