Ant Oleyhoo
Ant Oleyhoo

Reputation: 77

How to get the approximate background color of an image?

Is there a way to get the approximate background color from an image in Flutter? I am getting my image from a URL. I don't need an exact background color: just an approximation - for instance, getting the color of the pixel in the top left corner (0, 0) would be just fine.

There seems to be no easy way to do this - I have tried many imaging packages, but they only provide "primary color" and not background color.

Upvotes: 0

Views: 1327

Answers (2)

Marcelo Glasberg
Marcelo Glasberg

Reputation: 30889

Old question, but for people still needing this, see the ImagePixels widget from the https://pub.dev/packages/image_pixels package (I am the author of this package):

@override
Widget build(BuildContext context) {
    return ImagePixels(
              imageProvider: image,
              builder: (context, img) {
                  Color topLeftColor = img.pixelColorAt(0, 0);
                  Text("Pixel color at top-left: $topLeftColor.");
              );}} 

Note you could also get a dozen pixels all around the image (or at the corners of the image), and then average them. This would have a better chance of getting a good representative color.

Also note, if all you want to do with this color is to extend it to a larger area, there is a constructor that does that for you: ImagePixels.container.

Upvotes: 3

Michel Feinstein
Michel Feinstein

Reputation: 14276

Have you tried the image package?

If you just want the top left corner pixel, I believe you can read the image's pixels and get it.

Upvotes: 0

Related Questions