logbitup.gif (360 bytes)

 Curso JAVA 
 Unidad 11: "
Imágenes y sonido"

logbitdn.gif (787 bytes)

  www.bit.es - Calendario de cursos - Solicitud de información

Curso Java
Curso Analista Programador entorno Java

 
Objetivos de la Unidad:


1.- Cargar mostrar y tratar una imagen

import java.applet.Applet;
import java.awt.*;

public class LoadImageAndScale extends Applet
{
   private Image img;

   // carga la imagen cuando el applet empieza la ejecución
   public void init()
   {
      img = getImage( getDocumentBase(), "imagen.gif" );
   }

   // muestra la imagen
   public void paint( Graphics g )
   {
      // dibuja la imagen original
      g.drawImage( img, 1, 1, this );

      // dibuja con el doble de tamaño
      int width = img.getWidth( this );
      int height = img.getHeight( this );
      g.drawImage( img, 1, 90, width * 2, height * 2, this );
   }
}

HTML asociado:

<html>
<applet code="LoadImageAndScale.class" width=325 height=250>
</applet>
</html>
 

En el caso de querer cargar una imagen (tanto gif como jpeg) del sistema local de archivos img se puede obtener así tanto en un Frame como en un Servlet:

    img = Toolkit.getDefaultToolkit().getImage("imagen.gif");

Sin embargo para un Frame bastaría con:

    img = getToolkit().getImage("imagen.gif");

Y si lo que se quiere es personalizar el icono de la ventana éste puede establecerse con el método de Frame

     setIconImage("icono.gif")


donde la imagen debe ser de 16 x 16 pixels


A continuación se muestran un par de ejemplos que muestran como crear y/o modificar una imagen en memoria.

//
// GFromImg.java
//
//
// Modificación de la imagen mediante el el contexto de dispositivo
// utilizando el objeto Graphics de la Java API
//

import java.awt.*;
import java.awt.event.*;
import java.applet.*;

public class GFromImg extends Applet
{
  Image img = null;
  Image img2 = null;

  public void init()
  {
    try
    {
      img = getImage(getDocumentBase(), "foto.gif");

      // Las tres líneas siguientes garantizan la carga completa
      // de la omagen
      MediaTracker t = new MediaTracker(this);
      t.addImage(img, 0);
      t.waitForID(0);

      Dimension d = size(); // Obtiene las dimensiones del área cliente del applet
      img2 = createImage(d.width, d.height);

      Graphics gImg = null;

      gImg = img2.getGraphics();

      gImg.drawImage(img, 0, 0, null);
      gImg.setColor(Color.blue);
      gImg.fillRect(0,0,100,100);

      gImg.setColor(Color.red);
      gImg.drawString("Demo de double buffering", 10, 30);
    }

    catch (Exception e) {}
}

  public void paint(Graphics g)
  {
    g.drawImage(img2, 0, 0, null);
  }
}
 
 

//
// GFromImgPixels.java
//
// Modificación de la imagen modificando directamente
// su matriz de pixels
//

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

public class GFromImgPixels extends Applet
{
  Image img, img2;
  int iw, ih;
  int pixels[];

  public void init()
  {
    try
    {
      img = getImage(getDocumentBase(), "foto.gif");

      // Las tres líneas siguientes garantizan la carga completa
      // de la omagen
      MediaTracker t = new MediaTracker(this);
      t.addImage(img, 0);
      t.waitForID(0);

      iw = img.getWidth(null);
      ih = img.getHeight(null);
      pixels = new int[iw * ih];
      PixelGrabber pg = new PixelGrabber(img, 0, 0, iw, ih, pixels, 0, iw);
      pg.grabPixels();

      // Modificación imagen modificando directamente el array de pixels

      for(int y = 30; y < 50; y++)
      {
        for(int x = 20; x < 75; x++)
        {
          int r, g, b;
          r = 0xFF;
          g = 0xFF;
          b = 0xFF;

          pixels[x + y*iw] = (255 << 24) | (r << 16) | (g << 8) | b;
        }
      }

      img2 = createImage(new MemoryImageSource(iw, ih, pixels, 0, iw));
    }
    catch (InterruptedException e){};
  }

  public void paint(Graphics g)
  {
    g.drawImage(img2, 0, 0, null);
  }
}
 

Una aplicación directa de ello es generar imágenes "on the fly" desde un servlet. Para ello hay que utilizar un cofidicador según el formato de imagen que se quiera. Una opción es utilizar la clase GifEncoder.java, obtenible en www.acme.com.
Para generar la imagen habría que añadir:

      FileOutputStream fOut = new FileOutputStream("newfoto.gif");
      GifEncoder genc = new GifEncoder(img2, fOut);
      genc.encode();
      fOut.close();
 

1.1.- Cargar y reproducir una imagen en un canvas

Este ejemplo muestra cómo utilizar los canvas tanto como para contener una imagen como para generar gráficos por código.
Así mismo también se muestra la utilización de las inner classes, así como el GridLayout y el centrado de la ventana.
La imagen utilizada en el ejemplo es
duke.gif

package mosaico;

import java.awt.*;
import java.awt.event.*;

public class Frame1 extends Frame
{
  GridLayout gridLayout1 = new GridLayout();
  Pizarra pizarra1 = new Pizarra();
  Imagen imag = new Imagen("duke.gif");

