Flutter原生相册访问插件photos_native的使用

Flutter原生相册访问插件photos_native的使用

1. 开始使用

photos_native 是一个高性能且易于使用的照片库插件,适用于Android和iOS。它可以加载相册、加载图像/缩略图、保存、分享等操作。

安装

  1. 使用Flutter:
$ flutter pub add photos_native
  1. pubspec.yaml 文件中添加依赖项:
dependencies:
  photos_native: ^0.0.1

设置项目

该库依赖于 flutter-permission-handler,因此在使用之前需要设置正确的权限。同时,在运行时请求权限的同时,你仍需要告诉操作系统你的应用可能使用哪些权限。这需要在Android和iOS特定文件中添加权限配置。

Android

如果你的目标版本是 SDK 30 或更高版本,则无需进行任何设置。

如果您的 compileSdkVersion/targetSdkVersion29,可以考虑将以下内容添加到您的 AndroidManifest.xml 文件中,以便获取资源:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.your_package">

    <application android:label="{appName}"
        android:icon="@mipmap/ic_launcher"
        android:requestLegacyExternalStorage="true">
    </application>
</manifest>
iOS
  1. Podfile 文件中添加以下内容:
post_install do |installer|
    installer.pods_project.targets.each do |target|
    ... # Here are some configurations automatically generated by flutter

    # Start of the permission_handler configuration
    target.build_configurations.each do |config|
        config.build_settings['GCC_PREPROCESSOR_DEFINITIONS'] ||= [
        '$(inherited)',

        ## dart: PermissionGroup.photos
        'PERMISSION_PHOTOS=1',
        ]

    end 
    # End of the permission_handler configuration
    end
end
  1. 配置 Info.plist 文件:

ios/Runner/Info.plist 文件中添加 NSPhotoLibraryUsageDescription 键:

<key>NSPhotoLibraryUsageDescription</key>
<string>App needs access to photo library</string>

使用

基本概念
  • PHItem 是设备上的照片项,每个照片项有一个唯一的照片ID或文件URI。
  • PHAlbum 是Android上的MediaStore桶或iOS上的PHAssetCollection的抽象版本。一个相册可以包含多个照片项。
  • PHGallery 包含设备上的所有相册。
  • 默认相册为All Photos,其中包含画廊中的所有照片(用户可以选择任何名称作为默认相册)。
  • PHImageDescriptor 是图像描述符,包含图像的像素数据、宽度和高度。
请求权限

请求照片库权限:

await PhotosNative.requestPermissions();
获取相册

获取相册:

final gallery = await PhotosNative.loadGallery(title: 'All Photos');

查看 PHGallery 类以获取更多详细信息。

获取缩略图图像描述符

返回缩略图图像描述符:

final descriptor = await PhotosNative.getThumbnail(200, 200, 'id');

// 或者从URI加载
final descriptor = await PhotosNative.getThumbnail(200, 200, 'image uri');

查看 PHImageDescriptor 类以获取更多详细信息。

获取图像描述符

返回照片的图像描述符:

final descriptor = await PhotosNative.getPixels('photo_id');

查看 PHImageDescriptor 类以获取更多详细信息。

删除照片

删除照片并返回已删除的照片数量:

await PhotosNative.delete(['photo_id', 'photo_id2']);
保存照片

将照片保存到路径/目录:

await PhotosNative.save(bytes, width, height, path: path);
分享照片

通过其他应用程序分享照片:

await PhotosNative.share(bytes, width, height);

实验功能

与Flutter后端纹理一起工作。阅读 Flutter Texture 以了解更多信息。你可以尝试这些功能来检查是否可以提高你的应用程序性能。

加载图像纹理

加载图像纹理:

int textureId = await PhotosNative.acquireTexture(id, width, height);

// 使用
Container(child: Texture(textureId: textureId));
释放图像纹理

释放图像纹理:

await PhotosNative.releaseTexture(id);

