Skip to content

Instantly share code, notes, and snippets.

@iota9star
Created August 9, 2021 07:07
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iota9star/2a49a6781438089be951a31501d62760 to your computer and use it in GitHub Desktop.
Save iota9star/2a49a6781438089be951a31501d62760 to your computer and use it in GitHub Desktop.
Generate QR code by dart native.
import 'dart:io';
import 'package:image/image.dart';
import 'package:qr/qr.dart';
void main() async {
var bytes1 = _genQRCode('大宝好厉害!!!', rectSize: 20);
File('test1.png').writeAsBytesSync(bytes1);
var bytes2 = _genQRCode('大宝好厉害!!!', size: 500);
File('test2.png').writeAsBytesSync(bytes2);
}
List<int> _genQRCode(
String data, {
int size,
int rectSize,
int qrTypeNumber = 2,
int qrErrorCorrectLevel = QrErrorCorrectLevel.L,
int gap = 20,
String frontColor = '#000000',
String backgroundColor = '#ffffff',
bool withBorder = true,
String borderColor = '#666666',
}) {
assert(!(size == null && rectSize == null));
var qrCode = QrCode(qrTypeNumber, qrErrorCorrectLevel)
..addData(data)
..make();
var rect;
var rawGap;
if (rectSize != null) {
rect = rectSize;
rawGap = gap;
size = qrCode.moduleCount * rect + rawGap * 2;
} else {
var cw = size - 2 * gap;
var r = cw / qrCode.moduleCount;
rawGap = gap + (cw - qrCode.moduleCount * r) ~/ 2;
rect = ((size - 2 * rawGap) / qrCode.moduleCount).floor();
}
print('gap size: $gap => $rawGap, rect size: $rect');
var image = Image(size, size);
fill(image, _parseColor(backgroundColor));
for (var x = 0; x < qrCode.moduleCount; x++) {
for (var y = 0; y < qrCode.moduleCount; y++) {
var y1 = y * rect + rawGap;
var x1 = x * rect + rawGap;
var x2 = x1 + rect;
var y2 = y1 + rect;
if (qrCode.isDark(y, x)) {
fillRect(image, x1, y1, x2, y2, _parseColor(frontColor));
if (withBorder) {
drawRect(image, x1, y1, x2, y2, _parseColor(borderColor));
}
}
}
}
return encodePng(image);
}
int _parseColor(String color) {
var length = color.length;
if (length == 6) {
return int.parse('ff' + color, radix: 16);
} else if (length == 7) {
return int.parse('ff' + color.substring(1), radix: 16);
} else if (length == 8) {
return int.parse(color, radix: 16);
} else if (length == 9) {
return int.parse(color.substring(1), radix: 16);
}
throw 'Unsupported color string<$color>.';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment