如何压缩扑来上传图像?

发布于 2025-01-18 05:03:08 字数 754 浏览 4 评论 0原文

如何压缩 flutter 上传的图像?

现在,我已经使用了这种方法,但是我需要压缩图像文件然后上传到firestore。

SimpleDialogOption(
              padding: const EdgeInsets.all(20),
              child: const Text('Take a photo'),
              onPressed: () async {
                Navigator.of(context).pop();
                Uint8List file = await pickImage(ImageSource.camera);
                setState(() {
                  _file = file;
                });
              },
            ),

我见过类似的方法;但不知道如何改变它。

File _image;

  Future getImage() async {
    var image = await ImagePicker.pickImage(
        source: ImageSource.gallery,  
                imageQuality: 25,
    );

    setState(() {
      _image = image;
    });
  }

how can do compress upload image from flutter?

Now, I had used this methods, but I needs to compress image file then upload to firestore.

SimpleDialogOption(
              padding: const EdgeInsets.all(20),
              child: const Text('Take a photo'),
              onPressed: () async {
                Navigator.of(context).pop();
                Uint8List file = await pickImage(ImageSource.camera);
                setState(() {
                  _file = file;
                });
              },
            ),

I had saw similar this methods; but no idea how to change it.

File _image;

  Future getImage() async {
    var image = await ImagePicker.pickImage(
        source: ImageSource.gallery,  
                imageQuality: 25,
    );

    setState(() {
      _image = image;
    });
  }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

漫雪独思 2025-01-25 05:03:08

请参阅下面的代码示例,以选择多个图像并压缩所有采摘的图像。

我使用了以下包

images_picker: ^1.2.4

flutter_image_compress: ^0.7.0

class PickMultipleImagesScreen extends StatefulWidget {
  const PickMultipleImagesScreen({Key key}) : super(key: key);

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

class _PickMultipleImagesScreenState extends State<PickMultipleImagesScreen> {
  final ValueNotifier<bool> attachMultipleImages = ValueNotifier<bool>(false);
  List compressedPhotosList = ["place_holder"];
  int maxImagesCount = 5;

  pickPhotos() async {
    List<Media> photosList = [];
    photosList = await ImagesPicker.pick(
      count: (compressedPhotosList != null &&
              (compressedPhotosList.isNotEmpty) &&
              (compressedPhotosList.length > 1))
          ? (maxImagesCount + 1 - compressedPhotosList.length)
          : maxImagesCount,
      pickType: PickType.all,
      language: Language.System,
      cropOpt: CropOption(
        aspectRatio: CropAspectRatio(600, 400),
      ),
    );

    if (photosList != null && photosList.isNotEmpty && photosList.length > 0) {
      for (int i = 0; i < photosList.length; i++) {
        File photoCompressedFile =
            await compressImage(File(photosList[i].path));
        print("Images List: $photosList");
        print("Path of UnCompressed File: ${photosList[i].path}");
        compressedPhotosList.insert(
          0,
          photoCompressedFile.path.toString(),
        );
        print("Path of Compressed File: ${photoCompressedFile.path}");
        print("Compressed Images List: $compressedPhotosList");
      }
      attachMultipleImages.value = !attachMultipleImages.value;
    }
  }

