在颤振中重命名文件/图像

Utt*_*ila 9 android ios dart flutter imagepicker

我正在使用image_picker: ^0.6.2+3包从图库中选择图像/拍照。

File picture = await ImagePicker.pickImage(
  maxWidth: 800,
  imageQuality: 10,
  source: source, // source can be either ImageSource.camera or ImageSource.gallery
  maxHeight: 800,
);
Run Code Online (Sandbox Code Playgroud)

我得到picture.path

/用户/[一些路径]/tmp/image_picker_A0EBD0C1-EF3B-417F-9F8A-5DFBA889118C-18492-00001AD95CF914D3.jpg

现在我想将图像重命名为case01wd03id01.jpg

注意:我不想将其移动到新文件夹

我该如何重命名?我在官方文档中找不到它。

Man*_*Raj 10

首先导入路径包。

import 'package:path/path.dart' as path;
Run Code Online (Sandbox Code Playgroud)

然后创建一个新的目标路径来重命名文件。

File picture = await ImagePicker.pickImage(
        maxWidth: 800,
        imageQuality: 10,
        source: ImageSource.camera,
        maxHeight: 800,
);
print('Original path: ${picture.path}');
String dir = path.dirname(picture.path);
String newPath = path.join(dir, 'case01wd03id01.jpg');
print('NewPath: ${newPath}');
picture.renameSync(newPath);
Run Code Online (Sandbox Code Playgroud)


Den*_*dan 9

使用此功能仅重命名文件,而不改变文件路径。您可以在有或没有image_picker的情况下使用此函数。

import 'dart:io';

Future<File> changeFileNameOnly(File file, String newFileName) {
  var path = file.path;
  var lastSeparator = path.lastIndexOf(Platform.pathSeparator);
  var newPath = path.substring(0, lastSeparator + 1) + newFileName;
  return file.rename(newPath);
}
Run Code Online (Sandbox Code Playgroud)

阅读有关 Dart SDK 的 file.dart 中的更多文档。


Gil*_*ton 5

从那时起,曼尼什·拉杰的答案对我不起作用image_picker: ^0.6.7。他们最近在获取返回的图像或视频PickedFile而不是File.

我使用的新方法是从 转换为PickedFileFile然后使用新名称将其复制到应用程序目录。该方法需要path_provider.dart

import 'package:path_provider/path_provider.dart';

...
...

PickedFile pickedFile = await _picker.getImage(source: ImageSource.camera);

// Save and Rename file to App directory
String dir = (await getApplicationDocumentsDirectory()).path;
String newPath = path.join(dir, 'case01wd03id01.jpg');
File f = await File(pickedF.path).copy(newPath);
Run Code Online (Sandbox Code Playgroud)

我知道问题表明他们不想将其移动到新文件夹,但这是我能找到的使重命名工作的最佳方法。