如何在Flutter中将图像转换为文件? [英] How to convert Image to File in Flutter?
本文介绍了如何在Flutter中将图像转换为文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在编写此flutter代码,其中图像"小部件中有图像,并且希望将其转换为文件",以便可以将其上载到Firebase Storage.
Image _image = Image.asset('assets \ images \ profile.png');文件_fileImage = convertToFile(_image);//将_fileImage上传到Firebase存储代码
我需要 File convertToFile(Image img)
函数.
解决方案
特别感谢 sami kanafani ./p>
这是我的解决方案(非常适合我):
import'dart:async';导入'dart:io';导入'package:flutter/services.dart';导入'package:path_provider/path_provider.dart';类ImageUtils {静态Future< File>imageToFile({String imageName,String ext})异步{var bytes = await rootBundle.load('assets/$ imageName.$ ext');字符串tempPath =(await getTemporaryDirectory()).path;文件file = File('$ tempPath/profile.png');等待file.writeAsBytes(bytes.buffer.asUint8List(bytes.offsetInBytes,bytes.lengthInBytes));返回文件;}}class AnotherClass {文件imagePlaceHolder;_setPlaceHolder()异步{this.imagePlaceHolder =等待ImageUtils.imageToFile(imageName:"photo_placeholder",ext:"jpg");}...Image.file(this.imagePlaceHolder),}
I am writing this flutter code where I have Image in an Image widget and I want to convert it into File so that I can upload it to Firebase Storage.
Image _image = Image.asset('assets\images\profile.png');
File _fileImage = convertToFile(_image);
//upload _fileImage to Firebase Storage code
I need the File convertToFile(Image img)
function.
解决方案
Special thanks to sami kanafani.
This is my solution (works perfectly for me):
import 'dart:async';
import 'dart:io';
import 'package:flutter/services.dart';
import 'package:path_provider/path_provider.dart';
class ImageUtils {
static Future<File> imageToFile({String imageName, String ext}) async {
var bytes = await rootBundle.load('assets/$imageName.$ext');
String tempPath = (await getTemporaryDirectory()).path;
File file = File('$tempPath/profile.png');
await file.writeAsBytes(
bytes.buffer.asUint8List(bytes.offsetInBytes, bytes.lengthInBytes));
return file;
}
}
class AnotherClass {
File imagePlaceHolder;
_setPlaceHolder() async {
this.imagePlaceHolder = await ImageUtils.imageToFile(
imageName: "photo_placeholder", ext: "jpg");
}
...
Image.file(this.imagePlaceHolder),
}
这篇关于如何在Flutter中将图像转换为文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文