当前位置:   article > 正文

Flutter之下载网络图片并保存到本地文件夹_flutter保存图片到本地

flutter保存图片到本地

图片地址:https://img03.sogoucdn.com/v2/thumb/retype_exclude_gif/ext/auto/crop/xy/ai/w/1284/h/722?appid=200698&url=https://pic.baike.soso.com/ugc/baikepic2/24446/cut-20211222173333-829293243_jpg_1308_872_50708.jpg/0

因为图片是二进制数据的形式存储在计算机中的,所以保存图片到本地必须使用二进制数据。

下载图片

  1. //下载图片
  2. var result = await HttpManager.getInstance().get(
  3. "https://img03.sogoucdn.com/v2/thumb/retype_exclude_gif/ext/auto/crop/xy/ai/w/1284/h/722?appid=200698&url=https://pic.baike.soso.com/ugc/baikepic2/24446/cut-20211222173333-829293243_jpg_1308_872_50708.jpg/0",
  4. //将返回类型设置为二进制,此时的result是二进制数据,保存的是图片的字节数组
  5. option: Options(responseType: ResponseType.bytes));

选择本地文件夹

此时需利用file_picker: ^5.3.3 包

  • 添加依赖

  •  选择文件目录

  1. //选择文档目录
  2. //selectedDirectory是选择的文件夹的地址 C:\Users\lanlian\Desktop\沈成林\休闲娱乐来一套\下载图片
  3. String? selectedDirectory = await FilePicker.platform.getDirectoryPath();
  4. if (selectedDirectory == null) {
  5. print("请选择正确的文件地址");
  6. return;
  7. }
  8. else{}

此时需要判断选择的文档地址是否为空,如果则退出选择,不为空则继续操作

保存图片

  • 创建一个名为$name的新文件(要将图片保存到这里)

此时需要判断保存的图片是否已经存在,如果已经存在则退出

  1. //创建一个名为download1.jpg的新文件
  2. File image_file=File('${selectedDirectory}/download1.jpg');
  3. if(image_file.existsSync()){
  4. print("图片已存在");
  5. return;
  6. }
  • 将下载获取的图片的字节信息写入这个新文件
  1. //从网络上下载的图片的字节数组写入该文件中。
  2. image_file.writeAsBytes(result);

完整代码 

  1. Future<void> saveImage() async {
  2. print("保存图片到本地");
  3. //下载图片
  4. var result = await HttpManager.getInstance().get(
  5. "https://img03.sogoucdn.com/v2/thumb/retype_exclude_gif/ext/auto/crop/xy/ai/w/1284/h/722?appid=200698&url=https://pic.baike.soso.com/ugc/baikepic2/24446/cut-20211222173333-829293243_jpg_1308_872_50708.jpg/0",
  6. //将返回类型设置为二进制,此时的result是二进制数据,保存的是图片的字节数组
  7. option: Options(responseType: ResponseType.bytes));
  8. //选择文档目录
  9. //selectedDirectory是选择的文件夹的地址 C:\Users\lanlian\Desktop\沈成林\休闲娱乐来一套\下载图片
  10. String? selectedDirectory = await FilePicker.platform.getDirectoryPath();
  11. if (selectedDirectory == null) {
  12. print("请选择正确的文件地址");
  13. return;
  14. }
  15. else{
  16. print("selectedDirectory:${selectedDirectory}");
  17. //创建一个名为download1.jpg的新文件
  18. File image_file=File('${selectedDirectory}/download1.jpg');
  19. if(image_file.existsSync()){
  20. print("图片已存在");
  21. return;
  22. }
  23. //从网络上下载的图片的字节数组写入该文件中。
  24. image_file.writeAsBytes(result);
  25. }
  26. }

 

本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号