Flutter图片编辑插件flutter_photo_editor的使用

发布于 1周前 作者 bupafengyu 来自 Flutter

Flutter图片编辑插件flutter_photo_editor的使用

flutter_photo_editor 是一个简单易用的Flutter插件,支持在图片上进行绘画、添加文本和表情符号等操作,类似于故事编辑功能。

android ios

开始使用

要开始使用 flutter_photo_editor 插件,你需要按照以下步骤操作:

  1. 在你的 pubspec.yaml 文件中添加依赖:

    dependencies:
      flutter:
        sdk: flutter
      flutter_photo_editor: ^最新版本号
      image_picker: ^最新版本号
    
  2. 运行 flutter pub get 来安装依赖。

  3. 在你的 Dart 代码中导入插件:

    import 'package:flutter_photo_editor/flutter_photo_editor.dart';
    import 'package:image_picker/image_picker.dart';
    
  4. 使用插件提供的方法来编辑图片。以下是完整的示例代码:

完整示例代码

import 'dart:io';

import 'package:flutter/material.dart';
import 'dart:async';
import 'package:flutter/services.dart';
import 'package:flutter_photo_editor/flutter_photo_editor.dart';
import 'package:image_picker/image_picker.dart';

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

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

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _platformVersion = 'Unknown';
  final _flutterPhotoEditorPlugin = FlutterPhotoEditor();

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

  // 初始化平台状态
  Future<void> initPlatformState() async {
    String platformVersion;
    try {
      platformVersion =
          await _flutterPhotoEditorPlugin.getPlatformVersion() ?? 'Unknown platform version';
    } on PlatformException {
      platformVersion = 'Failed to get platform version.';
    }

    if (!mounted) return;

    setState(() {
      _platformVersion = platformVersion;
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: Column(
          children: [
            Center(
              child: TextButton(
                onPressed: () {
                  test();
                },
                child: const Text("Add photo"),
              ),
            ),

            if (imagePath != null)
              Image.file(File(imagePath!), width: 300, height: 500,)
          ],
        ),
      ),
    );
  }

  String? imagePath;

  void test() async {
    print("start");

    final image = await ImagePicker().pickImage(source: ImageSource.gallery);

    String? path = image?.path;
    if (path != null) {
      editImage(path);
    }
  }

  void editImage(String path) async {
    print("path: $path");

    var result = await FlutterPhotoEditor().editImage(path);

    setState(() {
      imagePath = path;
    });

    print("end : $result");
  }
}

解释

  • Image Picker: 我们使用 image_picker 插件从设备相册中选择一张图片。
  • Edit Image: 通过调用 FlutterPhotoEditor().editImage(path) 方法对选中的图片进行编辑。
  • 显示编辑后的图片: 编辑完成后,将图片路径保存到 imagePath 变量,并在界面上显示。

通过以上步骤,你可以轻松地在 Flutter 应用中集成图片编辑功能。希望这个示例对你有所帮助!


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

1 回复

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


当然,关于flutter_photo_editor这个Flutter插件的使用,下面是一个基本的代码示例,展示了如何在Flutter应用中使用它来编辑图片。这个示例包括加载图片、应用滤镜以及裁剪图片等功能。

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

dependencies:
  flutter:
    sdk: flutter
  flutter_photo_editor: ^latest_version  # 请替换为最新的版本号

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

接下来是一个简单的示例代码,展示了如何使用flutter_photo_editor

import 'package:flutter/material.dart';
import 'package:flutter_photo_editor/flutter_photo_editor.dart';
import 'dart:io';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Flutter Photo Editor Example'),
        ),
        body: MyHomePage(),
      ),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  File? _imageFile;
  PhotoEditorController? _editorController;

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        _imageFile == null
            ? Text('No image selected.')
            : Expanded(
                child: PhotoEditor(
                  imageProvider: FileImage(_imageFile!),
                  initialEditorValue: EditorValue(
                    cropRectangle: Rect.fromLTWH(0, 0, _imageFile!.width!.toDouble(), _imageFile!.height!.toDouble()),
                  ),
                  controller: _editorController!,
                ),
              ),
        SizedBox(height: 20),
        ElevatedButton(
          onPressed: _pickImage,
          child: Text('Pick Image'),
        ),
        SizedBox(height: 20),
        ElevatedButton(
          onPressed: _applyFilter,
          child: Text('Apply Sepia Filter'),
        ),
        SizedBox(height: 20),
        ElevatedButton(
          onPressed: _saveImage,
          child: Text('Save Image'),
        ),
      ],
    );
  }

  Future<void> _pickImage() async {
    final pickedFile = await ImagePicker().pickImage(source: ImageSource.gallery);

    if (pickedFile != null) {
      setState(() {
        _imageFile = File(pickedFile.path);
        _editorController = PhotoEditorController(
          imageProvider: FileImage(_imageFile!),
        );
      });
    }
  }

  Future<void> _applyFilter() async {
    if (_editorController != null && _imageFile != null) {
      final result = await _editorController!.applyFilter(
        FilterType.sepia,
        value: 1.0,
      );

      if (result != null) {
        setState(() {}); // Trigger UI update if needed
      }
    }
  }

  Future<void> _saveImage() async {
    if (_editorController != null && _imageFile != null) {
      final result = await _editorController!.getUiImage();

      if (result != null) {
        final byteData = await result.toByteData(format: ui.ImageByteFormat.png);
        final Uint8List pngBytes = byteData!.buffer.asUint8List();

        final outputFile = File('${(_imageFile!.path)!.split('/').first}/edited_image.png');
        await outputFile.writeAsBytes(pngBytes);

        print('Image saved to ${outputFile.path}');
      }
    }
  }
}

说明:

  1. 依赖安装:确保在pubspec.yaml中添加并安装了flutter_photo_editor
  2. 界面布局:使用Column布局了一些按钮和一个PhotoEditor组件。
  3. 图片选择:使用ImagePicker从图库中选择图片,并将其设置为PhotoEditorimageProvider
  4. 滤镜应用:通过_editorController!.applyFilter方法应用一个Sepia滤镜。
  5. 保存图片:通过_editorController!.getUiImage方法获取编辑后的图片,并将其保存为PNG格式。

请注意,这只是一个基础示例,flutter_photo_editor插件提供了许多其他功能,如亮度、对比度调整,贴纸添加,文本添加等,你可以根据需求进一步扩展。详细的功能和用法可以参考flutter_photo_editor的官方文档

回到顶部