  Future<File> compressImage(File file) async {
    final filePath = file.absolute.path;
    final lastIndex = filePath.lastIndexOf(new RegExp(r'.png|.jp'));
    final splitted = filePath.substring(0, (lastIndex));
    final outPath = "${splitted}_out${filePath.substring(lastIndex)}";

    if (lastIndex == filePath.lastIndexOf(new RegExp(r'.png'))) {
      final compressedImage = await FlutterImageCompress.compressAndGetFile(
          filePath, outPath,
          minWidth: 1000,
          minHeight: 1000,
          quality: 50,
          format: CompressFormat.png);
      return compressedImage;
    } else {
      final compressedImage = await FlutterImageCompress.compressAndGetFile(
        filePath,
        outPath,
        minWidth: 1000,
        minHeight: 1000,
        quality: 50,
      );
      return compressedImage;
    }
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: ValueListenableBuilder<bool>(
        valueListenable: attachMultipleImages,
        builder: (context, snapshot, child) {
          return Scaffold(
            body: (compressedPhotosList != null &&
                    compressedPhotosList.isNotEmpty &&
                    compressedPhotosList.length > 1)
                ? GridView.builder(
                    itemCount: (compressedPhotosList != null &&
                            compressedPhotosList.isNotEmpty &&
                            compressedPhotosList.length > 1 &&
                            (compressedPhotosList.length - 1 == maxImagesCount))
                        ? compressedPhotosList.length - 1
                        : compressedPhotosList.length,
                    shrinkWrap: true,
                    physics: NeverScrollableScrollPhysics(),
                    gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                        crossAxisCount: 3,
                        crossAxisSpacing: 4.0,
                        mainAxisSpacing: 4.0),
                    itemBuilder: (BuildContext context, int index) {
                      return ((compressedPhotosList[index] == "place_holder") &&
                              compressedPhotosList.length - 1 != maxImagesCount)
                          ? InkWell(
                              onTap: () async {
                                if (compressedPhotosList.length - 1 !=
                                    maxImagesCount) {
                                  pickPhotos();
                                }
                              },
                              child: Container(
                                margin: EdgeInsets.all(
                                  5.0,
                                ),
                                width: ScreenUtil().screenWidth,
                                height: ScreenUtil().setHeight(105.0),
                                color: Colors.blueAccent,
                                child: Center(
                                  child: Icon(
                                    Icons.add,
                                    size: ScreenUtil().setSp(24.0),
                                    color: Colors.grey,
                                  ),
                                ),
                              ),
                            )
                          : Stack(
                              clipBehavior: Clip.none,
                              children: [
                                ClipRRect(
                                  borderRadius: BorderRadius.circular(4.0),
                                  child: Image.file(
                                    File(compressedPhotosList[index]),
                                    fit: BoxFit.fitHeight,
                                    width: ScreenUtil().screenWidth,
                                    height: ScreenUtil().setHeight(105.0),
                                    filterQuality: FilterQuality.low,
                                    errorBuilder: (context, error, stackTrace) {
                                      return Container(
                                        width: ScreenUtil().screenWidth,
                                        height: ScreenUtil().setHeight(105.0),
                                        color: Colors.black,
                                      );
                                    },
                                  ),
                                ),
                                Positioned(
                                  bottom: 10,
                                  right: 8,
                                  child: InkWell(
                                    onTap: () async {
                                      compressedPhotosList.removeAt(index);
                                      attachMultipleImages.value =
                                          !attachMultipleImages.value;
                                    },
                                    child: CircleAvatar(
                                      radius: 15.0,
                                      backgroundColor: Colors.black45,
                                      child: Icon(
                                        Icons.delete_forever,
                                        color: Colors.white,
                                        size: 20,
                                      ),
                                    ),
                                  ),
                                )
                              ],
                            );
                    },
                  )
                : Center(
                    child: InkWell(
                      onTap: () {
                        pickPhotos();
                      },
                      child: Text("Attach Images"),
                    ),
                  ),
          );
        }
      ),
    );
  }
}

Please refer to below code example of picking multiple images and compress all the picked images.

I have used these following packages

images_picker: ^1.2.4

flutter_image_compress: ^0.7.0

class PickMultipleImagesScreen extends StatefulWidget {
  const PickMultipleImagesScreen({Key key}) : super(key: key);

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

class _PickMultipleImagesScreenState extends State<PickMultipleImagesScreen> {
  final ValueNotifier<bool> attachMultipleImages = ValueNotifier<bool>(false);
  List compressedPhotosList = ["place_holder"];
  int maxImagesCount = 5;

  pickPhotos() async {
    List<Media> photosList = [];
    photosList = await ImagesPicker.pick(
      count: (compressedPhotosList != null &&
              (compressedPhotosList.isNotEmpty) &&
              (compressedPhotosList.length > 1))
          ? (maxImagesCount + 1 - compressedPhotosList.length)
          : maxImagesCount,
      pickType: PickType.all,
      language: Language.System,
      cropOpt: CropOption(
        aspectRatio: CropAspectRatio(600, 400),
      ),
    );

    if (photosList != null && photosList.isNotEmpty && photosList.length > 0) {
      for (int i = 0; i < photosList.length; i++) {
        File photoCompressedFile =
            await compressImage(File(photosList[i].path));
        print("Images List: $photosList");
        print("Path of UnCompressed File: ${photosList[i].path}");
        compressedPhotosList.insert(
          0,
          photoCompressedFile.path.toString(),
        );
        print("Path of Compressed File: ${photoCompressedFile.path}");
        print("Compressed Images List: $compressedPhotosList");
      }
      attachMultipleImages.value = !attachMultipleImages.value;
    }
  }

