Home > Articles > Programming > User Interface (UI)

  • Print
  • + Share This
Like this article? We recommend

Blending Slides

Although Blender1 and Blender2 let you experience image blending via both techniques, neither offers the best venue for demonstrating this transition effect's usefulness. For this reason, I've created a SlideShow application that employs blending to transition from one slide to the next. Check out Listing 4 for this application's source code.

Listing 4 SlideShow.java.

// SlideShow.java

import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.awt.image.*;

import java.io.*;

import java.util.ArrayList;

import javax.imageio.*;

import javax.swing.*;

/**
 * This class describes and contains the entry point to the slideshow
 * application.
 */

public class SlideShow
{
  static Projector projector;

  /**
  * Create SlideShow's GUI and start the projector.
  */

  SlideShow ()
  {
   JFrame frame = new JFrame ("SlideShow 1.0");
   frame.addWindowListener (new WindowAdapter ()
                {
                  public void windowClosing (WindowEvent we)
                  {
                   projector.stop ();
                   System.exit (0);
                  }
                });

   Screen screen = new Screen (projector.getSlideWidth (),
                 projector.getSlideHeight ());
   frame.setContentPane (screen);

   frame.pack ();
   frame.setResizable (false);
   frame.setLocationRelativeTo (null); // center frame on screen
   frame.setVisible (true);

   projector.start (screen);
  }

  /**
  * Application entry point.
  *
  * @param args array of command-line arguments
  */

  public static void main (String [] args) throws IOException
  {
   if (args.length != 1)
   {
     System.err.println ("usage: java SlideShow imagesPath");
     return;
   }

   projector = new Projector (args [0]);

   Runnable r = new Runnable ()
          {
            public void run ()
            {
             new SlideShow ();
            }
          };
   EventQueue.invokeLater (r);
  }
}

/**
 * This class describes the projector that runs the slideshow.
 */

class Projector implements ActionListener
{
  /**
  * Create the projector, loading images from the specified path into
  * slides.
  *
  * @param imagesPath path to images (GIFs and/or JPEGS, and/or other
  * formats)
  */

  Projector (String imagesPath) throws IOException
  {
   load (imagesPath);

   slideCount = slides.size ();

   show_timer = new Timer (SLIDE_DELAY, this);
  }

  /**
  * Callback for show_timer -- invoked approximately every SLIDE_DELAY
  * milliseconds.
  *
  * @param ae action event
  */

  public void actionPerformed (ActionEvent ae)
  {
   ActionListener fader;
   fader = new ActionListener ()
       {
         int weight = 100;

         public void actionPerformed (ActionEvent ae)
         {
           // When the projector's stop() method is invoked, it
           // stops the show_timer. However, the fade_timer will
           // continue to run until 100 steps have been completed.
           // The following if statement ensures that the fade timer
           // also stops as quickly as possible.

           if (!show_timer.isRunning ())
           {
             fade_timer.stop ();
             return;
           }

           // Because slideIndex is initialized to 1, slideIndex-1
           // results in the introductory slide being blended with
           // the first real slide of the slideshow.

           BufferedImage biSlide;
           biSlide = blend (slides.get (slideIndex-1),
                   slides.get (slideIndex), weight/100.0);

           // Project the slide onto the screen.

           screen.showSlide (biSlide);

           // Countdown until weight drops below 0. At that point,
           // the fade_timer must stop. Also, the slideshow must
           // advance to the next slide. If there are no more
           // slides, the show_timer must stop.

           if (--weight < 0)
           {
             fade_timer.stop ();

             if (++slideIndex == slideCount)
               show_timer.stop ();
           }
         }
       };

   // The following timer must finish before the next invocation of this
   // method.

   fade_timer = new Timer (FADE_DELAY, fader);
   fade_timer.start ();
  }

  /**
  * Return a slide's height -- each slide must have the same height.
  */

  int getSlideHeight ()
  {
   return slideHeight;
  }

  /**
  * Return a slide's width -- each slide must have the same width.
  */

  int getSlideWidth ()
  {
   return slideWidth;
  }

