Untitled
unknown
java
a year ago
2.9 kB
16
Indexable
import com.google.zxing.BarcodeFormat; import com.google.zxing.WriterException; import com.google.zxing.client.j2se.MatrixToImageWriter; import com.google.zxing.common.BitMatrix; import com.google.zxing.qrcode.QRCodeWriter; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Base64; @RestController @RequestMapping("/api/qr") public class QRCodeController { @GetMapping("/generate") public ResponseEntity<String> generateQRCode(@RequestParam String text, @RequestParam int width, @RequestParam int height) { try { QRCodeWriter qrCodeWriter = new QRCodeWriter(); BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height); BufferedImage bufferedImage = MatrixToImageWriter.toBufferedImage(bitMatrix); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); ImageIO.write(bufferedImage, "png", byteArrayOutputStream); byte[] byteArray = byteArrayOutputStream.toByteArray(); String base64Image = Base64.getEncoder().encodeToString(byteArray); return ResponseEntity.ok(base64Image); } catch (WriterException | IOException e) { e.printStackTrace(); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error generating QR Code"); } } @PostMapping("/decode") public ResponseEntity<byte[]> decodeQRCode(@RequestBody String base64Image) { try { // Remove prefix if exists if (base64Image.contains(",")) { base64Image = base64Image.substring(base64Image.indexOf(",") + 1); } byte[] imageBytes = Base64.getDecoder().decode(base64Image); ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(imageBytes); BufferedImage bufferedImage = ImageIO.read(byteArrayInputStream); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); ImageIO.write(bufferedImage, "png", byteArrayOutputStream); byte[] imageInBytes = byteArrayOutputStream.toByteArray(); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.IMAGE_PNG); headers.setContentLength(imageInBytes.length); return new ResponseEntity<>(imageInBytes, headers, HttpStatus.OK); } catch (IOException e) { e.printStackTrace(); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null); } } }
Editor is loading...
Leave a Comment