  Future<File> compressImage(File file) async {
    final filePath = file.absolute.path;
    final lastIndex = filePath.lastIndexOf(new RegExp(r'.png|.jp'));
    final splitted = filePath.substring(0, (lastIndex));
    final outPath = "${splitted}_out${filePath.substring(lastIndex)}";

    if (lastIndex == filePath.lastIndexOf(new RegExp(r'.png'))) {
      final compressedImage = await FlutterImageCompress.compressAndGetFile(
          filePath, outPath,
          minWidth: 1000,
          minHeight: 1000,
          quality: 50,
          format: CompressFormat.png);
      return compressedImage;
    } else {
      final compressedImage = await FlutterImageCompress.compressAndGetFile(
        filePath,
        outPath,
        minWidth: 1000,
        minHeight: 1000,
        quality: 50,
      );
      return compressedImage;
    }
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: ValueListenableBuilder<bool>(
        valueListenable: attachMultipleImages,
        builder: (context, snapshot, child) {
          return Scaffold(
            body: (compressedPhotosList != null &&
                    compressedPhotosList.isNotEmpty &&
                    compressedPhotosList.length > 1)
                ? GridView.builder(
                    itemCount: (compressedPhotosList != null &&
                            compressedPhotosList.isNotEmpty &&
                            compressedPhotosList.length > 1 &&
                            (compressedPhotosList.length - 1 == maxImagesCount))
                        ? compressedPhotosList.length - 1
                        : compressedPhotosList.length,
                    shrinkWrap: true,
                    physics: NeverScrollableScrollPhysics(),
                    gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                        crossAxisCount: 3,
                        crossAxisSpacing: 4.0,
                        mainAxisSpacing: 4.0),
                    itemBuilder: (BuildContext context, int index) {
                      return ((compressedPhotosList[index] == "place_holder") &&
                              compressedPhotosList.length - 1 != maxImagesCount)
                          ? InkWell(
                              onTap: () async {
                                if (compressedPhotosList.length - 1 !=
                                    maxImagesCount) {
                                  pickPhotos();
                                }
                              },
                              child: Container(
                                margin: EdgeInsets.all(
                                  5.0,
                                ),
                                width: ScreenUtil().screenWidth,
                                height: ScreenUtil().setHeight(105.0),
                                color: Colors.blueAccent,
                                child: Center(
                                  child: Icon(
                                    Icons.add,
                                    size: ScreenUtil().setSp(24.0),
                                    color: Colors.grey,
                                  ),
                                ),
                              ),
                            )
                          : Stack(
                              clipBehavior: Clip.none,
                              children: [
                                ClipRRect(
                                  borderRadius: BorderRadius.circular(4.0),
                                  child: Image.file(
                                    File(compressedPhotosList[index]),
                                    fit: BoxFit.fitHeight,
                                    width: ScreenUtil().screenWidth,
                                    height: ScreenUtil().setHeight(105.0),
                                    filterQuality: FilterQuality.low,
                                    errorBuilder: (context, error, stackTrace) {
                                      return Container(
                                        width: ScreenUtil().screenWidth,
                                        height: ScreenUtil().setHeight(105.0),
                                        color: Colors.black,
                                      );
                                    },
                                  ),
                                ),
                                Positioned(
                                  bottom: 10,
                                  right: 8,
                                  child: InkWell(
                                    onTap: () async {
                                      compressedPhotosList.removeAt(index);
                                      attachMultipleImages.value =
                                          !attachMultipleImages.value;
                                    },
                                    child: CircleAvatar(
                                      radius: 15.0,
                                      backgroundColor: Colors.black45,
                                      child: Icon(
                                        Icons.delete_forever,
                                        color: Colors.white,
                                        size: 20,
                                      ),
                                    ),
                                  ),
                                )
                              ],
                            );
                    },
                  )
                : Center(
                    child: InkWell(
                      onTap: () {
                        pickPhotos();
                      },
                      child: Text("Attach Images"),
                    ),
                  ),
          );
        }
      ),
    );
  }
}

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文