Flutter图片选择插件images_picker_sellon的使用

Flutter图片选择插件images_picker_sellon的使用

简介

images_picker_sellon 是一个用于从Android和iOS设备中选择图片或视频的Flutter插件。此外,它还支持通过相机拍摄图片或录制视频,并将图片或视频保存到相册中。

功能支持:

  • 从相册中选择多张图片或视频(微信样式)。
  • 使用相机拍摄图片或录制视频。
  • 自定义裁剪图片(支持指定宽高比)。
  • 压缩图片(支持设置质量或最大大小)。
  • 将图片或视频保存到相册中。
  • 支持的语言:系统语言、简体中文、繁体中文、英文、日文、法文、韩文、德文、越南语等。

安装

iOS配置:

Info.plist 文件中添加以下权限描述:

<key>NSCameraUsageDescription</key>
<string>Example usage description</string>
<key>NSMicrophoneUsageDescription</key>
<string>Example usage description</string>
<key>NSPhotoLibraryUsageDescription</key>
<string>Example usage description</string>

Android配置:

AndroidManifest.xml 中添加以下权限:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />

同时,在 android/app/build.gradle 文件中设置最低SDK版本为21:

minSdkVersion 21

pubspec.yaml 中添加依赖:

images_picker: ^最新版本号

导入包:

import 'package:images_picker_sellon/images_picker.dart';

使用方法

1. 从相册中选择图片

Future<void> getImage() async {
  List<Media>? res = await ImagesPicker.pick(
    count: 3, // 选择数量
    pickType: PickType.image, // 选择类型为图片
  );
  if (res != null) {
    print(res.map((e) => e.path).toList()); // 打印选中的图片路径
  }
}

2. 从相册中选择视频

Future<void> getVideo() async {
  List<Media>? res = await ImagesPicker.pick(
    count: 3, // 选择数量
    pickType: PickType.video, // 选择类型为视频
  );
  if (res != null) {
    print(res.map((e) => e.path).toList()); // 打印选中的视频路径
  }
}

3. 打开相机拍摄图片

Future<void> openCameraForImage() async {
  List<Media>? res = await ImagesPicker.openCamera(
    pickType: PickType.image, // 拍摄类型为图片
    quality: 0.8, // 设置图片压缩质量
    maxSize: 800, // 设置图片最大大小(单位KB)
    maxTime: 15, // 设置录制视频的最大时间(秒)
  );
  if (res != null) {
    print(res[0].path); // 打印拍摄的图片路径
  }
}

4. 打开相机录制视频

Future<void> openCameraForVideo() async {
  List<Media>? res = await ImagesPicker.openCamera(
    pickType: PickType.video, // 拍摄类型为视频
    maxTime: 30, // 设置录制视频的最大时间(秒)
  );
  if (res != null) {
    print(res[0].path); // 打印录制的视频路径
  }
}

5. 添加GIF支持

Future<void> pickWithGif() async {
  List<Media>? res = await ImagesPicker.pick(
    count: 3,
    pickType: PickType.all, // 允许选择图片和视频
    gif: true, // 启用GIF支持
  );
  if (res != null) {
    print(res.map((e) => e.path).toList()); // 打印选中的文件路径
  }
}

6. 保存网络图片到相册

Future<void> saveNetworkImageToAlbum() async {
  File file = await downloadFile('https://cdn.chavesgu.com/logo.png');
  bool res = await ImagesPicker.saveImageToAlbum(file, albumName: "chaves");
  print(res); // 打印保存结果
}

Future<File> downloadFile(String url) async {
  Dio dio = Dio();
  String savePath = Directory.systemTemp.path + '/' + url.split('/').last;
  await dio.download(url, savePath, options: Options(responseType: ResponseType.bytes));
  print(savePath);
  return File(savePath);
}

7. 保存网络视频到相册

Future<void> saveNetworkVideoToAlbum() async {
  File file = await downloadFile('https://cdn.chavesgu.com/SampleVideo.mp4');
  bool res = await ImagesPicker.saveVideoToAlbum(file, albumName: "chaves");
  print(res); // 打印保存结果
}

Future<File> downloadFile(String url) async {
  Dio dio = Dio();
  String savePath = Directory.systemTemp.path + '/' + url.split('/').last;
  await dio.download(url, savePath, options: Options(responseType: ResponseType.bytes));
  print(savePath);
  return File(savePath);
}

