Giter Site home page Giter Site logo

bitmap's Introduction

transform image dog

Flutter Bitmap

Pub

A minimalist Flutter package to perform fast bitmaps operations. The focus here is to provide a cool bitmap manipulation interface.

The package standard format is RGBA32.

Bitmap uses the Dart FFI to perform operations such as contrast, brightness, saturation, and exposure.

For now, things like format encoding, EXIF and multi-frame images are not the concern of this package. If that is your need, check image. Some of the algorithms here are heavily inspired by this awesome lib.

Why this exists?

I started to use dart image to create LetsPicture (cool app, check it out) but since the beginning, I've noticed that the performance was really bad. Dart image has its own Image format, so between decoding, putting some transformations and then displaying the result on the app you had to convert the image two times (at least).

So this package is just this: We deal bitmaps (duh) and we focus only on Flutter use cases.

bitmap takes some advantages from Flutter:

  • Every image is decoded to RGBA32 by the framework trough ImageStreamListener, so we can rely on Flutter to do the decoding job;
  • Dart FFI: we are porting some of our functions to C (or C++) making it blazing fast.
  • With this package, you can easily take advantage of stuff like compute (Isolates) on only the manipulations you want to free the UI thread of heavy computation.

Alternatives

Dart image

As mentioned previously, check on pub.

Flutter Built-in ColorFilter class

Flutter has a powerful ColorFilter class (that came from skia) which can be used to put some color corrections when painting stuff on canvas. You can use a matrix to correct color (Some matrix examples here). Not every color transformation can be done through the matrix, though.

Basic usage

1. Image to Bitmap

Everything is around the Bitmap class. You can get an instance of that from any ImageProvider.

import 'package:bitmap/bitmap.dart';

Bitmap bitmap = await Bitmap.fromProvider(NetworkImage("http://pudim.com.br/pudim.jpg")); // Notice this is an async operation
You can create from a headed Uint8List:
import 'package:bitmap/bitmap.dart';

Bitmap bitmap = Bitmap.fromHeadful(imageWidth, imageHeight, theListOfInts); // Not async
Or a headless:
Bitmap bitmap = Bitmap.fromHeadless(imageWidth, imageHeight, theListOfInts); // Not async

This is useful when you are dealing with the Uint8List that ByteData generates.

You can even create a blank one
Bitmap bitmap = Bitmap.blank(imageWidth, imageHeight);

This creates a black, full transparent bitmap.

2. Applying some operations

Let's put some contrast

import 'package:bitmap/bitmap.dart';

Bitmap contrastedBitmap = bitmap.apply(BitmapContrast(0.2));;

It is possible to add several operations at once

import 'package:bitmap/bitmap.dart';
Bitmap brightBitmap = bitmap.applyBatch([
  BitmapBrightness(0.2),
  BitmapAdjustColor(
    saturation: 1.0
  ),
]);

3. Displaying/painting/saving the output

You can create two outputs from a Bitmap instance:

  • A Uint8List with no header, only the content of the file (.content property).
  • A Uint8List with a bitmap header, which Flutter can parse (.buildHeaded() method).
Displaying

To easiest way to display an image is to getting the bitmap with header and then passing it to the widget Image.memory:

// ..

Uint8List headedBitmap = bitmap.buildHeaded();

// ..
child: Image.memory(headedBitmap)
// ..
Painting

The Bitmap class has also a helper function buildImage that uses Flutter's decodeImageFromList to build a dart:ui Image. With an Image, you can paint it in a canvas (in a CustomPainter, for example).

import 'dart:ui' as ui;
// ..
ui.Image outputImage = await bitmap.buildImage();
canvas.drawImage(outputImage, Offset.zero, ui.Paint());
Saving

You can also save the image as a .bmp file (get the file content with the .buildHeaded() method). You can check also the image lib where you can save the image in several formats.

How to save files with Flutter?

Performance improvements and Dart FFI

Dart FFI

The capability of calling a c (or c++) function from dart can help us a lot in getter better performance times.

Isolates

Most of the manipulations on the bitmap take a long time to be completed. That's is because they have to iterate on every item of the bitmap. A picture with a 400px width and height sizes will generate a list of 640000 integers. This is a heavy computation. Those can be expensive. Sou you may use Isolates there to free the UI thread from all of this work.

Check the example app, where the transformations are applied through the compute function.

Important: it is noticed that the performance increases a lot when using release mode on your Flutter App

Apps using it (only one for now)

Supported operations

  • Flip vertical
  • Flip horizontal
  • Rotation
  • Resize (nearest interpolation)
  • Contrast
  • Brightness
  • Saturation
  • Exposure
  • Crop

Todo

