Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Imágenes
En esta parte del tutorial Java 2D, trabajaremos con imágenes.
BufferedImagees una clase fundamental para trabajar con imágenes en Java 2D. Es un rectángulo de
píxeles almacenados en la memoria.
DisplayImageEx.java
paquete com.zetcode;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
Superficie pública () {
cargar imagen();
setSurfaceSize ();
}
zetcode.com/gfx/java2d/java2dimages/ 1/15
26/9/2019 Imágenes en Java 2D
@Anular
public void paintComponent (Gráficos g) {
super.paintComponent (g);
doDrawing (g);
}
}
DisplayImageEx público () {
initUI ();
}
paquete();
setTitle ("Hongos");
setLocationRelativeTo (nulo);
setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
}
En el ejemplo, mostramos una imagen en el panel. El tamaño de la ventana se ajusta al tamaño de la image
Usamos la ImageIconclase para cargar la imagen. La imagen se encuentra en el directorio de trabajo actua
zetcode.com/gfx/java2d/java2dimages/ 2/15
26/9/2019 Imágenes en Java 2D
We determine the size of the loaded image. With the setPreferredSize() method, we set the preferred
size of the Surface panel. The pack() method of the JFrame container will cause the frame to fit the size o
its children. In our case the Surface panel. As a consequence, the window will be sized to exactly display th
loaded image.
The image is drawn on the panel using the drawImage() method. The last parameter is the ImageObserve
class. It is sometimes used for asynchronous loading. When we do not need asynchronous loading of our
images, we can just put null there.
The pack() method sizes the container to fit the size of the child panel.
Grayscale image
In computing, a grayscale digital image is an image in which the value of each pixel is a single sample, that
is, it carries the full (and only) information about its intensity. Images of this sort are composed exclusively
of shades of neutral gray, varying from black at the weakest intensity to white at the strongest. (Wikipedia)
GrayScaleImage.java
package com.zetcode;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
zetcode.com/gfx/java2d/java2dimages/ 3/15
26/9/2019 Imágenes en Java 2D
public Surface() {
loadImage();
determineAndSetSize();
createGrayImage();
}
d = new Dimension();
d.width = mshi.getWidth(null);
d.height = mshi.getHeight(null);
setPreferredSize(d);
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
doDrawing(g);
}
}
public GrayScaleImageEx() {
initUI();
}
zetcode.com/gfx/java2d/java2dimages/ 4/15
26/9/2019 Imágenes en Java 2D
pack();
setTitle("GrayScale image");
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
GrayScaleImageEx ex = new GrayScaleImageEx();
ex.setVisible(true);
}
});
}
}
There are several ways to create a grayscale image. We do it by writing image data into buffered image of
BufferedImage.TYPE_BYTE_GRAY type.
g2d.dispose();
Graphics objects created with createGraphics() method should be manually released. Graphics objects
which are provided as arguments to the paint() and update() methods of components are automatically
released by the system when those methods return.
The buffered image is drawn on the panel with the drawImage() method.
zetcode.com/gfx/java2d/java2dimages/ 5/15
26/9/2019 Imágenes en Java 2D
Flipped image
The following example flips image. We are going to filter the image. There is a filter() method which is
transforming images.
FlippedImageEx.java
package com.zetcode;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
public Surface() {
loadImage();
createFlippedImage();
setSurfaceSize();
}
Graphics gb = bufimg.getGraphics();
gb.drawImage(mshi, 0, 0, null);
gb.dispose();
zetcode.com/gfx/java2d/java2dimages/ 6/15
26/9/2019 Imágenes en Java 2D
int w = bufimg.getWidth();
int h = bufimg.getHeight();
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
doDrawing(g);
}
}
public FlippedImageEx() {
initUI();
}
add(new Surface());
pack();
setTitle("Flipped image");
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
FlippedImageEx ex = new FlippedImageEx();
ex.setVisible(true);
}
});
}
}
zetcode.com/gfx/java2d/java2dimages/ 7/15
26/9/2019 Imágenes en Java 2D
This is one of the filtering operations available. This could be also done by pixel manipulation. But Java 2D
provides high level classes that make it easier to manipulate images. In our case, the AffineTransformOp
class performs scaling and translation on the image pixels.
int w = bufimg.getWidth();
int h = bufimg.getHeight();
We set the preferred size for the panel. We calculate the size so that we can place two images on the panel
and put some space between them, and the images and the window borders.
Blurred image
The next code example blurs an image. A blur means an unfocused image. To blur an image, we use a
convolution operation. It is a mathematical operation which is also used in edge detection or noise
elimination. Blur operations can be used in various graphical effects. For example creating speed illusion o
showing an unfocused vision of a human.
The blur filter operation replaces each pixel in image with an average of the pixel and its neighbours.
Convolutions are per-pixel operations. The same arithmetic is repeated for every pixel in the image. A kern
can be thought of as a two-dimensional grid of numbers that passes over each pixel of an image in sequenc
performing calculations along the way. Since images can also be thought of as two-dimensional grids of
zetcode.com/gfx/java2d/java2dimages/ 8/15
26/9/2019 Imágenes en Java 2D
numbers, applying a kernel to an image can be visualized as a small grid (the kernel) moving across a
substantially larger grid (the image). (developer.apple.com)
BlurredImageEx.java
package com.zetcode;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.awt.image.BufferedImageOp;
import java.awt.image.ConvolveOp;
import java.awt.image.Kernel;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
public Surface() {
loadImage();
createBlurredImage();
setSurfaceSize();
}
try {
Logger.getLogger(Surface.class.getName()).log(
Level.WARNING, null, ex);
}
}
float[] blurKernel = {
1 / 9f, 1 / 9f, 1 / 9f,
1 / 9f, 1 / 9f, 1 / 9f,
1 / 9f, 1 / 9f, 1 / 9f
};
zetcode.com/gfx/java2d/java2dimages/ 9/15
26/9/2019 Imágenes en Java 2D
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
doDrawing(g);
}
}
public BlurredImageEx() {
setTitle("Blurred image");
add(new Surface());
pack();
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
In the code example, we load an image from the disk, perform a blur operation on the image, and display th
result on the window.
zetcode.com/gfx/java2d/java2dimages/ 10/15
26/9/2019 Imágenes en Java 2D
try {
Logger.getLogger(Surface.class.getName()).log(
Level.WARNING, null, ex);
}
}
The the read() method of the ImageIO class reads an image from the disk and returns a BufferedImage.
float[] blurKernel = {
1 / 9f, 1 / 9f, 1 / 9f,
1 / 9f, 1 / 9f, 1 / 9f,
1 / 9f, 1 / 9f, 1 / 9f
};
This matrix is called a kernel. The values are weights that are applied to the neighbouring values of the pixe
being changed.
Reflection
In the next example we show a reflected image. This effect makes an illusion as if the image was reflected in
water. The following code example was inspired by the code from jhlabs.com.
ReflectionEx.java
package com.zetcode;
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
zetcode.com/gfx/java2d/java2dimages/ 11/15
26/9/2019 Imágenes en Java 2D
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
public Surface() {
loadImage();
getImageSize();
createReflectedImage();
}
try {
Logger.getLogger(Surface.class.getName()).log(
Level.WARNING, null, ex);
}
}
img_w = image.getWidth();
img_h = image.getHeight();
}
zetcode.com/gfx/java2d/java2dimages/ 12/15
26/9/2019 Imágenes en Java 2D
g2d.drawImage(refImage, 0, 0, null);
g2d.dispose();
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
doDrawing(g);
}
@Override
public Dimension getPreferredSize() {
public ReflectionEx() {
initUI();
}
add(new Surface());
pack();
setTitle("Reflection");
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
zetcode.com/gfx/java2d/java2dimages/ 13/15
26/9/2019 Imágenes en Java 2D
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
rg.setComposite(AlphaComposite.getInstance(AlphaComposite.DST_IN));
rg.setPaint(new GradientPaint(0, img_h * fadeHeight,
new Color(0.0f, 0.0f, 0.0f, 0.0f), 0, img_h,
new Color(0.0f, 0.0f, 0.0f, opacity)));
This is the most important part of the code. We make the second image transparent. But the transparency i
not constant; the image gradually fades out. This is achieved with the GradientPaint class.
The background of the window is filled with a gradient paint. The paint is a smooth blending from black to
dark gray.
The normal image is moved to the center of the window and drawn.
Este código voltea la imagen y la traduce debajo de la imagen original. La operación de traducción es
necesaria porque la operación de escalado pone la imagen al revés y traduce la imagen hacia arriba. Para
zetcode.com/gfx/java2d/java2dimages/ 14/15
26/9/2019 Imágenes en Java 2D
entender lo que sucede, simplemente tome una fotografía y colóquela sobre la mesa y gírela.
@Anular
Dimensión pública getPreferredSize () {
Figura: Reflexión
zetcode.com/gfx/java2d/java2dimages/ 15/15