上次做了图片裁剪的需求没有记录, 最近遇到了身份证裁剪的需求又忘记处理方法了,处理完毕后记录一下
需求: 根据形状拍照,并进行裁剪

方案: 拍照。==》裁剪 ==》存储 ==》上传
步骤:
1、将file转化为image
changeFileWithImage(String filePath) async {
Uint8List bytes = await file2Uint8List(File(filePath));
ui.Codec codec = await ui.instantiateImageCodec(bytes,
targetWidth: screenWidth.toInt(), targetHeight: screenHeight.toInt());
ui.FrameInfo fi = await codec.getNextFrame();
return fi.image;
}

2、构建画布
Paint paint = Paint();
PictureRecorder recorder = PictureRecorder();
Canvas canvas2 = Canvas(recorder);
3、根据宽高比 计算实际裁剪宽高
double whrate = coverHeight / coverWidth;
double realHeight = screenWidth / whrate;
double topy = (screenHeight - realHeight) / 2;
3、处理被对照尺寸
Rect source = Rect.fromLTWH(0, topy, screenWidth, realHeight);
4、处理实际裁剪尺寸
Rect dest = Rect.fromLTWH(0, 0, screenWidth, realHeight);
canvas2.drawImageRect(fileImage, source, dest, paint);
5、裁剪
var image2 = recorder
.endRecording()
.toImage(dest.width.toInt(), dest.height.toInt());
image2.then((value) async {
6、将图片转化为字节
ByteData? byteData = await value.toByteData(format: ImageByteFormat.png);
Uint8List pngBytes = byteData!.buffer.asUint8List();
7、存储图片文件文件
new File(filePath).writeAsBytesSync(pngBytes);
idCardPath = filePath;
completer.complete();
网友评论