  /**
  * Start the projector.
  *
  * @param screen the display surface on which slides are projected
  */

  void start (Screen screen)
  {
   this.screen = screen;

   // Obtain introductory slide from the screen and replace null
   // placeholder with this special slide.

   slides.set (0, screen.getIntroSlide ());

   show_timer.start ();
  }

  /**
  * Stop the projector.
  */

  void stop ()
  {
   show_timer.stop ();
  }

  /**
  * Blend the contents of two BufferedImages according to a specified
  * weight.
  *
  * @param bi1 first BufferedImage
  * @param bi2 second BufferedImage
  * @param weight the fractional percentage of the first image to keep
  *
  * @return new BufferedImage containing blended contents of BufferedImage
  * arguments
  */

  private BufferedImage blend (BufferedImage bi1, BufferedImage bi2,
                double weight)
  {
   BufferedImage bi3 = new BufferedImage (slideWidth, slideHeight,
                       BufferedImage.TYPE_INT_RGB);
   Graphics2D g2d = bi3.createGraphics ();
   g2d.drawImage (bi1, null, 0, 0);
   g2d.setComposite (AlphaComposite.getInstance (AlphaComposite.SRC_OVER,
                          (float) (1.0-weight)));
   g2d.drawImage (bi2, null, 0, 0);
   g2d.dispose ();

   return bi3;
  }

  /**
  * Load all images from a specific directory. Each image is converted into
  * a slide.
  *
  * @param imagesPath path to images directory
  *
  * @throws IOException imagesPath represents a file, an image cannot be
  * read, an image's width doesn't match the slide width (or the height
  * doesn't match the slide height), or fewer than two images are loaded
  */

  private void load (String imagesPath) throws IOException
  {
   File imageFilesPath = new File (imagesPath);
   if (!imageFilesPath.isDirectory ())
     throw new IOException (imagesPath+" identifies a file");

   slides = new ArrayList<BufferedImage> ();

   // To simplify the previous action listener, a null placeholder for the
   // screen's introductory slide is added to the slides array list via the
   // following method call. This placeholder is replaced with the actual
   // introductory slide during the projector's start() method call.

   slides.add (null);

   File [] imageFiles = imageFilesPath.listFiles ();
   for (File imageFile: imageFiles)
   {
      // Skip subdirectories.

      if (imageFile.isDirectory ())
        continue;

      // Read next image file. Skip non-image files.

      BufferedImage slide = ImageIO.read (imageFile);
      if (slide == null)
        continue;

      // Capture initial slide width and height as standard slide width
      // and height.

      if (slideWidth == 0)
      {
        slideWidth = slide.getWidth ();
        slideHeight = slide.getHeight ();
      }

      // All slides must have the same width and height.

      if (slide.getWidth () != slideWidth ||
        slide.getHeight () != slideHeight)
        throw new IOException ("slide width/height does not match "+
                   "widths/heights of previous slides");

      slides.add (slide);
   }

   if (slides.size () < 2)
     throw new IOException ("at least one image must be loaded");
  }

  final static int FADE_DELAY = 10;

  final static int SLIDE_DELAY = 4500;

  private ArrayList<BufferedImage> slides;

  private int slideHeight, slideCount, slideIndex = 1, slideWidth;

  private Screen screen;

  private Timer fade_timer, show_timer;
}

/**
 * This class creates a panel that displays each slide.
 */

class Screen extends JPanel
{
  /**
  * Create the screen with a specified size. Also create an introductory
  * slide, which the projector later acquires at startup.
  *
  * @param width screen's preferred width
  * @param height screen's preferred height
  */

