Flutter将Image转换为base64并将base64字符串转换为Image

时间:2019-05-03 22:06:03

标签: android ios dart 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'

1 个答案:

答案 0 :(得分:1)

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

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

就将其用于您的FirebaseVisionImage而言,我不确定自己能提供多少帮助,因为我没有使用该类的经验(我假设您正在使用firebase_ml_vision库)。但是,查看FirebaseVisionImage的{​​{3}},有一个fromBytesfromFile的工厂构造函数,尽管使用起来有点复杂。但是,如果您可以使用它,那可能是更适合您需要的构造函数:

// 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);