【问题标题】:Flutter How to save Image file to new folder in gallery?Flutter 如何将图像文件保存到图库中的新文件夹?
【发布时间】:2019-07-01 02:15:31
【问题描述】:

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

 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";
});

【问题讨论】:

    标签: image flutter


    【解决方案1】:

    您需要将图像保存到外部存储目录中才能在图库中显示图像。 不获取临时目录,而是获取外部存储目录。

    final directory = await getExternalStorageDirectory();
    

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

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

    【讨论】:

    • 那行得通..比如何计算该文件夹中的文件? @Krishnakumar CN
    • 是的,它已经完成并添加这个 img.Image images = img.decodeImage(kompresimg.readAsBytesSync()); new File('${testdir.path}/image_$baru$rand.jpg') ..writeAsBytesSync(img.encodePng(images));
    • @krishnakumarcn - 我们如何编写视频文件?请建议。谢谢。
    • 无论文件类型如何,您都可以重复使用此方法。确保您提供了正确的文件扩展名。 @Kamlesh
    猜你喜欢
    • 1970-01-01
    • 2021-08-12
    • 2018-04-01
    • 2014-12-11
    • 1970-01-01
    • 2018-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多