  Screen (int width, int height)
  {
   size = new Dimension (width, height);

   biIntroSlide = new BufferedImage (width, height,
                    BufferedImage.TYPE_INT_RGB);
   Graphics2D g2d = biIntroSlide.createGraphics ();
   g2d.setColor (Color.white);
   g2d.fillRect (0, 0, width, height);
   g2d.setRenderingHint (RenderingHints.KEY_ANTIALIASING,
              RenderingHints.VALUE_ANTIALIAS_ON);

   g2d.setFont (new Font ("Arial", Font.BOLD | Font.ITALIC, 36));
   FontMetrics fm = g2d.getFontMetrics ();
   Rectangle2D r2d = fm.getStringBounds (TITLE, g2d);
   int text_width = (int)((Rectangle2D.Float) r2d).width;
   int text_height = fm.getHeight ();

   g2d.setColor (Color.black);
   g2d.drawString (TITLE, (width-text_width)/2+SHADOW_OFFSET,
           height/2+SHADOW_OFFSET);

   g2d.setColor (Color.blue);
   g2d.drawString (TITLE, (width-text_width)/2, height/2);
   g2d.dispose ();
  }

  /**
  * Return the introductory slide.
  */

  BufferedImage getIntroSlide ()
  {
   return biIntroSlide;
  }

  /**
  * Make the screen's preferred size available to the windowing toolkit for
  * layout.
  */

  public Dimension getPreferredSize ()
  {
   return size;
  }

  /**
  * Paint the screen.
  *
  * @param g graphics context used to performing painting
  */

  public void paintComponent (Graphics g)
  {
   Graphics2D g2d = (Graphics2D) g;

   // The screen will appear before the projector starts running. Because
   // there is no regular slide at this point, the contents of the
   // introductory slide will be displayed. The introductory slide will
   // eventually fade out and the first projector slide will fade in.

   if (biSlide != null)
     g2d.drawImage (biSlide, null, 0, 0);
   else
     g2d.drawImage (biIntroSlide, null, 0, 0);
  }

  /**
  * Display the next slide.
  *
  * @param biSlide next slide to be presented on the screen
  */

  void showSlide (BufferedImage biSlide)
  {
   this.biSlide = biSlide;
   repaint ();
  }

  final static int SHADOW_OFFSET = 3;

  final static String TITLE = "SlideShow 1.0";

  private BufferedImage biSlide, biIntroSlide;

  private Dimension size;
}

Listing 4 presents a SlideShow class that models a slideshow in terms of Projector and Screen classes—a projector loads images from a specific directory, and then projects them successively onto the screen. Furthermore, this listing refers to images that will be projected (and that have the same size) as slides.

SlideShow first verifies at least one command-line argument (identifying a directory that contains image files), and then creates a projector. In turn, the project loads these images and stores them in an array of BufferedImages. The application then creates the GUI, consisting of a Screen component, and finally starts and identifies the screen to the projector.

The projector-starting method obtains the first slide from the screen and makes sure that it's the first slide to be displayed—the screen's constructor draws an introductory message onto a BufferedImage and also displays this image at startup. This way, the first blending transition will blend the first loaded image with the introductory message, completely replacing this message by the end of the transition.

Moving on, Projector's start() method creates and starts a timer to begin the slideshow. Each timer tick causes the timer's action listener to be invoked, which creates and starts a separate timer, to manage a blending transition from a given slide being completely displayed to the next slide being completely displayed. Both timers stop after the last slide has been completely displayed.

  • It's not necessary (and a potential performance problem) for Projector's blend() method to create a new BufferedImage to hold the blended image each time blend() is invoked. Instead, you could create the BufferedImage in Projector's constructor, and reference this image from within blend().
  • Projector's load() method throws an exception when it encounters an image whose width or height differs from the standard slide width and height (which are set to the dimensions of the first loaded image). You might consider automatically resizing a loaded image to the slide width and height, instead of throwing this exception.
  • Apart from unnecessary BufferedImage creation in the blend() method, SlideShow is a memory hog: It loads all images into memory. If there's not enough virtual machine heap memory to store these images, the virtual machine will indicate an out-of-memory error. You could overcome this problem by loading images on demand, instead of all at once.

After compiling SlideShow.java, run this application with a single command-line argument that identifies a directory containing at least one image file. For example, java SlideShow images assumes that the current directory contains an images subdirectory. In Figure 2, SlideShow's GUI displays its introductory slide.

Figure 2

Figure 2 The introductory slide presents a startup message.

  • + Share This
  • 🔖 Save To Your Account

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020