问题描述
我有一个图像网址,例如“ https://example.com/xyz.jpg”。现在,我想将图像放入文件类型变量中;
遵循以下原则:
File f = File("https://example.com/xyz.jpg");
重点是从给定的URL获取图像并将其另存为File变量。我该怎么办? 我在互联网上搜索了许多解决方案,但没有直接的方法。
PS:我可能会漏掉类似回答问题的内容,所以请让我知道可以找到它的链接。
编辑:我正在使用文件类型变量在共享函数中传递它。 This是我正在使用的库。
这是我当前的共享按钮点击代码
if (file != null) {
ShareExtend.share(file.path,"image",sharePanelTitle: "share image title",subject: "share image subject");
}
感谢您的帮助。
解决方法
您需要下载图像并创建一个空文件,然后用图像数据填充该文件:
import 'dart:io';
import 'package:http/http.dart' as http;
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
Future<File> _fileFromImageUrl() async {
final response = await http.get('https://example.com/xyz.jpg');
final documentDirectory = await getApplicationDocumentsDirectory();
final file = File(join(documentDirectory.path,'imagetest.png'));
file.writeAsBytesSync(response.bodyBytes);
return file;
}