simple_native_image_compress 2.2.0 copy "simple_native_image_compress: ^2.2.0" to clipboard
simple_native_image_compress: ^2.2.0 copied to clipboard

A simple native image compression library for Flutter that supports Windows and Linux as well

example/lib/main.dart

import 'dart:io';

import 'package:file_picker/file_picker.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'dart:async';

import 'package:image_picker/image_picker.dart';
import 'package:simple_native_image_compress/simple_native_image_compress.dart';

Future<void> main() async {
  await NativeImageCompress.init();
  runApp(const MaterialApp(home: MyApp()));
}

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

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

class _MyAppState extends State<MyApp> {
  Duration _duration = const Duration();
  final _picker = ImagePicker();

  Uint8List? _bytes;

  Future<void> _compressImage() async {
    String filePath = '';
    if (Platform.isMacOS) {
      final res = await FilePicker.platform
          .pickFiles(type: FileType.image, allowMultiple: false);
      if (res == null) return;
      if (res.files.isEmpty) return;
      filePath = res.files[0].path!;
    } else {
      final file = await _picker.pickImage(source: ImageSource.gallery);
      if (file == null) return;
      filePath = file.path;
    }
    try {
      final startTime = DateTime.now();
      final bytes = await ImageCompress.contain(
        filePath: filePath,
        compressFormat: CompressFormat.jpeg,
        samplingFilter: FilterType.lanczos3,
        // withFileExt: true,
      );
      final endTime = DateTime.now();
      setState(() {
        _bytes = bytes;
        _duration = endTime.difference(startTime);
      });
    } catch (e) {
      if (!mounted) return;
      showDialog<void>(
        context: context,
        builder: (_) => AlertDialog(
          title: const Text(
            'Error Occured',
            style: TextStyle(color: Colors.red),
          ),
          content: Text(e.toString()),
          actions: [
            Center(
              child: TextButton(
                style: TextButton.styleFrom(
                  foregroundColor: Colors.white,
                  backgroundColor: Colors.blue, // Background Color
                ),
                onPressed: Navigator.of(context).pop,
                child: const Text('Ok'),
              ),
            ),
          ],
        ),
      );
    }
  }

  Future<void> _saveImage() async {
    if (Platform.isMacOS) return;
    String? outputFilePath = await FilePicker.platform.saveFile(
      dialogTitle: 'Please select an output file location',
      type: FileType.image,
    );

    if (outputFilePath == null) return;
    final tempFile = File(outputFilePath);
    await tempFile.create(recursive: true);
    RandomAccessFile raf = tempFile.openSync(mode: FileMode.write);
    try {
      raf.writeFromSync(_bytes!);
    } catch (e) {
      rethrow;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Plugin example app'),
      ),
      body: SafeArea(
        child: Column(
          children: [
            const SizedBox(height: 20),
            ElevatedButton(
              onPressed: _compressImage,
              child: const Text('Choose an image'),
            ),
            const SizedBox(height: 20),
            Text(
                '(${kDebugMode ? 'DEBUG' : 'RELEASE'}) mode time taken: ${_duration.inMilliseconds} ms'),
            const SizedBox(height: 10),
            Expanded(
              child: _bytes != null
                  ? InkWell(
                      onSecondaryTap: _saveImage, child: Image.memory(_bytes!))
                  : Container(),
            ),
          ],
        ),
      ),
    );
  }
}
19
likes
160
points
466
downloads

Publisher

verified publisherhyunwookim.net

Weekly Downloads

A simple native image compression library for Flutter that supports Windows and Linux as well

Homepage
Repository (GitHub)
View/report issues

Documentation

API reference

License

MIT (license)

Dependencies

flutter, flutter_rust_bridge, plugin_platform_interface

More

Packages that depend on simple_native_image_compress