【问题标题】:How to get the Image out of a chosen Image by gallery or camera in Flutter (don't want to show it on screen)?如何通过 Flutter 中的画廊或相机从所选图像中获取图像(不想在屏幕上显示)?
【发布时间】:2021-02-19 21:05:55
【问题描述】:

我有以下 Flutter / dart 代码,可让我打开相机/图库以选择图片。但我不想立即在屏幕上显示图像(就像这里一样)。我希望图像来处理它,所以可能会保存它或获取像'Image.asset(“”)'这样的图像。主要是我可以在选择图像后对它做一些事情。

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {


  Future<File> imageFile;
  pickImageFromGallery(ImageSource source) {
    setState(() {

    });
    imageFile = ImagePicker.pickImage(source: source);
  }

  Widget showImage() {
    return FutureBuilder<File>(
      future: imageFile,
      builder: (BuildContext context, AsyncSnapshot<File> snapshot) {
        if (snapshot.connectionState == ConnectionState.done && snapshot.data != null) {
          return Image.file(
            snapshot.data,
            width: 300,
            height: 300,
          );

        }
        else {
          return Text("error");
        }
      },
    );
  }

  bildmachen(ImageSource quelle) {
    pickImageFromGallery(quelle);
    Widget bildAusgabe = showImage();
    Navigator.of(context).push(MaterialPageRoute(
        builder: (BuildContext context) => Bildzeige(bildAusgabe)));

  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            showImage,
            RaisedButton(
              child: Text("gehtschon?"),
              onPressed: () {
                bildmachen(ImageSource.gallery);
              },
            ),
          ],
        ),
      ),
      backgroundColor: Colors.yellowAccent,
    );
  }
}

谢谢

【问题讨论】:

    标签: image flutter dart imagepicker


    【解决方案1】:

    如果要将 ImagePicker 中选择的图像保存在 File 对象中 你可以这样做

    File _imageFile;
    final picker = ImagePicker();
    .
    .
    .
    Future getImage() async {
        final pickedFile = await picker.getImage(source: ImageSource.gallery);
    
        setState(() {
          if (pickedFile != null) {
            _imageFile = File(pickedFile.path);
          }
        });
      }
    // the getImage() method will opens the ImagePicker and the selected image will be stored in _imageFile
    

    我希望这个解决方案有帮助

    【讨论】:

    • 如果你想显示图像你可以执行以下操作:Image.file(_imageFile, fit: BoxFit.cover),
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-12
    • 1970-01-01
    • 1970-01-01
    • 2019-09-30
    相关资源
    最近更新 更多