小编典典

Flutter如何将图像文件保存到图库中的新文件夹?

flutter

我想从相机获取文件后将图像保存在图库中,如何创建新目录并保存从相机获取的图像文件?

 Future getImageCamera() async {
var imageFile = await ImagePicker.pickImage(
    source: ImageSource.camera, maxHeight: 20.0, maxWidth: 20.0);

DateTime ketF = new DateTime.now();
String baru = "${ketF.year}${ketF.month}${ketF.day}";

//proses kompres
final temDirk = await getTemporaryDirectory();
final pathss = temDirk.path;

int rand = new math.Random().nextInt(100000);

//mengganti nama file
// String juduld = controllerJudul.text;

img.Image gambard = img.decodeImage(imageFile.readAsBytesSync());
img.Image gambarKecilx = img.copyResize(gambard,
    700); //parameter awal adalah sumber gambar // parameter kedua ukuran width, hp=>1k

var kompresimg = new File("$pathss/image_$baru$rand.jpg")
  ..writeAsBytesSync(img.encodeJpg(gambarKecilx, quality: 95));

setState(() {
  _gambar = kompresimg;
  namafile = "image_$baru$rand.jpg";
});

阅读 732

收藏
2020-08-13

共1个答案

小编典典

您需要将图像保存到外部存储目录中,以便在图库中显示图像。代替获取临时目录,而获取外部存储目录。

final directory = await getExternalStorageDirectory();

您需要提供AndroidManifest.xml文件android/app/src/main夹文件的权限

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

然后假设您要创建一个名为MyImages的文件夹,并将新图像添加到该文件夹​​中,

final myImagePath = '${directory.path}/MyImages' ;
final myImgDir = await new Directory(myImagePath).create();

然后将文件写入路径。

var kompresimg = new File("$myImagePath/image_$baru$rand.jpg")
  ..writeAsBytesSync(img.encodeJpg(gambarKecilx, quality: 95));

要获取文件数量,只需将文件获取到列表中并检查列表的长度

var listOfFiles = await myImgDir.list(recursive: true).toList();
var count = countList.length;
2020-08-13