There is a lot of work to be done:

  • Resize with other interpolations
  • Set channel
  • White balance
  • Color blend
  • Noise
  • Tones
  • ??? The sky is the limit

bitmap's People

Contributors

aingo03304 avatar bitsydarel avatar lorisleitner avatar mit-mit avatar mixedteam236 avatar renancaraujo avatar ryankauk avatar sachinbhankhar avatar spydon avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

bitmap's Issues

Suggestion: add compositeImage() function.

Suggestion: add compositeImage() function.
I'm currently using the Image package and the compositeImage() function.
Unfortunately this function is very slow,

I am submitting a suggestion to your package: please add a function similar to compositeImage() (from Image packet)

Direction for saving image

Hey love this library, I'm using it and need to send the file to a server and need to convert from bitmap to jpeg, I checked out the image library as suggested but the decodeImage method returns null because it doesn't have a decoder for Bitmap. Could you give some direction on how to approach this?

New release?

Hello,

first thx for your plugin. A little problem, i cant use it because of flutter 3 and gradle issues. I see u already merged the pull request to fix this but there is no version released for flutter 3 compatibility. Are there any plans to make a new release?

Bitmap build error

I just added bitmap: ^0.0.6 to pubspec.yaml and build it.
The log said:

Execution failed for task ':bitmap:generateJsonModelDebug'.
> exception while building Json $Cannot run program "/Users/choeseungmin/Library/Android/sdk/cmake/3.10.2.4988404/bin/cmake": error=2, No such file or directory

How can I fix this?

Android Gradle Plugin version

Getting the following error on the latest gradle version

The Android Gradle plugin supports only Kotlin Gradle plugin version 1.5.20 and higher.
The following dependencies do not satisfy the required version:
project ':bitmap' -> org.jetbrains.kotlin:kotlin-gradle-plugin:1.3.50

Gradle build failed. NDK error

I'm getting the error below when building my project:

FAILURE: Build failed with an exception.

* What went wrong:
A problem occurred configuring project ':bitmap'.
> No version of NDK matched the requested version 21.0.6113669. Versions available locally: 22.0.6917172

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 2s
Exception: Gradle task assembleDebug failed with exit code 1

Upgrade Kotlin Gradle plugin 1.3.50 to the latest version.

After upgrading the Android Gradle Plugin from Version 7.1.2 to 7.4.1, I got the following Error:

The Android Gradle plugin supports only Kotlin Gradle plugin version 1.5.20 and higher.
The following dependencies do not satisfy the required version:
project ':bitmap' -> org.jetbrains.kotlin:kotlin-gradle-plugin:1.3.50

Please consider upgrading to the latest version.

it occors the error when i import 'package:bitmap/bitmap.dart';

* Error running Gradle:
ProcessException: Process "/Users/music/Documents/.../android/gradlew" exited abnormally:

> Configure project :bitmap
WARNING: The option setting 'android.enableR8=true' is experimental and unsupported.
The current default is 'false'
Consider disabling R8 by removing 'android.enableR8=true' from your gradle.properties before publishing your app.


FAILURE: Build failed with an exception.

* What went wrong:
A problem occurred configuring project ':bitmap'.
> NDK not configured. 
  Download it with SDK manager.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 1s
  Command: /Users/music/Documents/.../android/gradlew app:properties

Finished with error: Please review your Gradle project setup in the android/ folder.

Update image without redraw

Hi,
I'm trying to find a way to adjust brightness and contrast of an image, using sliders on Flutter. I tested with the library image and with that. Both works well, but needs to redraw or rebuild the screen on each change. Would be possible make changes in the image without rebuild the image on screen? In a way that's transparent for the user, i mean.

Compile error with v0.1.2

Since today I'm getting this error when trying to compile my project:

FAILURE: Build failed with an exception.                                
                                                                        
