Flutter背景移除插件remove_bg的使用

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

Flutter背景移除插件remove_bg的使用

在Flutter项目中,我们可以使用remove_bg插件来轻松地从图片中移除背景。这个插件依赖于Remove.bg的服务,因此需要一个有效的API密钥。

使用方法

首先,在你的Flutter应用中导入remove_bg包,并确保你已经获取了一个私钥(API Key)。然后,你可以通过选择图片并上传到Remove.bg服务来获得处理后的图片。

示例代码

以下是一个完整的示例demo,展示了如何使用remove_bg插件:

import 'dart:io';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:remove_bg/remove_bg.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});
  
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key});
  
  [@override](/user/override)
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  double linearProgress = 0.0;
  File? file;
  String? fileName;
  Uint8List? bytes;

  // 选择图片
  Future pickImage() async {
    try {
      FilePickerResult? result =
          await FilePicker.platform.pickFiles(type: FileType.image);
      if (result == null) return;
      setState(() {
        fileName = result.files.first.name;
        file = File(result.files.single.path!);
      });
    } on PlatformException catch (e) {
      debugPrint(e.toString());
    }
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Remove.bg"),
      ),
      body: SingleChildScrollView(
        child: Center(
          child: Padding(
            padding: const EdgeInsets.all(14.0),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                if (bytes != null) Image.memory(bytes!),
                if (file != null)
                  SizedBox(
                    height: 240,
                    child: Row(
                      children: [
                        Expanded(
                          child: Column(
                            children: [
                              Card(
                                child: Image.file(
                                  file!,
                                  height: 200,
                                  width: double.infinity,
                                ),
                              ),
                              Text("FileName: $fileName"),
                            ],
                          ),
                        ),
                      ],
                    ),
                  ),
                const SizedBox(height: 10),
                LinearProgressIndicator(value: linearProgress),
                const SizedBox(height: 10),
                const Text('Remove.bg Upload Progress'),
                const SizedBox(height: 10),
                ElevatedButton(
                  onPressed: () {
                    pickImage();
                  },
                  child: const Text("Select Image"),
                )
              ],
            ),
          ),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          if (file != null) {
            Remove().bg(
              file!,
              privateKey: "your_private_key_here", // 替换为你的私钥
              onUploadProgressCallback: (progressValue) {
                if (kDebugMode) {
                  print(progressValue);
                }
                setState(() {
                  linearProgress = progressValue;
                });
              },
            ).then((data) async {
              if (kDebugMode) {
                print(data);
              }
              bytes = data;
              setState(() {});
            });
          }
        },
        tooltip: 'Submit',
        child: const Icon(Icons.add),
      ),
    );
  }
}

更多关于Flutter背景移除插件remove_bg的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter背景移除插件remove_bg的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是如何在Flutter项目中使用remove_bg插件来进行背景移除的示例代码。remove_bg插件是一个基于Remove.bg API的Flutter插件,用于从图像中移除背景。

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

dependencies:
  flutter:
    sdk: flutter
  remove_bg: ^最新版本号  # 请替换为最新版本号

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

接下来,你需要一个Remove.bg API密钥。你可以通过Remove.bg的官方网站获取API密钥。

以下是一个完整的Flutter应用程序示例,展示了如何使用remove_bg插件:

import 'package:flutter/material.dart';
import 'package:remove_bg/remove_bg.dart';
import 'dart:io';
import 'dart:typed_data';
import 'package:image_picker/image_picker.dart';  // 用于选择图像

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: BackgroundRemoverPage(),
    );
  }
}

class BackgroundRemoverPage extends StatefulWidget {
  @override
  _BackgroundRemoverPageState createState() => _BackgroundRemoverPageState();
}

class _BackgroundRemoverPageState extends State<BackgroundRemoverPage> {
  final RemoveBg _removeBg = RemoveBg(apiKey: '你的API密钥');  // 替换为你的API密钥
  File? _originalImage;
  File? _resultImage;

  final ImagePicker _picker = ImagePicker();

  Future<void> _pickImage() async {
    final XFile? image = await _picker.pickImage(source: ImageSource.camera);
    if (image != null && image.path != null) {
      setState(() {
        _originalImage = File(image.path!);
      });
      _removeBackground(image.path!);
    }
  }

  Future<void> _removeBackground(String imagePath) async {
    try {
      final Uint8List imageBytes = await File(imagePath).readAsBytes();
      final RemoveBgResult result = await _removeBg.removeBackground(imageBytes: imageBytes);

      if (result.error == null) {
        setState(() {
          _resultImage = File.fromRawBytes(result.data!);
        });
      } else {
        print('Error: ${result.error}');
      }
    } catch (e) {
      print('Error: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Background Remover'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: [
            _originalImage != null ? Image.file(_originalImage!) : Text('No image selected'),
            SizedBox(height: 20),
            _resultImage != null ? Image.file(_resultImage!) : Text('Background removal in progress...'),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: _pickImage,
              child: Text('Pick Image'),
            ),
          ],
        ),
      ),
    );
  }
}

注意事项:

  1. API密钥:确保你已经替换了你的API密钥为你从Remove.bg获得的真实API密钥。
  2. 图像选择:这个示例使用了image_picker插件来选择图像。你需要在pubspec.yaml中添加image_picker依赖并运行flutter pub get来安装它。
  3. 错误处理:这个示例中包含了基本的错误处理,但你可能需要根据你的应用需求来扩展它。

这样,你就可以在Flutter应用中使用remove_bg插件来移除图像的背景了。

回到顶部