Flutter图像处理插件flutter_image_filters的使用

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

Flutter图像处理插件flutter_image_filters的使用

Flutter 是一个用于开发跨平台移动应用的框架,而 flutter_image_filters 是一个专为 iOS 和 Android 平台设计的图像处理包。它允许开发者通过 OpenGL 滤镜对图片进行处理,以实现各种视觉效果。

使用方法

如何生成并使用一组滤镜

有关如何生成和使用多个滤镜,请参考官方文档

添加自定义滤镜

如果想要添加自定义滤镜,请查阅这里

导出处理后的图像

final texture = await TextureSource.fromAsset('demo.jpeg');
final configuration = BrightnessShaderConfiguration();
configuration.brightness = 0.5;
final image = await configuration.export(texture, texture.size);

管道导出(Pipeline Export)

当遇到性能问题时,可以考虑使用管道方式来优化:

final texture = await TextureSource.fromAsset('demo.jpeg');
final brConfig = BrightnessShaderConfiguration();
brConfig.brightness = 0.5;

final stConfig = SaturationShaderConfiguration();
stConfig.saturation = 0.5;

final configuration = GroupShaderConfiguration();
configuration.add(brConfig);
configuration.add(stConfig);
final result = await configuration.export(texture, texture.size);

LookupTable 示例

final texture = await TextureSource.fromAsset('demo.jpeg');
final configuration = SquareLookupTableShaderConfiguration();
await configuration.setLutAsset('lookup_amatorka.png');
final image = await configuration.export(texture, texture.size);

LookupTable HALD 示例

final texture = await TextureSource.fromAsset('demo.jpeg');
final configuration = HALDLookupTableShaderConfiguration();
await configuration.setLutAsset('lookup_hald.png');
final image = await configuration.export(texture, texture.size);

ImageShaderPreview 示例

这是一个简单的预览页面示例,展示了如何将亮度调整应用于图像。

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

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

  @override
  State<PreviewPage> createState() => _PreviewPageState();
}

class _PreviewPageState extends State<PreviewPage> {
  late TextureSource texture;
  late BrightnessShaderConfiguration configuration;
  bool textureLoaded = false;

  @override
  void initState() {
    super.initState();
    configuration = BrightnessShaderConfiguration();
    configuration.brightness = 0.5;
    TextureSource.fromAsset('demo.jpeg')
        .then((value) => texture = value)
        .whenComplete(
          () => setState(() {
            textureLoaded = true;
          }),
        );
  }

  @override
  Widget build(BuildContext context) {
    return textureLoaded
        ? ImageShaderPreview(
            texture: texture,
            configuration: configuration,
          )
        : const Offstage();
  }
}

PipelineImageShaderPreview 示例

此示例展示了如何在一个页面中组合多个滤镜效果。

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

  @override
  State<PreviewPage> createState() => _PreviewPageState();
}

class _PreviewPageState extends State<PreviewPage> {
  late TextureSource texture;
  late GroupShaderConfiguration configuration;
  bool textureLoaded = false;

  @override
  void initState() {
    super.initState();
    configuration = GroupShaderConfiguration();
    configuration.add(BrightnessShaderConfiguration()..brightness = 0.5);
    configuration.add(SaturationShaderConfiguration()..saturation = 0.5);
    TextureSource.fromAsset('demo.jpeg')
        .then((value) => texture = value)
        .whenComplete(
          () => setState(() {
            textureLoaded = true;
          }),
        );
  }

  @override
  Widget build(BuildContext context) {
    return textureLoaded
        ? PipelineImageShaderPreview(
            texture: texture,
            configuration: configuration,
          )
        : const Offstage();
  }
}

分割预览示例

该示例演示了如何创建一个分割视图,显示原始图像和应用滤镜后的图像对比。

import 'package:before_after_image_slider_nullsafty/before_after_image_slider_nullsafty.dart';
import 'package:flutter_image_filters/flutter_image_filters.dart';

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

  @override
  State<PreviewPage> createState() => _PreviewPageState();
}

class _PreviewPageState extends State<PreviewPage> {
  late TextureSource texture;
  late BrightnessShaderConfiguration configuration;
  bool textureLoaded = false;

  @override
  void initState() {
    super.initState();
    configuration = BrightnessShaderConfiguration();
    configuration.brightness = 0.5;
    TextureSource.fromAsset('demo.jpeg')
        .then((value) => texture = value)
        .whenComplete(
          () => setState(() {
            textureLoaded = true;
          }),
        );
  }

  @override
  Widget build(BuildContext context) {
    return textureLoaded
        ? BeforeAfter(
            thumbRadius: 0.0,
            thumbColor: Colors.transparent,
            beforeImage: ImageShaderPreview(
              texture: texture,
              configuration: NoneShaderConfiguration(),
            ),
            afterImage: ImageShaderPreview(
              texture: texture,
              configuration: configuration,
            ),
          )
        : const Offstage();
  }
}

导出并保存处理后的图像

下面的例子说明了如何导出处理后的图像并将其保存到本地存储中。

import 'package:image/image.dart' as img;
import 'package:path_provider/path_provider.dart';