* What went wrong:                                                      
Execution failed for task ':bitmap:externalNativeBuildDebug'.           
> Build command failed.                                                 
  Error while executing process /home/dlednik/Android/Sdk/cmake/3.6.4111459/bin/cmake with arguments {--build /home/dlednik/snap/flutter/common/flutter/.pub-cache/hosted/pub.dartlang.org/bitmap-0.1.2/android/.cxx/cmake/debug/armeabi-v7a --target bitmap}
  [1/2] Building CXX object CMakeFiles/bitmap.dir/home/dlednik/snap/flutter/common/flutter/.pub-cache/hosted/pub.dartlang.org/bitmap-0.1.2/ios/Classes/bitmap.cpp.o
  FAILED: /home/dlednik/Android/Sdk/ndk/22.0.7026061/toolchains/llvm/prebuilt/linux-x86_64/bin/clang++  --target=armv7-none-linux-androideabi16 --gcc-toolchain=/home/dlednik/Android/Sdk/ndk/22.0.7026061/toolchains/llvm/prebuilt/linux-x86_64 --sysroot=/home/dlednik/Android/Sdk/ndk/22.0.7026061/toolchains/llvm/prebuilt/linux-x86_64/sysroot  -Dbitmap_EXPORTS  -g -DANDROID -fdata-sections -ffunction-sections -funwind-tables -fstack-protector-strong -no-canonical-prefixes -D_FORTIFY_SOURCE=2 -march=armv7-a -mthumb -Wformat -Werror=format-security   -O0 -fno-limit-debug-info  -fPIC -MD -MT CMakeFiles/bitmap.dir/home/dlednik/snap/flutter/common/flutter/.pub-cache/hosted/pub.dartlang.org/bitmap-0.1.2/ios/Classes/bitmap.cpp.o -MF CMakeFiles/bitmap.dir/home/dlednik/snap/flutter/common/flutter/.pub-cache/hosted/pub.dartlang.org/bitmap-0.1.2/ios/Classes/bitmap.cpp.o.d -o CMakeFiles/bitmap.dir/home/dlednik/snap/flutter/common/flutter/.pub-cache/hosted/pub.dartlang.org/bitmap-0.1.2/ios/Classes/bitmap.cpp.o -c /home/dlednik/snap/flutter/common/flutter/.pub-cache/hosted/pub.dartlang.org/bitmap-0.1.2/ios/Classes/bitmap.cpp
  In file included from /home/dlednik/snap/flutter/common/flutter/.pub-cache/hosted/pub.dartlang.org/bitmap-0.1.2/ios/Classes/bitmap.cpp:1:
  In file included from /snap/flutter/current/usr/include/c++/8/stdlib.h:36:
  In file included from /snap/flutter/current/usr/include/c++/8/cstdlib:41:
  In file included from /snap/flutter/current/usr/include/x86_64-linux-gnu/c++/8/bits/c++config.h:508:
  In file included from /snap/flutter/current/usr/include/x86_64-linux-gnu/c++/8/bits/os_defines.h:39:
  In file included from /snap/flutter/current/usr/include/features.h:448:
  /snap/flutter/current/usr/include/x86_64-linux-gnu/gnu/stubs.h:7:11: fatal error: 'gnu/stubs-32.h' file not found
  # include <gnu/stubs-32.h>                                            
            ^~~~~~~~~~~~~~~~                                            
  1 error generated.                                                    
  ninja: build stopped: subcommand failed.   

Anyone else seeing this?
Looks like 32bit headers are missing. I installed flutter via snap on my Ubuntu 20.04

How should the parameters of the black and white filter be set?

Thanks to the author for writing such a great library!

Drag the progress bar to make the picture whiter, I tried it, the effect is not good

  void updateFilterValue(value) async {
    if (_filterValue == value) {
      return;
    }
    _filterValue = value;

    Bitmap bitmap = await Bitmap.fromProvider(ExtendedExactAssetImageProvider('assets/images/photoShoot/ic_icon_editor_topic_example.jpg'));
    Bitmap brightBitmap = bmp.brightness(bitmap, value); // 位图亮度, 可以在-1.0和1.0之间。 0.0不执行任何操作;
    Bitmap nowThisBitmapLooksWeird = bmp.contrast(brightBitmap, 1.5); // 对比度 0~2.0的范围  default 1.0
    Bitmap finalBitmap = bmp.adjustColor(nowThisBitmapLooksWeird, saturation: 0); // 饱和度 0 1
    result = finalBitmap.buildHeaded();

    notifyListeners();
  }

flutter gallery

I want to make a gridview that depicts all the recent pictures like in instagram's or messenger's chat, but I can't make it smooth. Do you have any idea? I should isolate also the bitmap generation from imageprovider besides the resizing, or any other solution? I think I cannot load all the Uint8Lists in the memory as there are about a few thousands picture on an average phone so that would take too much memory.

add non-asynchronous transformations in resize.dart

I want to make my image processing software run the main processing method in a compute(). Problem is, the resize() method in your library is async-only, and that trickles down into the function i want to be run in a 'compute()'. Still learning about isolates, so I'm not sure if it's absolutely necessary to have the function you're running be synchronous, but it makes things easier to grasp. Regardless, having these options be available is easy to do and gives more freedom to the developer.

GrayScale and Threshold function

Hey guys, and author of this package.

I was wondering that if there is a library for turning an image to grayscale and doing a threshold operation in flutter?
I asked this question on Reddit and they suggested to use this package(bitmap) but I can't see any threshold function in the docs. or maybe I couldn't find it.
Can you guys help me out?
Thank you all in advance.

Execution failed for task ':bitmap:stripDebugDebugSymbols'.

