분류, 패키지 및 저장소 검색

add_to_gallery 표지
패키지 상세v1.0.0

add_to_gallery

이미지와 비디오의 복사본을 안드로이드 갤러리 및 iOS 사진에 저장합니다

AndroidiOS
30일 다운로드
149
좋아요
28
Pub 점수
160

패키지 설치

flutter pub add add_to_gallery

패키지 개요

공개 정보를 바탕으로 생성한 선택 가이드입니다.

add_to_gallery 패키지는 Flutter 애플리케이션에서 안드로이드 및 iOS 기기의 네이티브 사진 갤러리에 이미지와 동영상을 저장할 수 있도록 합니다. 사용자가 기본 갤러리 앱에서 미디어 파일이 표시되도록 하기 위해 미디어 파일을 내보내는 간단한 인터페이스를 제공합니다. 이는 사진 편집기, 카메라 도구 또는 콘텐츠 제작자와 같은 미디어를 생성하거나 캡처하는 앱에 특히 유용합니다. 이 패키지는 플랫폼별 차이점을 원활하게 처리하여 두 운영 체제에서 일관된 동작을 제공합니다. 원본 파일은 수정하지 않고 시스템의 미디어 저장소에 복사본을 만듭니다.

사용 사례

  • 카메라에서 캡처한 사진 저장하기
  • 사진 편집기에서 편집된 이미지 내보내기
  • 사용자의 라이브러리에 생성된 비디오 추가
  • 사용자가 생성한 콘텐츠를 시스템 갤러리와 공유하기
  • 네이티브 스토리지로 미디어 백업 자동화

주요 기능

  • Android 및 iOS용 크로스 플랫폼 지원
  • 네이티브 갤러리에 복사본 저장
  • 최소한의 설정 필요
  • 플랫폼별 파일 경로 처리
  • 원본 미디어 파일 보존

적합한 대상

  • 사진 편집 앱
  • 카메라 통합 기능
  • 콘텐츠 생성 도구
  • 미디어 공유가 필요한 앱
  • 자동 갤러리 동기화를 원하는 사용자

고려 사항

  • 두 플랫폼 모두에서 적절한 권한이 필요합니다
  • 웹 또는 데스크톱을 지원하지 않습니다
  • 파일 크기는 성능에 영향을 줄 수 있습니다
  • 갤러리 메타데이터의 사용자 정의 제한
  • 일부 기기에서는 사용자 확인이 필요할 수 있습니다

원본 README

연결된 소스 저장소의 README 원문 스냅샷입니다. 최신 내용은 저장소에서 확인하세요.

Add to Gallery

Adds images and videos to the Android Gallery and iOS Photos

View example app

💡 There are a couple of important notes about Google photos and iOS filepaths. Jump to the end of this page for info!

Installation

Add add_to_gallery as a dependency in your pubspec.yaml file.

Permissions

You need the following permissions in your app:

  • iOS
    • NSPhotoLibraryUsageDescription
    • This allows the plugin to use the PHPhotoLibrary APIs to add assets to the user's photo library.
  • Android
    • READ_EXTERNAL_STORAGE
    • WRITE_EXTERNAL_STORAGE
    • If you target Android 10, you will also need the requestLegacyExternalStorage="true" in your AndroidManifest.
    • NB: Android < 13 needs storge permission
    • NB: Android >= 13 needs photos permission
      • ^ the example app shows how to request these permissions

This plugin does not manage permissions for you. By excluding permissions from our plugin we have created a simple, reliable plugin.

We recommend using permission_handler to handle permissions.

Usage

There's only one method. It copies the source file to the gallery and returns the new file.

File file = await AddToGallery.addToGallery(
  originalFile: File('/Some/Media/Path.jpg'),
  albumName: 'My Awesome App',
  deleteOriginalFile: false,
  keepFilename: true,
);
print("Savd to gallery with Path: ${file.path}");

Using permission_handler, this may look like:

Future<void> _addToGalleryExample() async {
  try {
    await _grantPermissions();
    File file = await AddToGallery.addToGallery(
      originalFile: File('/Some/Media/Path.jpg'),
      albumName: 'My Awesome App',
      deleteOriginalFile: true,
      keepFilename: true,
    );
    print("Savd to gallery with Path: ${file.path}");
  } catch(e) {
    print("Error: $e");
  }
}

Future<void> _grantPermissions() async {
  final int? androidVersion = Platform.isAndroid
      ? (await DeviceInfoPlugin().androidInfo).version.sdkInt
      : null;
  // We need storage on:
  // - iOS to pick files from other apps
  // - Android < 13 for legacy access
  if (Platform.isIOS || (androidVersion != null && androidVersion <= 32)) {
    if (!await Permission.storage.request().isGranted) {
      throw ('Storage Permission Required');
    }
  }
  // We need photos on:
  // - iOS to pick files from this app
  // - Android >= 13
  if (Platform.isIOS || (androidVersion != null && androidVersion >= 33)) {
    if (!await Permission.photos.request().isGranted) {
      throw ('Photos Permission Required');
    }
  }
}

Example app

The example app shows a few more edge-cases in action.

  • Uses permission_handler to request permissions
  • Uses image_picker to take photos with the camera
  • Copies assets to the gallery
  • Uses shared_preferences to save and read the file path locally
    • This shows that the assets are still accessible between reboots

Credits & Comparison

Add to Gallery is based on gallery_saver with some notable differences. Enough to warrant a new package rather than a pull-request. Generally speaking, I've simplified the API and unified the behaviour on iOS and Android. It also supports scoped storage on Android (which will be enforced with Android 11)

Big thanks to the Tecocraft LTD team for Android functionality on Android 10 and 11.

Feature gallery_saver
original package
add_to_gallery
this package
General Behaviour Android
  • 🔥 Source file is copied to the gallery
  • 🔥 The copy is not a tmp file
  • 👎 The file path is not returned
  • 👎 No way to find the new file path
iOS
  • 🔥 Source file is linked to the gallery
  • 👎 If the source file is in a tmp directory it may be garbage collected
  • 👎 The file path is not returned
  • 🔥 The original file path is correct
Android and iOS
  • 🔥 Source file is copied to the getApplicationDocumentsDirectory for persistence
  • 🔥 Your app has permission to access the file
  • 🔥 The new file path is returned
  • Automatically deletes sourceFile - defaults to false
Return Value Returns bool for the success of the operation Returns a File pointing to the new file in the gallery
Remote Files Automatically downloads files that start with http Does not download files that start with http
Album Name Optional with default values Is required
Image Manipulation Android
  • Rotates images according to EXIF data
  • Creates Thumbnails
iOS
  • Does not manipulate images
Does not manipulate images
Permissions Handled within the plugin. The first-call fails silently due to permissions race-condition Not handled within the plugin

💡 An Important Note about Google photos

Google Photos has a built-in feature to remove exact duplicates. It can be confusing to see your media disappearing like this. I considered addressing this behaviour in the plugin, but decided against it. I expect plugin users to be creating unique images with the camera or other methods.

💡 An Important Note about iOS Filepaths

Simply, it will change when new versions of your app are released. For example:

  • The user installs 1.0.0 of your app, the path is: .../<A-UNIQUE-DIRECTORY>/Documents/your-file.jpg
  • The user upgrades to 2.0.0, the path is now: .../<A-DIFFERENT-UNIQUE-DIRECTORY>/Documents/your-file.jpg

This becomes an issue when you try to access the file later, as the path has changed.

To handle this, you can use the path_provider package to build the path dynamically. Here's an example:

// 1. We used `add_to_gallery` to save a file, and stored the `file.path` locally (in a db, shared preferences etc.)
// 2. The user then updated their app
// 3. They re-opened the app, and we want to access the file again:
import 'package:path_provider/path_provider.dart';
final fileName = basename(filePath);
storageDirectory = await getApplicationDocumentsDirectory();
final sourcePath = '${storageDirectory.path}/$fileName'; // This is the new path

카테고리

의존성

의존성 목록 3 개

소스 저장소

이 패키지를 사용하는 프로젝트

아직 데이터가 없습니다.