小编典典

Flutter将Image转换为base64,将string64转换为Image

flutter

您好,我想将Image转换为base64字符串,然后再将其转换回Image。这是我的方法:

 File pickedImage = await ImagePicker.pickImage(
      source: ImageSource.gallery
    );
 List<int> test = pickedImage.readAsBytesSync();
 String test2 = base64Encode(test);
 Uint8List test3 = base64Decode(test2);
 File test4 = new File.fromRawPath(test3);
 FirebaseVisionImage ourImage = FirebaseVisionImage.fromFile(test4);

我收到一个错误,当我想打印test4时,我仅收到问号。当我打印pickleImage时,我得到这个:

File: '/storage/emulated/0/WhatsApp/Media/WhatsApp Images/IMG-20190503-WA0005.jpg'

阅读 1475

收藏
2020-08-13

共1个答案

小编典典

您似乎已经在完成将图像转换为base64并返回的所有工作:

List<int> imageBytes = pickedImage.readAsBytesSync();
String imageB64 = base64Encode(imageBytes);
Uint8List decoded = base64Decode(imageB64);

至于为您使用它FirebaseVisionImage,我不确定我能提供多少帮助,因为我对该类没有经验(我假设您正在使用firebase_ml_vision库)。然而,看着来源FirebaseVisionImage,有一个工厂构造fromBytes以及fromFile,虽然这是一个有点更复杂的使用。但是,如果您可以使其正常运行,则可能是更适合您需要的构造函数:

// Metadata values based on an RGBA-encoded 1920x1080 image
// You will have to change these values to fit your specific images
final planeMetadata = FirebaseVisionImagePlaneMetadata(
    width: 1920,
    height: 1080,
    bytesPerRow: 1920 * 4,
);

final metadata = FirebaseVisionImageMetadata(
    size: Size(1920, 1080),
    planeData: planeMetadata,

    // From https://developer.apple.com/documentation/corevideo/1563591-pixel_format_identifiers?language=objc
    // kCVPixelFormatType_32RGBA
    rawFormat: 'RGBA', 
);

final visionImage = FirebaseVisionImage.fromBytes(decoded, metadata);

另外,您可以将字节保存到一个临时文件中并使用:

// Assuming the source image is a PNG image
File imgFile = File('tempimage.png');
imgFile.writeAsBytesSync(decoded.ToList());

final visionImage = FirebaseVisionImage.fromFile(imgFile);
2020-08-13