Hi, I'm having real difficulty getting this package working on linux. I'm getting the following error:

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':bitmap:stripDebugDebugSymbols'.
> No toolchains found in the NDK toolchains folder for ABI with prefix: arm-linux-androideabi

I've got NDK v23 and v20 installed yet still I get this when I try to build my project.

Any ideas?
Thanks

Cannot Crop Bitmap

I am trying to crop a bitmap, but I get following exception. I have tried using code from example

Future<Uint8List> batchOperationsImageIsolate(List imageData) async {
  final Uint8List byteData = imageData[0];
  final int width = imageData[1];
  final int height = imageData[2];

  final Bitmap bigBitmap = Bitmap.fromHeadless(width, height, byteData);

  final Bitmap returnBitmap = bigBitmap.applyBatch([
    BitmapAdjustColor(
      saturation: 1.9,
    ),
    BitmapCrop.fromLTWH(
      left: 10,
      top: 10,
      width: width - 20,
      height: height - 20,
    ),
  ]);

  return returnBitmap.content;
}
E/flutter ( 3386): [ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception: Bad state: Too few elements
E/flutter ( 3386): #0      _TypedIntListMixin.setRange (dart:typed_data-patch/typed_data_patch.dart:409:7)
E/flutter ( 3386): #1      RGBA32BitmapHeader.applyContent
package:bitmap/src/bitmap.dart:136
E/flutter ( 3386): #2      Bitmap.buildHeaded
package:bitmap/src/bitmap.dart:79
E/flutter ( 3386): #3      ImageValueNotifier.batchOperations
package:image_editor/widgets/image_notifier.dart:179
E/flutter ( 3386): <asynchronous suspension>

Incompatible with flutter 1.12.13+hotfix.5

After upgrading to new flutter there's issues with the ffi file, see outcome below.

../../../.pub-cache/hosted/pub.dartlang.org/bitmap-0.0.5/lib/ffi.dart:22:32: Error: Method not found: 'Pointer.allocate'.
        ffi.Pointer<ffi.Uint8>.allocate(count: sourceBmp.length);
                               ^^^^^^^^
../../../.pub-cache/hosted/pub.dartlang.org/bitmap-0.0.5/lib/ffi.dart:24:41: Error: The method 'asExternalTypedData' isn't defined for the class 'Pointer<Uint8>'.
 - 'Pointer' is from 'dart:ffi'.
 - 'Uint8' is from 'dart:ffi'.
Try correcting the name to the name of an existing method, or defining a method named 'asExternalTypedData'.
    final pointerList = startingPointer.asExternalTypedData(
                                        ^^^^^^^^^^^^^^^^^^^
../../../.pub-cache/hosted/pub.dartlang.org/bitmap-0.0.5/lib/ffi.dart:29:21: Error: The method 'free' isn't defined for the class 'Pointer<Uint8>'.
 - 'Pointer' is from 'dart:ffi'.
 - 'Uint8' is from 'dart:ffi'.
Try correcting the name to the name of an existing method, or defining a method named 'free'.
    startingPointer.free();

How should the Uint8List for `Bitmap.fromHeadless` look

First of all thank you for this package.
However I am stuck while trying to convert an Uint8List to a bitmap.
What I am trying is:

  final bitmap = Bitmap.fromHeadless(
    this.width,
    this.height,
    layer
  );
  final headed = bitmap.buildHeaded();
  final imgMem = Image.memory(headed);
  return imgMem;

However the code always crashes at the buildHeaded().
Now I am wondering what the problem is and how the uint8list should be build.
Is it supposed to encode RGBA in separate ints like:

[255, 0, 0, 255]

for a completely red pixel?

publish newest changes to pub

There is code that allows you to rotate the bitmap clockwise/counterclockwise, but it doesn't show up when pulling the library from pub.
Had to copy/paste the file from here directly into my project.

Please update the pub version with the newest changes here.

Rotate?

Is there a way to rotate the image inside bitmap?

error

The method 'ImageStreamListener' isn't defined for the class 'ImageValueNotifier'.
The method 'fromHeadless' isn't defined for the class 'Bitmap'.
The function 'flipHorizontal' isn't defined.
The getter 'withHeader' isn't defined for the class 'Bitmap'.

Flutter Tests

Doesn't seem to work when running in flutter tests. Any plans to address in the future?

Desktop support

I'm trying to use images package but the performance is worst. Hope you makes the "image manipulation" cross-platform package <3

Failed to load some of the Bitmap package

I'm getting this exception when running the app after applying Bitmap package ;

       Invalid argument(s): Failed to load dynamic library (dlopen failed: library "libbitmap.so" not found)

Any idea why and how to solve this issue ?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.