8. 设置语言

Future<void> pickWithCustomLanguage() async {
  List<Media>? res = await ImagesPicker.pick(
    language: Language.Chinese, // 设置语言为简体中文
  );
  if (res != null) {
    print(res.map((e) => e.path).toList()); // 打印选中的文件路径
  }
}

参数说明

以下是所有可用参数的详细说明:

// 通用参数
int count = 1, // 选择数量
PickType pickType = PickType.image, // 选择类型
bool gif = true, // 是否启用GIF支持
int maxTime = 120, // 最大录制时间(秒)
CropOption cropOpt, // 裁剪选项
int maxSize, // 图片最大大小(单位KB)
double quality, // 图片压缩质量

// 相机参数
PickType pickType = PickType.image, // 拍摄类型
int maxTime = 15, // 最大录制时间(秒)
CropOption cropOpt, // 裁剪选项
int maxSize, // 图片最大大小(单位KB)
double quality, // 图片压缩质量

ProGuard规则

-keep class com.luck.picture.lib.** { *; }

-dontwarn com.yalantis.ucrop**
-keep class com.yalantis.ucrop** { *; }
-keep interface com.yalantis.ucrop** { *; }

许可证

本项目采用 MIT 许可证。


完整示例代码

import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'dart:async';

import 'package:images_picker_sellon/images_picker.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  [@override](/user/override)
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String? path;

  [@override](/user/override)
  void initState() {
    super.initState();
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('images_picker_sellon示例'),
        ),
        body: Column(
          children: [
            ElevatedButton(
              child: Text('从相册选择图片'),
              onPressed: () async {
                List<Media>? res = await ImagesPicker.pick(
                  count: 3,
                  pickType: PickType.image,
                );
                if (res != null) {
                  print(res.map((e) => e.path).toList());
                  setState(() {
                    path = res[0].thumbPath;
                  });
                }
              },
            ),
            ElevatedButton(
              child: Text('从相册选择视频'),
              onPressed: () async {
                List<Media>? res = await ImagesPicker.pick(
                  count: 3,
                  pickType: PickType.video,
                );
                if (res != null) {
                  print(res.map((e) => e.path).toList());
                  setState(() {
                    path = res[0].thumbPath;
                  });
                }
              },
            ),
            ElevatedButton(
              child: Text('打开相机拍摄图片'),
              onPressed: () async {
                List<Media>? res = await ImagesPicker.openCamera(
                  pickType: PickType.image,
                  quality: 0.8,
                  maxSize: 800,
                  maxTime: 15,
                );
                if (res != null) {
                  print(res[0].path);
                  setState(() {
                    path = res[0].thumbPath;
                  });
                }
              },
            ),
            ElevatedButton(
              child: Text('打开相机录制视频'),
              onPressed: () async {
                List<Media>? res = await ImagesPicker.openCamera(
                  pickType: PickType.video,
                  maxTime: 30,
                );
                if (res != null) {
                  print(res[0].path);
                  setState(() {
                    path = res[0].thumbPath;
                  });
                }
              },
            ),
            ElevatedButton(
              child: Text('保存网络图片到相册'),
              onPressed: () async {
                File file = await downloadFile('https://cdn.chavesgu.com/logo.png');
                bool res = await ImagesPicker.saveImageToAlbum(file, albumName: "chaves");
                print(res);
              },
            ),
            ElevatedButton(
              child: Text('保存网络视频到相册'),
              onPressed: () async {
                File file = await downloadFile('https://cdn.chavesgu.com/SampleVideo.mp4');
                bool res = await ImagesPicker.saveVideoToAlbum(file, albumName: "chaves");
                print(res);
              },
            ),
            path != null
                ? Container(
                    height: 200,
                    child: Image.file(
                      File(path!),
                      fit: BoxFit.contain,
                    ),
                  )
                : SizedBox.shrink(),
          ],
        ),
      ),
    );
  }

  Future<File> downloadFile(String url) async {
    Dio dio = Dio();
    String savePath = Directory.systemTemp.path + '/' + url.split('/').last;
    await dio.download(url, savePath, options: Options(responseType: ResponseType.bytes));
    print(savePath);
    return File(savePath);
  }
}

