使用的插件是
scan: any
要识别微信的二维码或者群聊的二维码;
现在遇到问题是有的用户保存微信图片时,使用了彩色的图片,在iOS16.x可以识别,但是15.x识别不到二维码,返回为null;
Scan.parse(path)
图片是绝对没问题的
使用Photoshop,把彩色图片反相后,15.x就可以识别了
具体操作代码如下
图片反相:
static Future<ui.Image> invertImage(ui.Image image) async {
final int width = image.width;
final int height = image.height;
final ui.PictureRecorder recorder = ui.PictureRecorder();
final ui.Canvas canvas = ui.Canvas(recorder);
final ui.Paint paint = ui.Paint();
// final maskFilter = ui.MaskFilter.blur(
// ui.BlurStyle.normal,
// ui.BlurStyle.normal.convertRadiusToSigma(1.0),
// );
final ui.Rect rect =
ui.Rect.fromLTWH(0, 0, width.toDouble(), height.toDouble());
final Offset offset = Offset(0, 0);
canvas.drawImage(image, offset, paint);
// canvas.drawImage
paint.color = ui.Color.fromRGBO(255, 255, 255, 1);
paint.blendMode = ui.BlendMode.difference;
canvas.drawRect(rect, paint);
final ui.Picture picture = recorder.endRecording();
final ui.Image newImage = await picture.toImage(width, height);
return newImage;
}
识别
//扫描二维码
static Future<String?> scanImageFile(String imagePath) async {
try {
if (imagePath.isEmpty) return null;
String? result = await Scan.parse(imagePath);
if (result == null) {
//第一次没有扫描到二维码
print('ScanUtils第一次没有扫描到二维码$imagePath');
File file = File(imagePath);
if (!file.existsSync()) {
return null;
}
//图片存在
final Uint8List imgData = file.readAsBytesSync();
final ui.Codec codec = await ui.instantiateImageCodec(imgData);
final ui.FrameInfo frameInfo = await codec.getNextFrame();
ui.Image image = await ImageUtils.invertImage(frameInfo.image);
Directory dir = await getTemporaryDirectory();
String path = dir.path + '/${genUUID(16)}.png';
final ByteData? byteData =
await image.toByteData(format: ui.ImageByteFormat.png);
if (byteData != null) {
final Uint8List pngBytes = byteData.buffer.asUint8List();
await File(path).writeAsBytes(pngBytes);
}
File(path).writeAsBytesSync(byteData!.buffer.asUint8List());
if (!File(path).existsSync()) return null;
print('ScanUtils扫码反相的${path}');
result = await Scan.parse(path);
if (result == null) {
return null;
}
return result;
}
print('ScanUtils第一次扫描到了$result');
return result;
} catch (e) {
print('ScanUtils扫描错误${e.toString()}');
return null;
}
}
done