Genera código de barras con texto en Java usando ZXing

Genera códigos de barras CODE 128 en Java con ZXing, añade texto legible debajo y exporta como PNG. Incluye dependencias Maven y ejemplo de código.

1 sept 2025 • 3 min read • Q2BSTUDIO Team

Inteligencia-Artificial-

Hace poco vi un ejemplo de generación de códigos de barras en Python y me inspiró a crear una versión en Java. En esta guía te muestro cómo generar un código de barras en formato CODE 128 y agregar el texto legible por humanos debajo, todo exportado como una sola imagen PNG utilizando la librería ZXing Zebra Crossing.

Dependencias Maven

Agrega estas dependencias a tu archivo pom.xml del proyecto:

<dependency> <groupId>com.google.zxing</groupId> <artifactId>core</artifactId> <version>3.5.1</version> </dependency> <dependency> <groupId>com.google.zxing</groupId> <artifactId>javase</artifactId> <version>3.5.1</version> </dependency>

Código Java completo

// Importaciones necesarias import com.google.zxing.*; import com.google.zxing.client.j2se.MatrixToImageWriter; import com.google.zxing.oned.Code128Writer; import javax.imageio.ImageIO; import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; public class Barcode { public static void main(String[] args) throws Exception { String data = "1234-5678-9012"; int width = 400; int height = 100; int textHeight = 30; BufferedImage barcode = MatrixToImageWriter.toBufferedImage(new Code128Writer().encode(data, BarcodeFormat.CODE_128, width, height)); BufferedImage combined = new BufferedImage(width, height + textHeight, BufferedImage.TYPE_INT_RGB); Graphics2D g = combined.createGraphics(); g.setColor(Color.WHITE); g.fillRect(0, 0, width, height + textHeight); g.drawImage(barcode, 0, 0, null); g.setColor(Color.BLACK); g.setFont(new Font("Arial", Font.PLAIN, 18)); int textX = (width - g.getFontMetrics().stringWidth(data)) / 2; g.drawString(data, textX, height + 20); g.dispose(); ImageIO.write(combined, "png", new File("barcode_with_text.png")); System.out.println("Barcode with text saved as barcode.png."); } }

Salida esperada

Obtendrás una imagen PNG con el código de barras CODE 128 y el contenido de datos centrado debajo, lista para usarse en etiquetas, albaranes o inventario.

Notas rápidas sobre CODE 128

CODE 128 es un formato lineal de alta densidad que soporta los 128 caracteres ASCII. Es muy usado en logística, etiquetas de envío e inventarios. ZXing se encarga del detalle de la codificación, de modo que integrarlo en aplicaciones Java es directo y fiable.

Buenas prácticas y ajustes útiles

- Si necesitas barras más nítidas para impresoras térmicas, aumenta width y height manteniendo la relación. - Ajusta textHeight y el tamaño de la fuente para códigos más largos. - Para fondos transparentes, usa un BufferedImage.TYPE_INT_ARGB y no rellenes con blanco. - Si el lector no reconoce bien el código, revisa el contraste, márgenes laterales y evita reescalar la imagen con interpolación.

Cómo encaja en un proyecto real

En entornos empresariales, este patrón es útil para etiquetas de picking, control de activos, tickets o integraciones con ERP y WMS. Puedes generar el PNG bajo demanda en una API, insertarlo en PDFs o imprimirlo desde estaciones de trabajo. Si gestionas grandes volúmenes, considera cachear imágenes para valores repetidos y firmar rutas de descarga.

Sobre Q2BSTUDIO

En Q2BSTUDIO somos una empresa de desarrollo de software especializada en aplicaciones a medida y software a medida, integrando estándares de calidad, observabilidad y seguridad desde la base. Podemos ayudarte a incorporar generación de códigos de barras, QR, etiquetas y automatización de procesos en tus flujos de negocio. Descubre cómo abordamos proyectos end to end en nuestro servicio de desarrollo de aplicaciones a medida.

Además, somos especialistas en inteligencia artificial aplicada, creación de agentes IA, visión por computador y NLP. Si buscas impulsar la productividad, la analítica y la toma de decisiones con IA para empresas, visita nuestra propuesta de inteligencia artificial.

Palabras clave y capacidades

Aplicaciones a medida, software a medida, inteligencia artificial, ciberseguridad, servicios cloud aws y azure, servicios inteligencia de negocio, ia para empresas, agentes IA, power bi. También abordamos hardening, auditorías y pruebas de seguridad, integración con servicios cloud, pipelines de datos y cuadros de mando de alto impacto con BI.

Conclusión

Con unas pocas líneas y ZXing puedes generar códigos de barras CODE 128 en Java, añadir texto legible y exportar un PNG listo para impresión o distribución digital. Este enfoque es sencillo de integrar en microservicios, aplicaciones de escritorio o backends web, y escalable para escenarios de alto volumen en entornos empresariales.

A BREAK?

Play for a moment before you go

OUR SERVICES

How we can help you

Artificial intelligence

AI agents, chatbots, and intelligent assistants that automate tasks and serve your customers 24/7 to improve the efficiency of your business.

More info

Software Development

Web, mobile, and desktop applications, intranets, e-commerce, SaaS, and management platforms designed for your company's specific needs.

More info

Cloud services

Migration, infrastructure, managed hosting, high availability, and security on Microsoft Azure and Amazon Web Services to help your business scale without limits.

More info

Cybersecurity and pentesting

Security audits, penetration testing and protection of applications, data and infrastructure on-premise and cloud, with ethical hacking and regulatory compliance.

More info

Business Intelligence

Dashboards and data analysis with Power BI: we integrate your sources, design dashboards and KPIs and turn your data into decisions.

More info

Process automation

We automate repetitive tasks and connect your applications with n8n, Power Automate, Make, and RPA, eliminating manual work and increasing productivity.

More info

Training for Companies

We train your teams in technology with criteria: web development, databases, Git, best practices and security, automation with n8n, artificial intelligence for companies and creation of AI solutions with Azure AI Foundry.

More info

Code Auditing

We audit the code that you, your team or an AI create: we tell you what is good and what to improve, we secure it and make it ready for production, web or app.

More info

AI Image Generation

We create for you the images that your business needs with artificial intelligence: product, networks, advertising, illustration and avatars. You tell us what you want and we deliver it ready to use.

More info

AI Video Generation

We create videos with artificial intelligence for you: promotional, networking, virtual presenters, dubbing and animations. You tell us the idea and we will deliver it assembled and ready to publish.

More info

AI Conversational Avatars

We create conversational avatars with AI – digital humans with a face and voice – that serve your customers and teams with the knowledge of your company, on your website, interactive monitors, WhatsApp or Teams.

More info

Online Marketing and AI

Google Ads, Meta Ads, LinkedIn Ads and AI Engine Positioning (GEO/AEO): we attract customers and make your brand appear where they search for you, also on ChatGPT, Gemini and Perplexity.

More info

Do you have a project in mind?

Tell us your vision and we'll turn it into a software solution. Whatever the scope, we make your idea real.

Live Chat