final texture = await TextureSource.fromAsset('demo.jpeg');
final configuration = BrightnessShaderConfiguration();
configuration.brightness = 0.5;
final image = await configuration.export(texture, texture.size);

final directory = await getTemporaryDirectory();
final output = File('${directory.path}/result.jpeg');
final bytes = await image.toByteData();
final persistedImage = img.Image.fromBytes(
  image.width,
  image.height,
  bytes!.buffer.asUint8List(),
);
img.JpegEncoder encoder = img.JpegEncoder();
final data = encoder.encodeImage(persistedImage);
await output.writeAsBytes(data);

其他信息

GPUImage 支持状态

以下是 flutter_image_filtersGPUImage for iOSGPUImage for Android 中滤镜的支持情况:

状态 名称
Brightness
Bulge Distortion
CGA Colorspace
Color Invert
Color Matrix
Contrast
Crosshatch
Exposure
False Color
Gamma
Glass Sphere
Grayscale
Halftone
Haze
Highlight Shadow
Hue
Lookup Table
Luminance
Luminance Threshold
Monochrome
Opacity
Pixelation
Posterize
RGB
Saturation
Solarize
Swirl
Vibrance
Vignette
White Balance
Zoom Blur

示例结果

示例项目

维护者

以上就是关于 flutter_image_filters 插件的基本介绍及用法示例,希望对你有所帮助!


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

1 回复

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


当然,关于flutter_image_filters插件的使用,这里是一个简单的示例,展示了如何在Flutter应用中应用一些基本的图像过滤效果。flutter_image_filters插件允许你轻松地在Flutter应用中应用各种图像处理效果。

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

dependencies:
  flutter:
    sdk: flutter
  flutter_image_filters: ^0.x.x  # 请替换为最新版本号

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

接下来是一个完整的示例代码,展示如何使用flutter_image_filters应用一些基本的图像过滤效果,比如灰度、模糊和锐化:

import 'package:flutter/material.dart';
import 'package:flutter_image_filters/flutter_image_filters.dart';
import 'dart:ui' as ui;

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

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

class ImageFilterScreen extends StatelessWidget {
  final String imageUrl = 'https://example.com/your-image.jpg'; // 替换为你的图片URL

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Image Filters Demo'),
      ),
      body: Column(
        children: <Widget>[
          Expanded(
            child: Stack(
              alignment: Alignment.center,
              children: <Widget>[
                Image.network(
                  imageUrl,
                  fit: BoxFit.cover,
                ),
                // 应用灰度滤镜
                Positioned(
                  child: ImageFilterWidget(
                    imageProvider: NetworkImage(imageUrl),
                    filter: ui.ImageFilter.matrix(
                      Float64List.fromList([
                        0.299, 0.587, 0.114, 0.0, 0.0,
                        0.299, 0.587, 0.114, 0.0, 0.0,
                        0.299, 0.587, 0.114, 0.0, 0.0,
                        0.0, 0.0, 0.0, 1.0, 0.0,
                      ]),
                    ),
                  ),
                ),
                // 应用模糊滤镜
                Positioned(
                  top: 50.0,
                  child: ImageFilterWidget(
                    imageProvider: NetworkImage(imageUrl),
                    filter: ui.ImageFilter.blur(sigmaX: 10.0, sigmaY: 10.0),
                  ),
                ),
                // 应用锐化滤镜
                Positioned(
                  bottom: 50.0,
                  child: ImageFilterWidget(
                    imageProvider: NetworkImage(imageUrl),
                    filter: ui.ImageFilter.matrix(
                      Float64List.fromList([
                        0.0, -1.0, 0.0, 0.0, 0.0,
                        -1.0, 5.0, -1.0, 0.0, 0.0,
                        0.0, -1.0, 0.0, 0.0, 0.0,
                        0.0, 0.0, 0.0, 1.0, 0.0,
                      ]),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}

class ImageFilterWidget extends StatelessWidget {
  final ImageProvider imageProvider;
  final ui.ImageFilter filter;

  ImageFilterWidget({required this.imageProvider, required this.filter});

  @override
  Widget build(BuildContext context) {
    return BackdropFilter(
      filter: ui.ImageFilter.layer(
        filter,
        offset: Offset.zero,
      ),
      child: Container(
        decoration: BoxDecoration(
          image: DecorationImage(
            image: imageProvider,
            fit: BoxFit.cover,
          ),
        ),
      ),
    );
  }
}

在这个示例中,我们展示了如何应用灰度、模糊和锐化滤镜。ImageFilterWidget是一个辅助小部件,用于将指定的图像滤镜应用到图像上。

注意:

  1. ImageFilterWidget使用了BackdropFilter来应用滤镜。然而,BackdropFilter可能不总是适用于所有情况,尤其是在需要处理复杂图像或复杂布局时。根据实际需求,你可能需要调整布局或使用其他方法。
  2. ui.ImageFilter.matrix允许你使用自定义的5x4矩阵来应用各种图像变换效果,包括灰度、锐化等。
  3. ui.ImageFilter.blur用于应用高斯模糊效果。

这个示例提供了一个基础,你可以根据需要进一步扩展和修改。

回到顶部