插件简介

flutter_native_image 是一个强大的 Flutter 原生图像处理插件,为开发者提供了高效的图像压缩、调整大小、裁剪和属性获取功能。该插件针对鸿蒙平台进行了专门适配,能够充分利用鸿蒙系统的原生图像处理能力,提供更高效的图像处理体验。

核心功能

  • 图像压缩:通过调整质量和尺寸来减小图像文件大小
  • 图像调整大小:按比例或指定尺寸调整图像大小
  • 图像裁剪:根据坐标和尺寸裁剪图像
  • 图像属性获取:获取图像的宽度、高度和方向等信息

适用场景

  • 应用内图片上传前的压缩处理
  • 用户头像裁剪和调整
  • 图片分享时的尺寸优化
  • 图像处理应用的核心功能支持

安装和配置

1. 添加依赖

由于这是针对鸿蒙平台的自定义修改版本,需要使用 Git 方式引入依赖。在项目的 pubspec.yaml 文件中添加以下配置:

dependencies:
  flutter_native_image:
    git:
      url: "https://atomgit.com/openharmony-sig/flutter_native_image.git"

2. 权限配置

在鸿蒙平台上使用该插件需要添加文件访问权限。在 ohos/entry/src/main/module.json5 文件中添加以下权限声明:

"requestPermissions": [
  {
    "name": "ohos.permission.READ_USER_STORAGE"
  },
  {
    "name": "ohos.permission.WRITE_USER_STORAGE"
  }
]

API使用详解

1. 导入包

在需要使用图像处理功能的 Dart 文件中导入包:

import 'package:flutter_native_image/flutter_native_image.dart';

2. 图像压缩

基本压缩

通过指定压缩质量和调整百分比来压缩图像:

File compressedFile = await FlutterNativeImage.compressImage(
  file.path,
  quality: 80,  // 压缩质量 (0-100)
  percentage: 70,  // 调整大小的百分比 (0-100)
);
指定目标尺寸压缩

通过指定目标宽度和高度来压缩图像:

File compressedFile = await FlutterNativeImage.compressImage(
  file.path,
  quality: 80,
  targetWidth: 600,
  targetHeight: 300,
);
保持宽高比压缩

先获取图像属性,然后计算保持宽高比的目标尺寸:

ImageProperties properties = await FlutterNativeImage.getImageProperties(file.path);
File compressedFile = await FlutterNativeImage.compressImage(
  file.path,
  quality: 80,
  targetWidth: 600,
  targetHeight: (properties.height! * 600 / properties.width!).round(),
);

3. 获取图像属性

获取图像的宽度、高度和方向等信息:

ImageProperties properties = await FlutterNativeImage.getImageProperties(file.path);
print('宽度: ${properties.width}');
print('高度: ${properties.height}');
print('方向: ${properties.orientation}');

4. 图像裁剪

根据指定的起始坐标和尺寸裁剪图像:

// 从坐标 (100, 100) 开始裁剪一个宽 200、高 150 的区域
File croppedFile = await FlutterNativeImage.cropImage(
  file.path,
  100,  // 起始 X 坐标
  100,  // 起始 Y 坐标
  200,  // 裁剪宽度
  150,  // 裁剪高度
);

完整示例

以下是一个在鸿蒙平台上使用 flutter_native_image 插件的完整示例:

import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:path_provider/path_provider.dart';
import 'package:flutter_native_image/flutter_native_image.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  File? originalFile;
  File? processedFile;
  String imageInfo = '';

  Future<void> loadImage() async {
    // 获取临时目录
    final tempDir = (await getTemporaryDirectory()).path;
    final filePath = '$tempDir/test_image.jpg';

    // 从 assets 加载示例图片
    final ByteData bytes = await rootBundle.load('assets/test.jpg');
    originalFile = File(filePath);
    await originalFile!.writeAsBytes(bytes.buffer.asUint8List());

    setState(() {
      processedFile = originalFile;
    });

    // 获取并显示图片属性
    getImageProperties();
  }

  Future<void> getImageProperties() async {
    if (originalFile != null) {
      ImageProperties properties =
          await FlutterNativeImage.getImageProperties(originalFile!.path);
      setState(() {
        imageInfo = '原始尺寸: ${properties.width}×${properties.height}';
      });
    }
  }

  Future<void> compressImage() async {
    if (originalFile != null) {
      // 压缩图片到指定尺寸并保持宽高比
      ImageProperties properties =
          await FlutterNativeImage.getImageProperties(originalFile!.path);

      File compressed = await FlutterNativeImage.compressImage(
        originalFile!.path,
        quality: 80,
        targetWidth: 800,
        targetHeight: (properties.height! * 800 / properties.width!).round(),
      );

      setState(() {
        processedFile = compressed;
      });
    }
  }

  Future<void> cropImage() async {
    if (originalFile != null) {
      // 裁剪图片中心区域
      ImageProperties properties =
          await FlutterNativeImage.getImageProperties(originalFile!.path);

      int cropWidth = properties.width! ~/ 2;
      int cropHeight = properties.height! ~/ 2;
      int originX = (properties.width! - cropWidth) ~/ 2;
      int originY = (properties.height! - cropHeight) ~/ 2;

      File cropped = await FlutterNativeImage.cropImage(
        originalFile!.path,
        originX,
        originY,
        cropWidth,
        cropHeight,
      );

      setState(() {
        processedFile = cropped;
      });
    }
  }

  
  void initState() {
    super.initState();
    loadImage();
  }

  
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Flutter Native Image 鸿蒙示例'),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              if (processedFile != null)
                Image.file(processedFile!, width: 300, height: 300, fit: BoxFit.contain),
              SizedBox(height: 20),
              Text(imageInfo),
              SizedBox(height: 20),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: [
                  ElevatedButton(
                    onPressed: compressImage,
                    child: Text('压缩图片'),
                  ),
                  ElevatedButton(
                    onPressed: cropImage,
                    child: Text('裁剪图片'),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }
}

总结

flutter_native_image 插件为鸿蒙平台上的 Flutter 应用提供了强大的原生图像处能力,通过简单易用的 API,开发者可以轻松实现图像压缩、调整大小、裁剪和属性获取等功能。该插件充分利用了鸿蒙系统的原生能力,提供了高效的图像处理体验,适用于各种需要图像处理功能的应用场景。

欢迎加入开源鸿蒙跨平台社区:https://openharmonycrossplatform.csdn.net

Logo

开源鸿蒙跨平台开发社区汇聚开发者与厂商,共建“一次开发,多端部署”的开源生态,致力于降低跨端开发门槛,推动万物智联创新。

更多推荐