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

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

问题描述:

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

Hello i want to convert a Image to a base64 String and then convert it back to an Image. This is how I did it:

 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时,我得到以下信息:

I get a error and when i want to print test4 i get only questionmarks. When I print pickedImage I get this:

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


完成将图像转换为base64并返回的所有工作:

You seem to be doing all the work already for converting an image into base64 and back:

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

就将它用于您的 FirebaseVisionImage ,由于无法使用该类,因此我不确定能提供多少帮助(我假设您正在使用firebase_ml_vision库)。但是,请查看对于 FirebaseVisionImage ,有一个 fromBytes 以及 fromFile $ c的工厂构造函数$ c>,尽管使用起来有点复杂。但是,如果您可以使用它,那可能是更适合您的构造函数:

As far as using it for your FirebaseVisionImage, I'm not sure how much I can help as I have no experience with that class (I'm assuming you're using the firebase_ml_vision library). However, looking at the source for FirebaseVisionImage, there is a factory constructor for fromBytes as well as fromFile, though it's a bit more complicated to use. If you can get it to work, though, that would probably be the more appropriate constructor for your needs:

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

或者,您可以将字节保存到临时文件中并使用:

Alternatively, you could just save the bytes to a temporary file and use that:

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

final visionImage = FirebaseVisionImage.fromFile(imgFile);