作者

此Flutter照片插件由 Annotium 开发。 联系邮箱:annotium@gmail.com


示例代码

example/lib/main.dart

import "package:photos_native_example/gallery.dart";
import "package:flutter/material.dart";

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

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  [@override](/user/override)
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text("All Photos"),
        ),
        body: const GalleryWidget(),
      ),
    );
  }
}

更多关于Flutter原生相册访问插件photos_native的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter原生相册访问插件photos_native的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,关于如何在Flutter项目中使用photos_native插件来访问原生相册,以下是一个简单的代码示例。这个示例展示了如何请求相册访问权限、列出相册以及获取相册中的图片。

首先,确保你已经在pubspec.yaml文件中添加了photos_native依赖:

dependencies:
  flutter:
    sdk: flutter
  photos_native: ^最新版本号  # 请替换为实际最新版本号

然后,运行flutter pub get来安装依赖。

接下来,在你的Flutter项目中,你可以按照以下步骤使用photos_native插件:

  1. 请求相册访问权限
import 'package:flutter/material.dart';
import 'package:photos_native/photos_native.dart';
import 'package:permission_handler/permission_handler.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('相册访问示例'),
        ),
        body: PermissionRequestScreen(),
      ),
    );
  }
}

class PermissionRequestScreen extends StatefulWidget {
  @override
  _PermissionRequestScreenState createState() => _PermissionRequestScreenState();
}

class _PermissionRequestScreenState extends State<PermissionRequestScreen> {
  bool _hasPermission = false;

  @override
  void initState() {
    super.initState();
    _requestPermission();
  }

  Future<void> _requestPermission() async {
    var status = await Permission.photos.status;
    if (!status.isGranted) {
      var result = await Permission.photos.request();
      if (result.isGranted) {
        setState(() {
          _hasPermission = true;
        });
      }
    } else {
      setState(() {
        _hasPermission = true;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    if (!_hasPermission) {
      return Center(
        child: CircularProgressIndicator(),
      );
    } else {
      return Center(
        child: ElevatedButton(
          onPressed: () {
            Navigator.push(
              context,
              MaterialPageRoute(builder: (context) => AlbumScreen()),
            );
          },
          child: Text('访问相册'),
        ),
      );
    }
  }
}
  1. 列出相册并获取图片
class AlbumScreen extends StatefulWidget {
  @override
  _AlbumScreenState createState() => _AlbumScreenState();
}

class _AlbumScreenState extends State<AlbumScreen> {
  List<Album> _albums = [];

  @override
  void initState() {
    super.initState();
    _fetchAlbums();
  }

  Future<void> _fetchAlbums() async {
    List<Album> albums = await PhotosNative.fetchAlbums();
    setState(() {
      _albums = albums;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('相册列表'),
      ),
      body: ListView.builder(
        itemCount: _albums.length,
        itemBuilder: (context, index) {
          Album album = _albums[index];
          return ListTile(
            title: Text(album.title),
            subtitle: Text('图片数量: ${album.assetCount}'),
            onTap: () {
              _fetchAssets(album.identifier);
            },
          );
        },
      ),
    );
  }

  Future<void> _fetchAssets(String albumId) async {
    List<Asset> assets = await PhotosNative.fetchAssets(albumId: albumId);
    // 这里你可以处理获取到的图片资源,比如显示它们
    // 例如,使用 Image.memory(assets[index].thumbnailData!) 来显示缩略图
    print('获取到的图片资源: $assets');
  }
}

注意:

  • AlbumAssetphotos_native 插件定义的类,用于表示相册和相册中的图片资源。
  • Permission.photos.request() 方法来自 permission_handler 插件,用于请求相册访问权限。因此,你还需要在 pubspec.yaml 文件中添加 permission_handler 依赖。

请确保在实际项目中处理错误情况,并根据需要调整UI设计。这个示例仅用于展示基本的使用流程。

回到顶部