Coder Social home page Coder Social logo

marcglasberg / image_pixels Goto Github PK

View Code? Open in Web Editor NEW
24.0 2.0 5.0 187 KB

Flutter Package: Lets you extend the background color of an image, or else build any widget that depends on the image width/height, and the color of its pixels.

License: MIT License

Swift 2.53% Objective-C 0.24% Dart 96.36% Java 0.87%

image_pixels's People

Contributors

esentis avatar marcglasberg 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

Watchers

 avatar  avatar

image_pixels's Issues

Null check operator used on a null value

he following _TypeError was thrown building ImagePixels(dirty, state: _ImagePixelsState#d22d7):
Null check operator used on a null value

The relevant error-causing widget was
ImagePixels
sard_widget.dart:290
When the exception was thrown, this was the stack
#0 _FeedSardWidgetState.build.


`ImagePixels(
                        imageProvider: CachedNetworkImageProvider(
                          "https://storage.googleapis.com/siyaq-videos/b7g3uge8kla3v4xsrnuh8fbz5g6db6s3.jpg",
                          //   maxHeight: 600,
                          maxWidth: Get.width.toInt(),
                        ),
                        defaultColor: Colors.grey,
                        builder: (context, img) => img.height! > 600
                            ? CachedNetworkImage(
                                imageUrl:
                                    "https://storage.googleapis.com/siyaq-videos/b7g3uge8kla3v4xsrnuh8fbz5g6db6s3.jpg",
                                fit: BoxFit.fitWidth,
                                width: double.infinity,
                                filterQuality: FilterQuality.high,
                                height: 600.h,
                              )
                            : CachedNetworkImage(
                                width: double.infinity,
                                imageUrl:
                                    "https://storage.googleapis.com/siyaq-videos/b7g3uge8kla3v4xsrnuh8fbz5g6db6s3.jpg",
                                fit: BoxFit.fitWidth,
                                // // (widget.sard.content![0].file!.heightInPx! /
                                // Get.pixelRatio)
                              ),
                      )`

img.hasImage seems to loose it's state at one point

Hello,

im using your library and I'm really thankful for your work! I noticed some strange behavior which seems to have something to do with your value img.hasImage

I created an own widget which I'm using in a FutureBuilder. The FutureBuilder is fetching data from a server and returns a list with an image and text. I'm applying the data to this widget. It shows a background gradient where it picks a color from the given image, some text and the image itself in the foreground.

Im picking the color with img.pixelColorAtAlignment(Alignment.bottomRight). In the imageProvider im applying the fetched image. I wrapped the Background Container with an AnimatedOpacity so I can fade in the color if we have access to the image.

But most of the time if I show the next item from the list, we already have the given color, but the background is flashing for a millisecond and then shows back the picked color. It seems that we are loosing the img.hasImage for a short period, until it's back in there. The flashing occurs, because of my AnimatedOpacity which waits for the result of img.hasImage

FYI: If I remove the AniamtedOpacity The short period shows a yellow background (I defined the defaultColor as yellow to analyze the behavior). I also placed a print statement in my FutureBuilder Widget Build, to see if there is any rebuild, but there isn't.

Hope you can find a solution

return ImagePixels(
        defaultColor: Colors.red,
        imageProvider: imageUrl != null ? NetworkImage(imageUrl) : fallback, <-- imageProvider is the fetched image
        builder: (context, img) {
          return Stack(
            children: [
              AnimatedOpacity(
                  opacity: img.hasImage ? 1.0 : 0.0, <-- checking if image has image, if yes we have a fading animation
                  duration: Duration(milliseconds: 200),
                  child: Container(
                    width: cardWidth,
                    height: cardHeight,
                    decoration: BoxDecoration(
                      gradient: LinearGradient(
                          colors: [
                            const Color.fromARGB(20, 20, 21, 1)
                            img.pixelColorAtAlignment(Alignment.bottomRight), <- picking the color
                          ],
                          begin: Alignment.topLeft,
                          end: Alignment.bottomCenter,
                          stops: [0.35, 1]),
                    ),
                  )),
              //),
              Container(
...

Memory leak when using many ImagePixel widgets

We've wanted to incorporate more complex UIs with quite a couple of ImagePixel-widgets in our flutter app.
The results being that after loading around 20 sub-pages (closing every single one before opening the next) and populating an infinite scrolling list (even though using a SliverList.builder to not render more than needed) the apps memory started to run full, get laggy and crash consistently.

I think this might be due to the streams & eventListeners being created/added in _GetImage.run():282 which never get removed. In other flutter example which do a similar thing, these listeners always get removed.

We've hat to ditch this feature and supply the colors manually, but it might be worth looking into.

Using SVG images

Hi @marcglasberg ,
First of all, thanks for the amazing package, it's helped me a lot. I can use img.pixelColorAt() to get color from 1 point in the image
But now I must use svg image as my input and it doesn't work

    Widget flutter = SvgPicture.asset(AssetHelper.gioviet); //this is svg image link
    ImageProvider flutterImageProvider = flutter as ImageProvider;
    Offset localPosition = const Offset(10, 10);
    return ImagePixels(
      imageProvider: flutterImageProvider,
      builder: (BuildContext context, ImgDetails img) {
        var color = img.pixelColorAt!(
          localPosition.dx.toInt(),
          localPosition.dy.toInt(),
        );
        Brightness brightness = ThemeData.estimateBrightnessForColor(color);
        return SizedBox(
          width: 150,
          height: 213,
          child: Column(
            children: [
              Image(image: flutterImageProvider),
              Text("Pixel color at top-left: $color."),
              Text("And brightness: $brightness."),
            ],
          ),
        );
      },
    );

Do you have any idea to solve my problem
Thanks

support network images

Please also support network images.
Unable to get information about the current image due to a flutter bug.

The method 'toDouble' was called on null.

Hi,

I got the following exception when getting the original size of a network image. This does not make my app crash but would like to handle this.

════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
The following NoSuchMethodError was thrown building ImagePixels(dirty, state: _ImagePixelsState#98fea):
The method 'toDouble' was called on null.
Receiver: null
Tried calling: toDouble()

The relevant error-causing widget was: 
  ImagePixels file:///C:/Data/Personality/SideProjects/TiengVietDep/tieng_viet_dep/lib/scenes/ReadingPage.dart:146:7
When the exception was thrown, this was the stack: 
#0      Object.noSuchMethod (dart:core-patch/object_patch.dart:51:5)
#1      double./ (dart:core-patch/double.dart:52:23)
#2      _ReadingPageState.buildContent.<anonymous closure> (package:tieng_viet_dep/scenes/ReadingPage.dart:151:48)
#3      _ImagePixelsState.build (package:image_pixels/src/image_pixels.dart:225:55)
#4      StatefulElement.build (package:flutter/src/widgets/framework.dart:4744:28)
...
════════════════════════════════════════════════════════════════════════════════════════════════════

Here is the code to reproduce this exception:

Widget buildContent(BuildContext context, String url) {
    final width = MediaQuery.of(context).size.width;
    final height = MediaQuery.of(context).size.height;
    print("Screen size: $width $height");
    Image nimg = Image.network(url);
    precacheImage(nimg.image, context);
    print(nimg);
    return Stack(children: [
      Center(
          child: Image(
            image: nimg.image,
            fit: BoxFit.fill,
            width: width,
            height: height,
          )
      ),
      ImagePixels(
        imageProvider: nimg.image,
        builder: (context, img) {
          return Positioned(
              
              top: img != null ? 92.0 * (height/img.height) : 0.0,
              left: img != null ? 137.0 * (width/img.width) : 0.0,
              child: InkWell(
                onTap: () {
                  print("On tap");
                  playAudio();
                },
                child:
                Container(
                  width: 50,
                  height: 50,
                  color: Colors.grey[100],
                ),

              )
          );
        },
      )
    ]);
  }

imageProvider ignores dimensions of ResizeImage

Hi :)

First of all, thanks for the amazing package ❤

I cannot find information about this anywhere -- I'm getting unexpected results for the following code:

    final originalImage = AssetImage(silhouette['path']); // w100 h200
    final image = ResizeImage(
      originalImage,
      height: 100, // set the height to 100
    );
    
    return ImagePixels(
      imageProvider: image,
      builder: (context, img) {
        if (!img.hasImage) {
          return SizedBox();
        }
        
        print('${img.width}'); // 100
        print('${img.height}'); // 200

Is there a way to make ResizeImage work with ImagePixels?

Buildcontext !0 null is not true

Hello and thank you for your library.

Im using your library for placing a background color to my image. Using the lastest versions of flutter and your library, this is the error i'm receiving:

════════ Exception caught by scheduler library ═════════════════════════════════
'package:image_pixels/src/image_pixels.dart': Failed assertion: line 252 pos 16: 'buildContext != null': is not true.
════════════════════════════════════════════════════════════════════════════════

Im using it inside a Widget:

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

class SwipeCard extends StatelessWidget {
  const SwipeCard({
    Key key,
    this.cardWidth,
    this.cardHeight,
    this.fooName,
    this.foo2Name,
    this.imageUrl,
  }) : super(key: key);

  final double cardHeight;
  final double cardWidth;
  final String fooName;
  final String foo2Name;
  final String imageUrl;

  @override
  Widget build(BuildContext context) {
    return ImagePixels.container(
    defaultColor: Color.fromRGBO(20, 20, 22, 1),
    imageProvider: NetworkImage(imageUrl != null ?  imageUrl : ''),    
    colorAlignment: Alignment.topLeft,
    child: Container(
      decoration: BoxDecoration(
        gradient: LinearGradient(
                    colors: [
                      const Color.fromRGBO(21, 21, 22, 0.5),
                      const Color.fromRGBO(20, 20, 22, 1),
                    ],
                    begin: Alignment.topLeft,
                    end: Alignment.bottomRight,
                    stops: [0.0, 1]),
                ),
      width: cardWidth,
      height: cardHeight,
      child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Column(
              children: [
                Container(
                ...

I'm using the SwipeCard here:

return Stack(
      children: [
        Consumer<FooNotifier>(builder: (__, consumerValues, _) {
          return FutureBuilder(
            future: fooFuture,
            // ignore: missing_return
            builder: (context, snapshot) {
              switch (snapshot.connectionState) {
                case ConnectionState.none:
                  break;
                case ConnectionState.waiting:
                  return Center(child: CircularProgressIndicator());
                  break;
                case ConnectionState.done:
                  return consumerValues.swiperList.length != 0
                      ? ListView.builder(
                          physics: NeverScrollableScrollPhysics(),
                          itemCount: consumerValues.swiperList.length ?? 0,
                          itemBuilder: (BuildContext context, int index) {
                     
                             return Dismissible(
                              resizeDuration: Duration(milliseconds: 1500),
                              onDismissed: (DismissDirection direction) {
                                setState(() {
                                  consumerValues.swiperList.removeAt(index);
                                  print(consumerValues.swiperList);
                               });
                              },

                              secondaryBackground: Container(
                                child: Center(
                                  child: Text(
                                    'Foo geliked',
                                    style: TextStyle(color: Colors.black),
                                  ),
                                ),
                                color: Colors.lightGreenAccent,
                              ),
                              background: Container(
                                  child: Center(
                                    child: Text(
                                      'Nicht interessant',
                                      style: TextStyle(color: Colors.black),
                                    ),
                                  ),
                                  color: Colors.redAccent),
                              child: SwipeCard(
                                cardWidth: MediaQuery.of(context).size.width * 1,
                                cardHeight:
                                    MediaQuery.of(context).size.height * 1,
                                fooName:
                                    consumerValues.swiperList[index].fooName,
                                foo2Name:
                                    consumerValues.swiperList[index].foo2Name,
                                imageUrl:
                                    consumerValues.swiperList[index].imageUrl,
                              ),
                              key: UniqueKey(),
                              direction: DismissDirection.horizontal,
                            );
                          },
                        )
                      : SwipeNoItems();

                  break;
                default:
              }
            },
          );
        }),
        SafeArea(
          child: Padding(
            padding: const EdgeInsets.all(15.0),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                IconButton(
                  icon: SvgPicture.asset(
                    'assets/icon-close-boxed.svg',
                    fit: BoxFit.contain,
                    width: 35,
                    height: 35,
                    //color: Colors.white,
                  ),
                  onPressed: () async {
                    await Provider.of<FooControls>(context,
                            listen: false)
                        .stop();
                    widget.func(0);
                  },
                  tooltip: 'Close',
                ),
              ],
            ),
          ),
        ),
      ],
    );

[web] Error: Failed to encode the image into bytes.

Hi :)

After upgrading to flutter 3.0.0 we're unable to use image_pixels @ web:

Error: Failed to encode the image into bytes.
    at Object.createErrorWithStack (http://localhost:52985/dart_sdk.js:5093:12)
    at Function._throw (http://localhost:52985/dart_sdk.js:20399:18)
    at Function.throwWithStackTrace (http://localhost:52985/dart_sdk.js:20396:18)
    at async._AsyncCallbackEntry.new.callback (http://localhost:52985/dart_sdk.js:40921:18)
    at Object._microtaskLoop (http://localhost:52985/dart_sdk.js:40778:13)
    at _startMicrotaskLoop (http://localhost:52985/dart_sdk.js:40784:13)
    at http://localhost:52985/dart_sdk.js:36261:9

We've found this issue which seems to be the cause of it?

Any help is appreciated.

Thanks,

Ivan

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.