Dart 如何在flatter中保存图像文件?使用图像选择器插件选择的文件
我真的很困惑。颤栗是可怕的,但有些时间是停留在脑海中 所有代码都完成了。选定的文件也显示在预览中,但我尝试将该文件保存在本地android存储中。我在工作中无法取得成功Dart 如何在flatter中保存图像文件?使用图像选择器插件选择的文件,dart,flutter,Dart,Flutter,我真的很困惑。颤栗是可怕的,但有些时间是停留在脑海中 所有代码都完成了。选定的文件也显示在预览中,但我尝试将该文件保存在本地android存储中。我在工作中无法取得成功 Future getImage(ImageSource imageSource) async { var image = await ImagePicker.pickImage(source: imageSource); setState(() { _image = image; });
Future getImage(ImageSource imageSource) async {
var image = await ImagePicker.pickImage(source: imageSource);
setState(() {
_image = image;
});
}
在
\u image
中选择使用此代码的文件和我的文件现在我尝试使用path\u provider和dart.io进行存储,但我无法获得保存方法。使用等待ImagePicker.pickImage(…)
,您已经在正确的轨道上了,因为函数返回一个值
文件
类有一个,您可以使用该类复制文件(该文件已通过相机或多媒体资料保存在磁盘上)并将其放入应用程序文档目录:
// using your method of getting an image
final File image = await ImagePicker.pickImage(source: imageSource);
// getting a directory path for saving
final String path = await getApplicationDocumentsDirectory().path;
// copy the file to a new path
final File newImage = await image.copy('$path/image1.png');
setState(() {
_image = newImage;
});
还应注意,您可以使用image.path
,从ImagePicker
获取图像文件的路径,它还将包含您可能要提取的文件结尾,您可以使用newImage保存图像路径。path
@creativecreateormormaybeno答案确实有用,但它遗漏了一个重要部分,即检索图像以供以后使用
保存图像
// Step 1: Retrieve image from picker
final File image = await ImagePicker.pickImage(source: imageSource);
// Step 2: Check for valid file
if (image == null) return;
// Step 3: Get directory where we can duplicate selected file.
final String path = await getApplicationDocumentsDirectory().path;
// Step 4: Copy the file to a application document directory.
final var fileName = basename(file.path);
final File localImage = await image.copy('$path/$fileName');
// Step 1: Save image/file path as string either db or shared pref
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString('test_image', localImage.path)
// Step 2: Loading image by using the path that we saved earlier. We can create a file using path
// and can use FileImage provider for loading image from file.
CircleAvatar(
backgroundImage: FileImage(File(prefs.getString('test_image')),
radius: 50,
backgroundColor: Colors.white)
提示:您可以使用basename(file.path)从原始文件中检索文件名。确保导入“package:path/path.dart”
检索/加载图像
// Step 1: Retrieve image from picker
final File image = await ImagePicker.pickImage(source: imageSource);
// Step 2: Check for valid file
if (image == null) return;
// Step 3: Get directory where we can duplicate selected file.
final String path = await getApplicationDocumentsDirectory().path;
// Step 4: Copy the file to a application document directory.
final var fileName = basename(file.path);
final File localImage = await image.copy('$path/$fileName');
// Step 1: Save image/file path as string either db or shared pref
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString('test_image', localImage.path)
// Step 2: Loading image by using the path that we saved earlier. We can create a file using path
// and can use FileImage provider for loading image from file.
CircleAvatar(
backgroundImage: FileImage(File(prefs.getString('test_image')),
radius: 50,
backgroundColor: Colors.white)
希望能帮助和看到别人。给一个喜欢的
重新绘制边界
将对您有所帮助
final GlobalKey _repaintKey = new GlobalKey();
// Image Widget
Widget _buildQrImage() {
_avatar = RepaintBoundary(
key: _repaintKey,
child: Image.asset('assets/ifredom.jpg')
);
return Column(
children: <Widget>[
_avatar,
(imageFile == null)
? Image.asset('assets/default.jpg')
: Image.file(imageFile),
FlatButton(
child: Text("save"),
onPressed: () {
_saveScreenShot(context);
},
),
],
);
}
void _saveScreenShot(BuildContext context) {
RenderRepaintBoundary boundary = _repaintKey.currentContext.findRenderObject();
// ScreenShot and save
saveScreenShot(boundary, success: () {
saveScreenShot2SDCard(boundary, success: () {
showToast('save ok');
}, fail: () {
showToast('save ok');
});
}, fail: () {
showToast('save fail!');
});
}
final GlobalKey _repainkey=new GlobalKey();
//图像小部件
小部件_buildQrImage(){
_化身=重新绘制边界(
键:_重新绘制键,
子级:Image.asset('assets/ifredom.jpg')
);
返回列(
儿童:[
_阿凡达,
(imageFile==null)
?Image.asset('assets/default.jpg'))
:Image.file(imageFile),
扁平按钮(
子项:文本(“保存”),
已按下:(){
_保存屏幕截图(上下文);
},
),
],
);
}
void\u保存屏幕截图(BuildContext上下文){
RenderPaintBoundary=\u RepaitKey.currentContext.FindEnderObject();
//截图和保存
保存屏幕截图(边界,成功:(){
saveScreenShot2SDCard(边界,成功:(){
showtoos(‘保存ok’);
},失败:(){
showtoos(‘保存ok’);
});
},失败:(){
showtoos('save fail!');
});
}
这个文件是utils
颤振提供了一个重新绘制边界小部件来实现屏幕截图功能
RepaitBoundary用于包装需要截取的零件
RenderPaintBoundary可用于截取由RepaitBoundary包裹的零件
然后使用boundary.toImage()方法将其转换为ui.Image对象,然后Image.toByteData()将图像转换为byteData
最后通过file()将其存储为文件对象。WriteAsBytes():
导入'dart:async';
导入“dart:io”;
导入“dart:键入的_数据”;
将“dart:ui”导入为ui;
导入“package:flatter/rendering.dart”;
导入“package:path_provider/path_provider.dart”;
导入“package:permission_handler/permission_handler.dart”;
导入“package:Oktoos/Oktoos.dart”;
最终字符串scrawlImagePath='/screen_shot_scraw.png';
未来的getScreenShotFile()异步{
目录tempDir=await getTemporaryDirectory();
字符串tempPath='${tempDir.path}$scrawlImagePath';
文件映像=文件(临时路径);
bool isExist=wait image.exists();
返回isExist?图像:空;
}
未来的saveScreenShot2SDCard(渲染绘制边界,
{函数成功,函数失败})异步{
//检查存储权限。
PermissionHandler().requestPermissions([PermissionGroup.storage])。然后((映射){
if(映射[PermissionGroup.storage]==PermissionStatus.grated){
capturePng2List(边界)。然后((uint8List)异步{
if(uint8List==null | | uint8List.length==0){
如果(fail!=null)fail();
返回;
}
目录tempDir=等待getExternalStorageDirectory();
_saveImage(uint8List,目录(“${tempDir.path}/flatter_ui”),
“/screen\u shot\u scraw\u${DateTime.now()}.png”,
成功:成功,失败:失败);
});
}否则{
展示请打开SD卡存储权限!');
//如果(fail!=null)fail();
返回;
}
});
}
无效保存屏幕截图(渲染绘制边界,
{函数成功,函数失败}){
capturePng2List(边界)。然后((uint8List)异步{
if(uint8List==null | | uint8List.length==0){
如果(fail!=null)fail();
返回;
}
目录tempDir=await getTemporaryDirectory();
_saveImage(uint8List、tempDir、scrawlImagePath、,
成功:成功,失败:失败);
});
}
void\u saveImage(Uint8List Uint8List,目录目录,字符串文件名,
{函数成功,函数失败})异步{
bool isDirExist=等待目录(dir.path).exists();
if(!isDirExist)目录(dir.path).create();
字符串tempPath='${dir.path}$fileName';
文件映像=文件(临时路径);
bool isExist=wait image.exists();
if(isExist)等待image.delete();
文件(tempPath).writeAsBytes(uint8List).then((){
如果(success!=null)success();
});
}
Future capturePng2List(渲染绘制边界边界)异步{
图像=
wait boundary.toImage(像素比率:ui.window.devicePixelRatio);
ByteData ByteData=等待image.toByteData(格式:ui.ImageByteFormat.png);
Uint8List pngBytes=byteData.buffer.asUint8List();
返回PNG字节;
}
从图像选择器0.6.7开始
pickImage
、pickVideo
和retrieveLostData
已被弃用了
这些方法必须用新的方法来取代
getImage
getVideo
getLostData
getImage()
方法的示例用法:
...
File _storedImage;
...
void _takePicture() async {
// 1. Create an ImagePicker instance.
final ImagePicker _picker = ImagePicker();
// 2. Use the new method.
//
// getImage now returns a PickedFile instead of a File (form dart:io)
final PickedFile pickedImage = await _picker.getImage(...)
// 3. Check if an image has been picked or take with the camera.
if (pickedImage == null) {
return;
}
// 4. Create a File from PickedFile so you can save the file locally
// This is a new/additional step.
File tmpFile = File(pickedFile.path);
// 5. Get the path to the apps directory so we can save the file to it.
final String path = await getApplicationDocumentsDirectory().path;
final String fileName = basename(pickedFile.path); // Filename without extension
final String fileExtension = extension(pickedFile.path); // e.g. '.jpg'
// 6. Save the file by copying it to the new location on the device.
tmpFile = await tmpFile.copy('$path/$fileName$fileExtension');
// 7. Optionally, if you want to display the taken picture we need to update the state
// Note: Copying and awaiting the file needs to be done outside the setState function.
setState(() => _storedImage = tmpFile);
}
略为紧凑的示例:
File _image;
final picker = ImagePicker();
Future getImage() async {
final File pickedImage = await picker.getImage(source: ImageSource.camera);
if (pickedImage == null) return;
File tmpFile = File(pickedImage.path);
tmpFile = await tmpFile.copy(tmpFile.path);
setState(() {
_image = tmpFile;
});
}
要在本地保存文件,
final pickedFile = await picker.getImage(source: ImageSource.camera);
_image = File(pickedFile.path);
// getting a directory path for saving
final Directory extDir = await getApplicationDocumentsDirectory();
String dirPath = extDir.path;
final String filePath = '$dirPath/image.png';
// copy the file to a new path
final File newImage = await _image.copy(filePath);
setState(() {
if (pickedFile != null) {
_image = newImage;
} else {
print('No image selected.');
}
});