Flutter图像处理插件scrunch的使用

Flutter图像处理插件scrunch的使用

功能

  • 使用 flutter_isolate 在单独的隔离区压缩图像文件。
  • 可以设置图像大小,当图像超过该大小时触发压缩。

开始使用

要使用此插件,运行以下命令:

flutter pub add scrunch

或者在你的 pubspec.yaml 文件中添加以下内容:

dependencies:
    ...
    scrunch: LATEST_VERSION

使用方法

导入 scrunch.dart

import 'package:scrunch/scrunch.dart';

快速使用示例:

final Scrunch scrunch = Scrunch();

List<File> imageFilesToCompress = [image1, image2, image3];

Future<List<File>?> runCompression(List<File?> imageFiles) async {
  try {
    // 第二个参数(5)是触发压缩的大小(单位为兆字节)
    final compressedFiles = await scrunch.compress(imageFiles, 5);
    return compressedFiles;
  } catch (e) {
    // 处理错误
  } finally {
    scrunch.dispose();
  }
} 

final compressedImageFiles = await runCompression(imageFilesToCompress);

示例代码

以下是完整的示例代码:

import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart' show rootBundle;
import 'package:path_provider/path_provider.dart';
import 'package:scrunch/scrunch.dart';

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

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

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const ScrunchExamplePage(title: 'Scrunch Example Page'),
    );
  }
}

class ScrunchExamplePage extends StatefulWidget {
  const ScrunchExamplePage({Key? key, required this.title}) : super(key: key);

  final String title;

  [@override](/user/override)
  State<ScrunchExamplePage> createState() => _ScrunchExamplePageState();
}

class _ScrunchExamplePageState extends State<ScrunchExamplePage> {
  final Scrunch _scrunch = Scrunch();

  /// 这个变量将保存示例文件
  File? _exampleFile;

  /// 这个变量将保存压缩后的文件
  File? _compressedFile;

  /// 这个变量用于指示何时正在压缩 [_exampleFile]
  /// 并根据 `_isCompressing` 的值改变按钮文本从 "Compress Image" 到 "Compressing..."
  bool _isCompressing = false;

  /// 此方法使用 "path_provider" 包从示例资产图像创建文件
  void getImageFileFromAssets() async {
    final byteData = await rootBundle.load('assets/example_image.jpg');

    final file = File('${(await getTemporaryDirectory()).path}/example_image.jpg');
    await file.writeAsBytes(byteData.buffer.asUint8List(byteData.offsetInBytes, byteData.lengthInBytes));
    setState(() => _exampleFile = file);
  }

  [@override](/user/override)
  void initState() {
    super.initState();

    getImageFileFromAssets();
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: _exampleFile == null
            ? const CircularProgressIndicator(
                strokeWidth: 2.0,
              )
            : SingleChildScrollView(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    Text(
                      "未压缩图像",
                      style: Theme.of(context).textTheme.headline4,
                    ),
                    Image.asset("assets/example_image.jpg"),
                    _compressedFile == null
                        ? TextButton(
                            onPressed: !_isCompressing
                                ? () async {
                                    setState(() => _isCompressing = true);
                                    final result = await _scrunch
                                        .compress([_exampleFile!], 8); // 最小允许图像大小为8兆字节

                                    if (result != null) {
                                      setState(
                                        () => _compressedFile = result[0],
                                      );
                                    }
                                  }
                                : null,
                            style: ButtonStyle(
                                backgroundColor: MaterialStateProperty.all<Color>(
                                    Colors.orangeAccent)),
                            child: Text(_isCompressing ? "压缩中..." : "压缩图像"),
                          )
                        : const SizedBox.shrink(),
                    _compressedFile != null
                        ? Column(
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              const SizedBox(
                                height: 24.0,
                              ),
                              Text(
                                "压缩后图像",
                                style: Theme.of(context).textTheme.headline4,
                              ),
                              Image.file(_compressedFile!),
                            ],
                          )
                        : const SizedBox.shrink(),
                  ],
                ),
              ),
      ),
    );
  }
}

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

1 回复

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


scrunch 是一个用于 Flutter 的图像处理插件,它允许你在 Flutter 应用中对图像进行压缩和调整大小等操作。scrunch 插件的主要目的是在保证图像质量的同时,减少图像文件的大小,从而优化应用的性能和加载时间。

安装 scrunch 插件

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

dependencies:
  flutter:
    sdk: flutter
  scrunch: ^0.1.0  # 请根据最新版本号进行替换

然后运行 flutter pub get 来安装插件。

使用 scrunch 插件

1. 导入 scrunch 插件

在你的 Dart 文件中导入 scrunch 插件:

import 'package:scrunch/scrunch.dart';

2. 压缩图像

scrunch 插件提供了 compress 方法来压缩图像。你可以通过指定图像的质量、宽度和高度来控制压缩结果。

Future<void> compressImage() async {
  // 加载图像文件
  File imageFile = File('path/to/your/image.jpg');

  // 压缩图像
  File compressedImage = await Scrunch.compress(
    imageFile,
    quality: 80, // 图像质量 (0 - 100)
    width: 800,  // 图像宽度
    height: 600, // 图像高度
  );

  // 保存或使用压缩后的图像
  print('Compressed image saved at: ${compressedImage.path}');
}

3. 调整图像大小

如果你只想调整图像的大小而不改变其质量,可以使用 resize 方法:

Future<void> resizeImage() async {
  // 加载图像文件
  File imageFile = File('path/to/your/image.jpg');

  // 调整图像大小
  File resizedImage = await Scrunch.resize(
    imageFile,
    width: 400,  // 图像宽度
    height: 300, // 图像高度
  );

  // 保存或使用调整大小后的图像
  print('Resized image saved at: ${resizedImage.path}');
}

4. 压缩并调整图像大小

你也可以同时压缩和调整图像的大小:

Future<void> compressAndResizeImage() async {
  // 加载图像文件
  File imageFile = File('path/to/your/image.jpg');

  // 压缩并调整图像大小
  File compressedResizedImage = await Scrunch.compress(
    imageFile,
    quality: 70, // 图像质量 (0 - 100)
    width: 640,  // 图像宽度
    height: 480, // 图像高度
  );

  // 保存或使用压缩并调整大小后的图像
  print('Compressed and resized image saved at: ${compressedResizedImage.path}');
}
回到顶部