  public Frame1()
  {
    try
    {
      jbInit();
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
  }

  public static void main(String[] args)
  {
    Frame1 f = new Frame1();
    f.centra();
    f.setVisible(true);
  }

  private void jbInit() throws Exception
  {
    this.setBackground(new Color(192, 192, 216));
    this.setSize(new Dimension(355, 172));
    gridLayout1.setHgap(30);
    gridLayout1.setColumns(2);
    this.setLayout(gridLayout1);
    this.add(imag);
    this.add(pizarra1);

    this.addWindowListener(new java.awt.event.WindowAdapter()
    {
      public void windowClosing(WindowEvent e)
      {
        this_windowClosing(e);
      }
    });
  }

  void this_windowClosing(WindowEvent e)
  {
    System.exit(0);
  }

  class Pizarra extends Canvas
  {
    Font f = new Font("SansSerif", Font.BOLD|Font.ITALIC, 16);

    Pizarra()
    {
      setBackground(Color.white);
    }

    public void paint(Graphics g)
    {
      g.setColor(Color.blue);
      g.setFont(f);
      g.drawString("Hola", 20, 20);
      g.setColor(Color.red);
      g.drawLine(30, 30, 100, 100);
    }
  }

  public void centra()
  {
    int anchoPantalla = getToolkit().getScreenSize().width;
    int altoPantalla = getToolkit().getScreenSize().height;

    int anchoVentana = getSize().width;
    int altoVentana = getSize().height;

    setLocation( (anchoPantalla - anchoVentana) / 2, (altoPantalla - altoVentana) / 2);
  }

  class Imagen extends Canvas
  {
    Image img;

    Imagen(String fichero)
    {
      setBackground(Color.yellow);
      img = getToolkit().getImage(fichero);
    }

    public void paint(Graphics g)
    {
      // Tamaño fijo
      // g.drawImage(img, 10, 20, this);

      // Tamaño ajustable al tamaño del canvas
      g.drawImage(img, 10, 20,
      this.getSize().width - 20, this.getSize().height - 40, this);
    }
  }
}

El aspecto del programa al ejecutarse es:

 

En el ejemplo anterior se comparan dos canvas: uno con primitivas de dibujo y otro con una imagen. Para este último vamos a crear un bean reutilizable que podamos incorporar en la paleta de componentes y que visualize una imagen de tamaño autoajustable:

import java.awt.*;

public class ImageBean extends Panel
{
  BorderLayout borderLayout1 = new BorderLayout();
  CanvasImagen imag = new CanvasImagen();
  Image img;
  String fichero;

  public ImageBean()
  {
    try
    {
      jbInit();
    }
    catch (Exception ex)
    {
      ex.printStackTrace();
    }
  }

  private void jbInit() throws Exception
  {
    this.setLayout(borderLayout1);
    this.add(imag, BorderLayout.CENTER);
  }

  public void setFichero(String newFichero)
  {
    fichero = newFichero;
    img = Toolkit.getDefaultToolkit().getImage(fichero);
  }

  public String getFichero()
  {
    return fichero;
  }

  class CanvasImagen extends Canvas
  {
    public void paint (Graphics g)
    {
      if (img != null)
      {
        g.drawImage(img, 0, 0, this.getSize().width, this.getSize().height, this);
      }
    }
  }
}

2.- Cargar y reproducir un sonido

// Carga un clip de audio y lo reproduce
import java.applet.*;
import java.awt.*;

public class LoadAudioAndPlay extends Applet
{
   private AudioClip sound;
   private Button playSound, loopSound, stopSound;

   // carga el sonido al ejecutar el applet
   public void init()
   {
      sound = getAudioClip( getDocumentBase(), "sonido.au" );
      playSound = new Button( "Play" );
      loopSound = new Button( "Loop" );
      stopSound = new Button( "Stop" );
      add( playSound );
      add( loopSound );
      add( stopSound );
   }

   public boolean action( Event e, Object o )
   {
      if ( e.target == playSound )
         sound.play();
      else if ( e.target == loopSound )
         sound.loop();
      else if ( e.target == stopSound )
         sound.stop();

      return true;
   }
}

HTML asociado:

<html>
<applet code="LoadAudioAndPlay.class" width=275 height=30>
</applet>
</html>
 

3.- Applet de un mapa sensible:
 

// Demonstración de un image map.
import java.awt.*;
import java.applet.Applet;

public class ImageMap extends Applet
{
   Image mapImage;
   MediaTracker trackImage;
   int width, height;

   public void init()
   {
      trackImage = new MediaTracker( this );
      mapImage = getImage( getDocumentBase(), "mapa.gif" );
      trackImage.addImage( mapImage, 0 );

      try
      {
         trackImage.waitForAll();
      }
      catch( InterruptedException e ) { }

      width = mapImage.getWidth( this );
      height = mapImage.getHeight( this );
      resize( width, height );
   }

   public void paint( Graphics g )
   {
      g.drawImage( mapImage, 0, 0, this );
   }

   public boolean mouseMove( Event e, int x, int y )
   {
      // aquí se puede procesar según las coordenadas
      // al igual que el click
      showStatus( "x: " + x + ", y: " + y );
      return true;
   }

   public boolean mouseExit( Event e, int x, int y )
   {
      showStatus( "Punto fuera del ImageMap applet" );
      return true;
   }
}

HTML asociado:

<html>
<applet code="ImageMap.class" width=400 height=400>
</applet>
</html>
 


Unidad anterior - Unidad siguiente