QRCode-Kotlin

repository·main·Indexed 43 days ago

https://github.com/g0dkar/qrcode-kotlin

A lightweight, pure Kotlin library for creating customizable QRCodes. It supports Kotlin Multiplatform (KMP) across JVM, Android, iOS, JavaScript, and tvOS. The library provides a high-level API via the QRCode class and QRCodeBuilder to customize shapes (squares, circles, rounded squares), colors, gradients, and logos. It can render QRCodes to PNG byte arrays or graphics objects and is compatible with Spring Boot for backend image serving.

Tokens
4.6K
Snippets
11
Records
20
Agent score
55%

What's inside QRCode-Kotlin

  1. How QRCodeBuilder works

    main

    After calling a shape factory method like QRCode.ofSquares(), you receive a QRCodeBuilder instance. This builder allows you to chain configuration methods to customize the QRCode before calling .build(content).

    Key customization capabilities include:

    • .withColor(color): Sets the foreground color (use qrcode.color.Colors).
    • .withSize(size): Adjusts the size of the cells.
    • .withSpacing(spacing): Adjusts the spacing.
    • Adding a logo: Allows embedding a logo and optionally removing the cells behind it.
  2. Migration guide from v3 to v4

    main

    If you are upgrading from version 3, note the following breaking changes:

    1. Package Renaming: The main package has changed from io.github.g0dkar.qrcode to simply qrcode.
    2. Class Renaming: The old QRCode class (used for processing) has been renamed to QRCodeProcessor. The new QRCode class is a redesigned, high-level API for creating beautiful QRCodes. For most simple use cases, the new QRCode API is compatible with the old logic.
    3. Performance: Significant optimizations have been made to the drawing process, moving from multiple canvases to a single large canvas for better performance.
    4. Platform Support: Support for iOS and tvOS was added (experimental) starting from version v4.0.7 via QRCodeGraphics implementation.
  3. Install QRCode-Kotlin

    main

    You can install QRCode-Kotlin using various package managers depending on your platform (JVM, Android, Node.js, or Browser).

    Gradle (Android or JVM)

    // Use this for both Android and JVM
    implementation("io.github.g0dkar:qrcode-kotlin:4.5.0")

    Maven (JVM)

    <dependency>
        <groupId>io.github.g0dkar</groupId>
        <artifactId>qrcode-kotlin-jvm</artifactId>
        <version>4.5.0</version>
    </dependency>

    Maven (Android)

    <dependency>
        <groupId>io.github.g0dkar</groupId>
        <artifactId>qrcode-kotlin-android</artifactId>
        <version>4.5.0</version>
    </dependency>

    NodeJS

    npm install qrcode-kotlin@4.5.0

    Browser (CDN)

    <script src="https://cdn.jsdelivr.net/gh/g0dkar/qrcode-kotlin@main/release/qrcode-kotlin.min.js" type="application/javascript"></script>
    // Gradle
    implementation("io.github.g0dkar:qrcode-kotlin:4.5.0")
    
    // Maven JVM
    <dependency>
        <groupId>io.github.g0dkar</groupId>
        <artifactId>qrcode-kotlin-jvm</artifactId>
        <version>4.5.0</version>
    </dependency>
  4. How the QRCode class works

    main

    The QRCode class acts as a high-level orchestrator for the QR Code generation process. It manages the lifecycle of several internal components:

    1. QRCodeProcessor: Handles the core logic of encoding the data, calculating error correction, and determining the raw QR structure.
    2. QRCodeGraphics: Represents the drawing canvas where the shapes are rendered.
    3. QRCodeShapeFunction: Defines how individual modules (squares, circles, etc.) are drawn.
    4. QRCodeColorFunction: Determines the colors used for the background and the modules.

    When render() is called, the class fills the background, applies any doBefore hooks, iterates through the rawData to draw shapes via the shapeFn, and finally executes any doAfter hooks.

  5. Create a QR Code using factory methods

    main

    The QRCode class provides several static factory methods via its companion object to quickly create different aesthetic styles using a QRCodeBuilder. This is the recommended way to instantiate a QR Code if you want specific shapes like circles or rounded squares.

    Available styles:

    • ofSquares(): Uses standard squares (default).
    • ofCircles(): Uses circles (inspired by Apple Music).
    • ofRoundedSquares(): Uses rounded squares.
    • ofCustomShape(customShapeFunction): Uses a user-provided QRCodeShapeFunction for complete control over the shape of each module.
    // Create a standard square QR Code
    val qrCode = QRCode.ofSquares().data("https://example.com").build()
    
    // Create a circular QR Code
    val circleQrCode = QRCode.ofCircles().data("https://example.com").build()
    
    // Create a rounded square QR Code
    val roundedQrCode = QRCode.ofRoundedSquares().data("https://example.com").build()
  6. Generate QRCodes in Spring Boot/Framework

    main

    To serve QRCodes from a backend Spring application, generate the PNG bytes using the library and wrap them in a ByteArrayResource. You can return this as a ResponseEntity with the appropriate MediaType.IMAGE_PNG_VALUE and CONTENT_DISPOSITION header to allow users to download or view the image.

    import org.springframework.core.io.ByteArrayResource
    import org.springframework.http.HttpHeaders.CONTENT_DISPOSITION
    import org.springframework.http.MediaType.IMAGE_PNG_VALUE
    import org.springframework.web.bind.annotation.GetMapping
    import org.springframework.web.bind.annotation.RequestParam
    import org.springframework.web.bind.annotation.RestController
    import qrcode.render.QRCode
    
    @RestController
    class QRCodeController {
    
        @GetMapping("/qrcode")
        fun generateQrCode(@RequestParam content: String): ResponseEntity<ByteArrayResource> {
            val pngData = QRCode.ofSquares()
                .build(content)
                .render()
            val resource = ByteArrayResource(pngData, IMAGE_PNG_VALUE)
    
            return ResponseEntity.ok()
                .header(CONTENT_DISPOSITION, "attachment; filename=\"qrcode.png\"")
                .body(resource)
        }
    }
  7. Generate QRCodes in Spring Boot/Spring Framework

    main

    To use QRCode-Kotlin in a backend Spring application, you can return the generated PNG bytes as a ResponseEntity<ByteArrayResource>. This allows you to serve the QR code directly via an HTTP endpoint.

    Example controller method:

    @GetMapping("/qrcode")
    fun generateQrCode(content: String): ResponseEntity<ByteArrayResource> {
        val pngData = QRCode.ofSquares()
            .build(content)
            .render()
        val resource = ByteArrayResource(pngData, MediaType.IMAGE_PNG_VALUE)
    
        return ResponseEntity.ok()
            .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"qrcode.png\"")
            .body(resource)
    }
    @GetMapping("/qrcode")
    fun generateQrCode(content: String): ResponseEntity<ByteArrayResource> {
        val pngData = QRCode.ofSquares()
            .build(content)
            .render()
        val resource = ByteArrayResource(pngData, IMAGE_PNG_VALUE)
    
        return ResponseEntity.ok()
            .header(CONTENT_DISPOSITION, "attachment; filename=\"qrcode.png\"")
            .body(resource)
    }
  8. Generate a basic QRCode with QRCode.render.QRCode

    main

    The primary class for creating QRCodes is qrcode.render.QRCode. It provides static methods to choose the shape of the QR code cells.

    Available shapes:

    • QRCode.ofSquares(): Standard square cells.
    • QRCode.ofCircles(): Circular cells.
    • QRCode.ofRoundedSquares(): Rounded square cells.

    These methods return a QRCodeBuilder instance, which allows you to customize colors, size, spacing, and add logos before calling .build(content).

    import qrcode.render.QRCode
    import qrcode.color.Colors
    import java.io.FileOutputStream
    
    val helloWorld = QRCode.ofSquares()
        .withColor(Colors.DEEP_SKY_BLUE) // Default is Colors.BLACK
        .withSize(10) // Default is 25px
        .build("Hello world!")
    
    // By default, QRCodes are generated as PNG
    val pngBytes = helloWorld.render()
    
    FileOutputStream("hello-world.png").use { it.write(pngBytes) }
  9. Create a basic QRCode with QRCode.render.QRCode

    main

    The qrcode.render.QRCode class is the primary entry point for generating QRCodes. You start by choosing a shape using static factory methods, then use a QRCodeBuilder to customize the appearance before building the final object with your content. By default, render() produces PNG byte arrays.

    import qrcode.render.QRCode
    import qrcode.color.Colors
    import java.io.FileOutputStream
    
    // 1. Choose a shape: ofSquares(), ofCircles(), or ofRoundedSquares()
    val helloWorld = QRCode.ofSquares()
        .withColor(Colors.DEEP_SKY_BLUE) // Custom color (Default: Colors.BLACK)
        .withSize(10)                   // Custom size (Default: 25)
        .build("Hello world!")         // Build with content
    
    // 2. Render to PNG bytes
    val pngBytes = helloWorld.render()
    
    // 3. Save to file
    FileOutputStream("hello-world.png").use { it.write(pngBytes) }
  10. Adjust canvas size, offsets, and margins

    main

    Control the final output dimensions and positioning.

    • withCanvasSize(size: Int): Sets the total pixel size of the square canvas. If set to 0, the size is computed automatically from the data.
    • withXOffset(xOffset: Int) / withYOffset(yOffset: Int): Offsets the drawing on the X or Y axis.
    • withMargin(margin: Int): Adds extra whitespace around the QR Code edges.
  11. Use LinearGradientColorFunction for gradient QR codes

    main

    The LinearGradientColorFunction allows you to render a QR code with a color gradient transitioning between two foreground colors. You can specify whether the gradient is applied vertically or horizontally.

    Parameters

    • startForegroundColor: The color at the beginning of the gradient.
    • endForegroundColor: The color at the end of the gradient.
    • backgroundColor: The background color of the QR code (defaults to Colors.WHITE).
    • vertical: A boolean determining the direction. If true, the gradient is vertical (based on rows). If false, the gradient is horizontal (based on columns).
    val gradientFunction = LinearGradientColorFunction(
        startForegroundColor = 0xFF0000, // Red
        endForegroundColor = 0x0000FF,   // Blue
        backgroundColor = 0xFFFFFFFF,   // White
        vertical = true
    )
  12. Customize QRCode shape and size

    main

    You can change the geometric shape of the QR Code cells and the size of individual cells.

    • withShape(shape: QRCodeShapesEnum): Sets the shape. Supported values are SQUARE, CIRCLE, ROUNDED_SQUARE, and CUSTOM.
    • withSize(size: Int): Sets the size of each individual cell (square) in pixels.
    • withRadius(radius: Int): Sets the corner radius for ROUNDED_SQUARE shapes. Use a negative number to use the default radius.
    • withInnerSpacing(innerSpacing: Int?): Sets the space between cells. Defaults to 1 pixel (or 0 for CUSTOM).
    • withCustomShapeFunction(shapeFn: QRCodeShapeFunction?): Provides a custom implementation for drawing cell shapes.