更多关于Flutter图片选择插件images_picker_sellon的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter图片选择插件images_picker_sellon的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


images_picker_sellon 是一个 Flutter 插件,用于从设备的相册或相机中选择图片。它提供了简单易用的 API,允许开发者轻松地集成图片选择功能到 Flutter 应用中。

安装插件

首先,你需要在 pubspec.yaml 文件中添加 images_picker_sellon 插件的依赖:

dependencies:
  flutter:
    sdk: flutter
  images_picker_sellon: ^1.0.0  # 请使用最新版本

然后运行 flutter pub get 来安装插件。

使用插件

1. 导入插件

在你的 Dart 文件中导入 images_picker_sellon 插件:

import 'package:images_picker_sellon/images_picker_sellon.dart';

2. 选择图片

使用 ImagesPickerSellon.pickImages 方法来选择图片。你可以选择从相册或相机中获取图片。

Future<void> pickImage() async {
  try {
    // 从相册中选择图片
    List<ImageFile>? images = await ImagesPickerSellon.pickImages(
      maxCount: 1, // 最多选择1张图片
      pickType: PickType.gallery, // 从相册中选择
    );

    if (images != null && images.isNotEmpty) {
      // 获取选择的图片
      ImageFile image = images.first;
      print('Selected image path: ${image.path}');
      // 你可以在这里处理图片,比如显示在界面上
    }
  } catch (e) {
    print('Error picking image: $e');
  }
}

3. 从相机拍照

如果你想从相机拍照,可以将 pickType 设置为 PickType.camera

Future<void> takePhoto() async {
  try {
    // 从相机拍照
    List<ImageFile>? images = await ImagesPickerSellon.pickImages(
      maxCount: 1, // 最多选择1张图片
      pickType: PickType.camera, // 从相机拍照
    );

    if (images != null && images.isNotEmpty) {
      // 获取拍摄的图片
      ImageFile image = images.first;
      print('Captured image path: ${image.path}');
      // 你可以在这里处理图片,比如显示在界面上
    }
  } catch (e) {
    print('Error taking photo: $e');
  }
}

4. 处理多张图片

如果你允许用户选择多张图片,可以设置 maxCount 为大于1的值:

Future<void> pickMultipleImages() async {
  try {
    // 从相册中选择多张图片
    List<ImageFile>? images = await ImagesPickerSellon.pickImages(
      maxCount: 5, // 最多选择5张图片
      pickType: PickType.gallery, // 从相册中选择
    );

    if (images != null && images.isNotEmpty) {
      // 处理选择的图片
      for (var image in images) {
        print('Selected image path: ${image.path}');
      }
    }
  } catch (e) {
    print('Error picking images: $e');
  }
}

注意事项

  1. 权限:在使用相机或访问相册时,确保你已经请求了相应的权限。你可以在 AndroidManifest.xmlInfo.plist 中添加相应的权限声明。

  2. 错误处理:在实际应用中,建议对可能出现的错误进行捕获和处理,以提供更好的用户体验。

  3. 插件版本:请确保使用最新版本的插件,以获得最新的功能和修复。

示例代码

以下是一个完整的示例代码,展示了如何使用 images_picker_sellon 插件从相册中选择图片并显示在界面上:

import 'package:flutter/material.dart';
import 'package:images_picker_sellon/images_picker_sellon.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: ImagePickerExample(),
    );
  }
}

class ImagePickerExample extends StatefulWidget {
  [@override](/user/override)
  _ImagePickerExampleState createState() => _ImagePickerExampleState();
}

class _ImagePickerExampleState extends State<ImagePickerExample> {
  String? _imagePath;

  Future<void> _pickImage() async {
    try {
      List<ImageFile>? images = await ImagesPickerSellon.pickImages(
        maxCount: 1,
        pickType: PickType.gallery,
      );

      if (images != null && images.isNotEmpty) {
        setState(() {
          _imagePath = images.first.path;
        });
      }
    } catch (e) {
      print('Error picking image: $e');
    }
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Image Picker Example'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            _imagePath != null
                ? Image.file(File(_imagePath!))
                : Text('No image selected.'),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: _pickImage,
              child: Text('Pick Image from Gallery'),
            ),
          ],
        ),
      ),
    );
  }
}
回到顶部