Trabajo con imágenes en Java: bibliotecas, herramientas y ejemplos de código
Java proporciona potentes herramientas integradas para trabajar con gráficos, así como un rico ecosistema de bibliotecas de terceros. En este artículo, exploraremos las principales formas de cargar, procesar, transformar y guardar imágenes en Java, desde las clases estándar javax.imageio y java.awt hasta bibliotecas populares que simplifican la vida del desarrollador.
1. Herramientas estándar: javax.imageio y java.awt.image
El trabajo básico con imágenes rasterizadas en Java se basa en el paquete javax.imageio (carga/guardado) y java.awt.image (trabajo con píxeles). La clase principal es BufferedImage, que almacena la imagen en la memoria RAM.
Carga y guardado de imágenes
import javax.imageio.ImageIO;import java.awt.image.BufferedImage;import java.io.File;import java.io.IOException;
public class ImageExample { public static void main(String[] args) throws IOException { // Carga de imagen desde archivo BufferedImage image = ImageIO.read(new File("input.jpg")); System.out.println("Ancho: " + image.getWidth() + ", Alto: " + image.getHeight());
// Guardado en otro formato ImageIO.write(image, "png", new File("output.png")); }}ImageIO admite los formatos: JPEG, PNG, BMP, WBMP, GIF (solo lectura). Para ampliar la lista de formatos, use los plugins de ImageIO (por ejemplo, TwelveMonkeys).
Cambio de tamaño (método manual)
import java.awt.Graphics2D;import java.awt.RenderingHints;import java.awt.image.BufferedImage;
public static BufferedImage resize(BufferedImage original, int newWidth, int newHeight) { BufferedImage resized = new BufferedImage(newWidth, newHeight, original.getType()); Graphics2D g2d = resized.createGraphics(); g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g2d.drawImage(original, 0, 0, newWidth, newHeight, null); g2d.dispose(); return resized;}2. Java 2D API: dibujo y filtros
La clase Graphics2D no solo permite escalar, sino también aplicar efectos, rotar, recortar imágenes, añadir texto y figuras geométricas.
Aplicación de marca de agua
public static BufferedImage addWatermark(BufferedImage source, String text) { BufferedImage result = new BufferedImage(source.getWidth(), source.getHeight(), source.getType()); Graphics2D g2d = result.createGraphics(); g2d.drawImage(source, 0, 0, null); g2d.setColor(new Color(255, 255, 255, 128)); g2d.setFont(new Font("Arial", Font.BOLD, 40)); g2d.drawString(text, 20, source.getHeight() - 20); g2d.dispose(); return result;}Aplicación de filtro de color (sepia)
public static BufferedImage applySepia(BufferedImage img) { int width = img.getWidth(); int height = img.getHeight(); BufferedImage sepia = new BufferedImage(width, height, img.getType());
for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { int rgb = img.getRGB(x, y); int r = (rgb >> 16) & 0xFF; int g = (rgb >> 8) & 0xFF; int b = rgb & 0xFF;
int newR = (int) (0.393 * r + 0.769 * g + 0.189 * b); int newG = (int) (0.349 * r + 0.686 * g + 0.168 * b); int newB = (int) (0.272 * r + 0.534 * g + 0.131 * b);
newR = Math.min(255, newR); newG = Math.min(255, newG); newB = Math.min(255, newB);
int newPixel = (0xFF << 24) | (newR << 16) | (newG << 8) | newB; sepia.setRGB(x, y, newPixel); } } return sepia;}