Skip to content

Commit 9d2d8ed

Browse files
authored
[GH-5] Overhaul Render (#6)
* [GH-5] Overhaul the renderer * [GH-5] Overhaul the renderer * [GH-5] Fixing tests and adding Android deps * [GH-5] Fixing tests and adding Android deps * [GH-5] New render is go! * [GH-5] New render is go! * [GH-5] Updating docs * [GH-5] Updating docs and examples * [GH-5] Updating docs and examples * [GH-5] Updating docs and examples
1 parent cf9df25 commit 9d2d8ed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

53 files changed

+2086
-645
lines changed

README.md

+66-255
Large diffs are not rendered by default.

README.pt_BR.md

+231
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,231 @@
1+
# qrcode-kotlin
2+
3+
[![Licença](https://img.shields.io/github/license/g0dkar/qrcode-kotlin)](LICENSE)
4+
[![Maven Central](https://img.shields.io/maven-central/v/io.github.g0dkar/qrcode-kotlin.svg?label=Maven%20Central)](https://search.maven.org/search?q=g:%22io.github.g0dkar%22%20AND%20a:%22qrcode-kotlin%22)
5+
6+
[![Mande uma Mensagem de Agradecimento](https://img.shields.io/badge/Mande%20uma-Mensagem%20de%20Agradecimento-green?style=for-the-badge)](https://saythanks.io/to/g0dkar)
7+
8+
[_:us: **Available in English**_](README.md)
9+
10+
Criar QRCodes em Kotlin e Java é mais difícil do que deveria. O QRCode-Kotlin tenta trazer uma forma simples, direta e
11+
personalizável de se criar QRCodes para o domínio da JVM, especialmente no backend.
12+
13+
## Vantagens do QRCode-Kotlin
14+
15+
* **Kotlin Puro:** Reimplementação em puro Kotlin a partir da implementação de referência da especificação do QRCode
16+
por [Kazuhiko Arase](https://github.com/kazuhikoarase/qrcode-generator)
17+
* **Leve:** Sem dependencias*, `~72KB` e faz exatamente o que promete fazer.
18+
* **Fácil de usar:** Instancie um objeto, chame um método e pronto :)
19+
* **Compacta:** Não adiciona nenhum "inchaço" como quando se usa bibliotecas como a Google ZXing (que fazem bem mais que
20+
gerar QRCodes)
21+
* **Saída Personalizada:** Quer um QRCode colorido? Nós temos!
22+
* **Amigável aos Servidores:** Esta não é uma biblioteca para aplicações Mobile. Esta biblioteca foi pensada por devs
23+
backend para devs backend.
24+
25+
>\* Bom, exceto talvez a `org.jetbrains.kotlin:kotlin-stdlib-jdk8` se você estiver usando Java...
26+
27+
## Instalação
28+
29+
Esta biblioteca está disponível a partir da [Central Maven](https://search.maven.org/artifact/io.github.g0dkar/qrcode-kotlin/2.0.0/qrcode-kotlin),
30+
então basta adicionar o `QRCode-Kotlin` a seu projeto como qualquer outra dependência:
31+
32+
**Se você utiliza Maven - pom.xml:**
33+
34+
```xml
35+
<dependency>
36+
<groupId>io.github.g0dkar</groupId>
37+
<artifactId>qrcode-kotlin</artifactId>
38+
<version>2.0.0</version>
39+
</dependency>
40+
```
41+
42+
**Se você utiliza Gradle:**
43+
44+
```groovy
45+
// Kotlin ❤️
46+
implementation("io.github.g0dkar:qrcode-kotlin:2.0.0")
47+
48+
// Groovy
49+
implementation 'io.github.g0dkar:qrcode-kotlin:2.0.0'
50+
```
51+
52+
## Exemplos e Usos
53+
54+
Aqui estão alguns exemplos de como utilizar a biblioteca para se ter alguns resultados bacanas. Se você tiver interesse
55+
em usos mais avançados ou QRCodes mais sofisticados, por favor leia a documentação :)
56+
57+
>Também lembre de checar a pasta de [exemplos](examples) para ver códigos em Kotlin e Java, e os QRCodes resultantes!
58+
59+
### Apenas um QRCode simples, nada de mais:
60+
61+
Para gerar um QRCode simples:
62+
63+
```kotlin
64+
// Por padrão, o método writeImage() escreve PNGs
65+
val fileOut = FileOutputStream("example01.png")
66+
67+
QRCode("https://github.com/g0dkar/qrcode-kotlin").render().writeImage(fileOut)
68+
```
69+
70+
O mesmo que o código acima, em Java:
71+
72+
```java
73+
// By default, the writeImage() method outputs PNGs
74+
FileOutputStream fileOut = new FileOutputStream("example01-java.png");
75+
76+
new QRCode("https://github.com/g0dkar/qrcode-kotlin").render().writeImage(fileOut);
77+
```
78+
79+
### Um QRCode, mas maior
80+
81+
A função `render()` pode receber o parâmetro `cellSize` para ajustar o tamanho do QRCode resultante. Este parâmetro
82+
representa o tamanho em pixels de cada quadrado no QRCode resultante. Seu valor padrão é `25`:
83+
84+
```kotlin
85+
val fileOut = FileOutputStream("example02.png")
86+
87+
QRCode("https://github.com/g0dkar/qrcode-kotlin")
88+
.render(cellSize = 50)
89+
.writeImage(fileOut)
90+
```
91+
92+
Em Java:
93+
94+
```java
95+
FileOutputStream fileOut = new FileOutputStream("example02-java.png");
96+
97+
new QRCode("https://github.com/g0dkar/qrcode-kotlin")
98+
.render(50)
99+
.writeImage(fileOut);
100+
```
101+
102+
### Igual ao Google ZXing!
103+
104+
No momento da escrita desta documentação, a [biblioteca Google ZXing](https://github.com/zxing/zxing) é amplamente
105+
utilizada para se gerar QRCodes. Seus resultados normalmente incluem uma "borda" _(também chamada de "margem")_ ao redor
106+
do QRCode, geralmente com 1 célula de tamanho. A função `render()` também pode receber um parâmetro `margin` com a
107+
quantidade de pixels que queremos ter como margem ao redor do QRCode. **Por padrão, o parâmetro `margin` é igual a `0`
108+
.**
109+
110+
Para se ter um desses QRCodes bem espaçados, tente fazer o seguinte:
111+
112+
```kotlin
113+
val fileOut = FileOutputStream("example03.png")
114+
val cellSize = 30 // pixels
115+
116+
QRCode("https://github.com/g0dkar/qrcode-kotlin")
117+
.render(cellSize, margin = cellSize)
118+
.writeImage(fileOut)
119+
```
120+
121+
Em Java:
122+
123+
```java
124+
FileOutputStream fileOut = new FileOutputStream("example03-java.png");
125+
int cellSize = 30; // pixels
126+
127+
new QRCode("https://github.com/g0dkar/qrcode-kotlin")
128+
.render(cellSize, cellSize);
129+
.writeImage(fileOut);
130+
```
131+
132+
### Um toque de Cor
133+
134+
![novo na v2.0.0](https://img.shields.io/badge/novo!-v2.0.0-critical)
135+
136+
Quer um QRCode colorido? Fácil, fácil! A Função `render()` também tem os parâmetros `brightColor`, `darkColor` e
137+
`marginColor` para isso. Seus valores padrão são para quadrados Preto-e-Branco com uma margem Branca. Esses são simples
138+
e (bem) velhos valores `java.awt.Color` no espaço RGBA.
139+
140+
Por diversão, este código cria um QRCode com as cores do Modo Escuro do GitHub:
141+
142+
```kotlin
143+
import io.github.g0dkar.qrcode.render.Colors
144+
145+
val background = Colors.css("#8b949e")
146+
val foreground = Colors.css("#0d1117")
147+
val fileOut = FileOutputStream("example03.png")
148+
149+
QRCode("https://github.com/g0dkar/qrcode-kotlin").render(
150+
brightColor = background, // Background
151+
darkColor = foreground, // Foreground (aka the "black squares")
152+
marginColor = background // Margin (ignored since margin = 0)
153+
).writeImage(fileOut)
154+
```
155+
156+
Em Java:
157+
158+
```java
159+
import java.awt.Color;
160+
161+
Color background = new Color(13, 17, 23);
162+
Color foreground = new Color(139, 148, 158);
163+
FileOutputStream fileOut = new FileOutputStream("example04-java.png");
164+
165+
new QRCode("https://github.com/g0dkar/qrcode-kotlin")
166+
.render(25, 0, background.getRGB(), foreground.getRGB(), background.getRGB())
167+
.writeImage(fileOut);
168+
```
169+
170+
### Especificando seu próprio tipo de dados
171+
172+
Se você não quer depender da lógica básica de identificação de tipo de dado implementada pela biblioteca, você pode
173+
especificar qual o tipo de dado da string de entrada. Você pode passar essa informação pelo parâmetro `dataType` no
174+
construtor da classe `QRCode` dessa forma:
175+
176+
```kotlin
177+
// Cria um QRCode do tipo "String" ao invés do tipo "Número" (que seria identificado automaticamente)
178+
QRCode("42", dataType = QRCodeDataType.DEFAULT)
179+
```
180+
181+
### Spring Framework e/ou Spring Boot
182+
183+
Uma das razões principais que desenvolvi essa biblioteca foi para utilizá-la em uma API Spring Boot que necessitava
184+
gerar QRCodes, então é apenas natural mostrar como se fazer isso :)
185+
186+
```kotlin
187+
import org.springframework.core.io.ByteArrayResource
188+
import org.springframework.http.HttpHeaders.CONTENT_DISPOSITION
189+
import org.springframework.http.MediaType.IMAGE_PNG_VALUE
190+
191+
@GetMapping("/qrcode")
192+
fun generateQrCode(content: String): ResponseEntity<ByteArrayResource> {
193+
val imageOut = ByteArrayOutputStream()
194+
195+
QRCode(content).render().writeImage(imageOut)
196+
197+
val imageBytes = imageOut.toByteArray()
198+
val resource = ByteArrayResource(imageBytes, IMAGE_PNG_VALUE)
199+
200+
return ResponseEntity.ok()
201+
.header(CONTENT_DISPOSITION, "attachment; filename=\"qrcode.png\"")
202+
.body(resource)
203+
}
204+
```
205+
206+
## Licença
207+
208+
Direito Autoral 2021 Rafael M. Lins, Licenciado pela [Licença MIT (texto em inglês)](LICENSE).
209+
210+
QR Code é marca registrada de Denso Wave, inc.
211+
212+
## Agradecimentos e Reconhecimentos
213+
214+
* [Kazuhiko Arase](https://github.com/kazuhikoarase): Autor da implementação de referência!
215+
* [Paul Varry](https://github.com/pvarry): Por abrir as primeiras issues no repositório e ajudar a fazer a biblioteca
216+
melhor para todo o mundo! :grin:
217+
* [Renan Lukas](https://github.com/RenanLukas): Por sua amizade, paciência e ajuda com Android, Gradle e outras coisas
218+
durante o desenvolvimento da v2.0.0!
219+
220+
## Suporte e Links
221+
222+
* Se encontrou bugs, por
223+
favor [abra uma Issue](https://github.com/g0dkar/qrcode-kotlin/issues/new?assignees=g0dkar&labels=bug&template=bug_report.md&title=)
224+
😁
225+
* Tem sugestões?
226+
Você [pode fazê-las](https://github.com/g0dkar/qrcode-kotlin/issues/new?assignees=&labels=&template=feature_request.md&title=)
227+
também!
228+
229+
Se curtiu a biblioteca e quiser me pagar um café, utilize o botão abaixo :love_you_gesture:
230+
231+
[![ko-fi](https://ko-fi.com/img/githubbutton_sm.svg "Pague um café para mim no Ko-fi!")](https://ko-fi.com/g0dkar)

build.gradle.kts

+14-8
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,11 @@
11
import org.jetbrains.dokka.gradle.DokkaTask
22

3+
buildscript {
4+
dependencies {
5+
classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:1.6.10")
6+
}
7+
}
8+
39
plugins {
410
id("idea")
511
signing
@@ -13,7 +19,7 @@ plugins {
1319
}
1420

1521
group = "io.github.g0dkar"
16-
version = "1.2.1"
22+
version = "2.0.0"
1723

1824
java {
1925
sourceCompatibility = JavaVersion.VERSION_1_8
@@ -27,10 +33,6 @@ idea {
2733
}
2834
}
2935

30-
repositories {
31-
mavenCentral()
32-
}
33-
3436
dependencies {
3537
implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8")
3638

@@ -76,11 +78,13 @@ ktlint {
7678
}
7779
}
7880

81+
82+
7983
/* **************** */
8084
/* Publishing */
8185
/* **************** */
82-
val ossrhUsername: String? = properties.getOrDefault("ossrhUsername", System.getenv("OSSRH_USER"))?.toString()
83-
val ossrhPassword: String? = properties.getOrDefault("ossrhPassword", System.getenv("OSSRH_PASSWORD"))?.toString()
86+
val ossrhUsername = properties.getOrDefault("ossrhUsername", System.getenv("OSSRH_USER"))?.toString()
87+
val ossrhPassword = properties.getOrDefault("ossrhPassword", System.getenv("OSSRH_PASSWORD"))?.toString()
8488

8589
val dokkaHtml by tasks.getting(DokkaTask::class)
8690
val javadocJar: TaskProvider<Jar> by tasks.registering(Jar::class) {
@@ -120,7 +124,7 @@ publishing {
120124
licenses {
121125
license {
122126
name.set("MIT")
123-
url.set("https://github.com/g0dkar/qrcode-kotlin/blob/main/LICENSE")
127+
url.set("$projectGitUrl/blob/main/LICENSE")
124128
}
125129
}
126130
developers {
@@ -165,6 +169,8 @@ signing {
165169
sign(publishing.publications)
166170
}
167171

172+
173+
168174
/* *************************** */
169175
/* SonarQube Quality Reporting */
170176
/* *************************** */

examples/java-colored.png

5.93 KB
Loading

examples/java-darkmode-reversed.png

7.51 KB
Loading

examples/java-darkmode.png

7.51 KB
Loading

examples/java-gradient.png

5.16 KB
Loading

examples/java-random-colored.png

9.19 KB
Loading

examples/java-round.png

14.2 KB
Loading

examples/java-simple.png

6.44 KB
Loading

examples/java/build.gradle.kts

+2-1
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,9 @@ plugins {
44

55
repositories {
66
mavenCentral()
7+
mavenLocal()
78
}
89

910
dependencies {
10-
implementation("io.github.g0dkar:qrcode-kotlin:1.1.0")
11+
implementation("io.github.g0dkar:qrcode-kotlin:2.0.0")
1112
}

examples/java/src/main/java/ColoredQRCode.java

+10-5
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,11 @@
22

33
import io.github.g0dkar.qrcode.QRCode;
44
import java.awt.Color;
5-
import java.awt.image.BufferedImage;
6-
import java.io.File;
5+
import java.io.FileOutputStream;
76
import java.io.IOException;
87
import java.util.Arrays;
98
import java.util.List;
109
import java.util.Random;
11-
import javax.imageio.ImageIO;
1210

1311
public class ColoredQRCode {
1412

@@ -21,9 +19,16 @@ public void createQRCode(
2119
String filename
2220
) throws IOException {
2321
String destination = ofNullable(filename).orElse(DEFAULT_FILENAME);
22+
FileOutputStream fileOut = new FileOutputStream(destination);
2423
QRCode qrCode = new QRCode(content);
25-
BufferedImage imageData = qrCode.render(25, 0, qrCode.encode(), backgroundColor, squareColor);
26-
ImageIO.write(imageData, "PNG", new File(destination));
24+
25+
qrCode.render(
26+
QRCode.DEFAULT_CELL_SIZE,
27+
QRCode.DEFAULT_MARGIN,
28+
backgroundColor.getRGB(),
29+
squareColor.getRGB()
30+
)
31+
.writeImage(fileOut);
2732
}
2833

2934
public static void main(String[] args) throws Exception {

0 commit comments

Comments
 (0)