Trabalhando com Imagens em Java: Bibliotecas, Ferramentas e Exemplos de Código
O Java fornece poderosos recursos integrados para trabalhar com gráficos, bem como um rico ecossistema de bibliotecas de terceiros. Neste artigo, exploraremos as principais formas de carregar, processar, transformar e salvar imagens em Java — desde as classes padrão javax.imageio e java.awt até bibliotecas populares que simplificam a vida do desenvolvedor.
1. Recursos Padrão: javax.imageio e java.awt.image
O trabalho básico com imagens raster em Java é baseado no pacote javax.imageio (carregamento/salvamento) e java.awt.image (manipulação de pixels). A classe principal é BufferedImage, que armazena a imagem na memória RAM.
Carregando e Salvando uma Imagem
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 { // Carregando imagem de um arquivo BufferedImage image = ImageIO.read(new File("input.jpg")); System.out.println("Largura: " + image.getWidth() + ", Altura: " + image.getHeight());
// Salvando em outro formato ImageIO.write(image, "png", new File("output.png")); }}ImageIO suporta os formatos: JPEG, PNG, BMP, WBMP, GIF (somente leitura). Para expandir a lista de formatos, use plugins ImageIO (por exemplo, TwelveMonkeys).
Redimensionamento (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: Desenho e Filtros
A classe Graphics2D permite não apenas redimensionar, mas também aplicar efeitos, girar, recortar imagens, adicionar texto e formas geométricas.
Aplicando Marca d'Água
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;}Aplicando Filtro de Cor (Sépia)
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;}