@ResponseBody @RequestMapping(method = RequestMethod.GET, value = "/{productId}/ean") public ResponseEntity<?> getProductEAN(@PathVariable String productId) throws WriterException, IOException { Product product = repository.findOne(productId); if (product == null) { return ResponseEntity.notFound().build(); } EAN13Writer ean13Writer = new EAN13Writer(); BitMatrix matrix = ean13Writer.encode(product.getEan(), BarcodeFormat.EAN_13, 300, 200); BufferedImage bufferedImage = MatrixToImageWriter.toBufferedImage(matrix); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(bufferedImage, "png", baos); byte[] imageData = baos.toByteArray(); ByteArrayResource byteArrayResource = new ByteArrayResource(imageData); return ResponseEntity.ok().contentType(MediaType.IMAGE_PNG).body(byteArrayResource); }
public static InputStream createBarCode(long inputId) { try { EAN13Writer wt = new EAN13Writer(); String data = String.format("%012d", inputId); int check = getStandardUPCEANChecksum(data); data += check; BitMatrix bt = wt.encode(data, BarcodeFormat.EAN_13, 200, 50); int width = bt.getWidth(); int height = bt.getHeight(); BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); int[] pixels = new int[width * height]; int index = 0; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { pixels[index++] = bt.get(x, y) ? Color.BLACK.hashCode() : Color.WHITE.hashCode(); } } image.setRGB(0, 0, width, height, pixels, 0, width); ByteArrayOutputStream out = new ByteArrayOutputStream(); ImageIO.write(image, "png", out); return new ByteArrayInputStream(out.toByteArray()); } catch (FormatException | WriterException | IOException e) { e.printStackTrace(); } return null; }
public static BitMatrix generateEAN13(String content, int width, int height) throws WriterException { return new EAN13Writer().encode(content, BarcodeFormat.EAN_13, width, height); }