Coder Social home page Coder Social logo

osamaqarem / react-native-image-colors Goto Github PK

View Code? Open in Web Editor NEW
647.0 647.0 35.0 20.26 MB

Fetch prominent colors from an image.

License: MIT License

Ruby 7.62% Java 16.36% JavaScript 4.83% Swift 29.52% Objective-C 0.59% TypeScript 24.93% Objective-C++ 4.81% Kotlin 11.15% C 0.19%

react-native-image-colors's Introduction

react-native-image-colors's People

Contributors

bibazavr avatar dependabot[bot] avatar evansendra avatar krzysztofmoch avatar matteodanelli avatar mohit23x avatar osamaqarem avatar tewarig 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

react-native-image-colors's Issues

Cached Images Support

It would be great if this supported cached images (just like react-native-fast-image)

Cannot find native module 'ImageColors'

Bug

NOT WORKING IN REACT_NATIVE_CLI

Environment info

Library Version
react-native-image-colors ^2.3.0

Steps To Reproduce

  1. npm install react-native-image-colors
  2. npx react-native start then press a for android

Describe what you expected to happen:

  1. When app is open and direct show this error : cannot find native module 'ImageColors'

Reproducible sample code

State

const [backgroundColors, setBackgroundColors] = useState({});

Fatching Image Color Function

const fetchImageColor = async (imageUrl: any, index: any) => {

try {
  const colors: any = await getColors(imageUrl, {
    fallback: '#228B22',
    cache: true,
    key: imageUrl,
  });
  setBackgroundColors((prevColors: any) => ({
    ...prevColors,
    [index]: colors.dominant || '#228B22',
  }));
} catch (error) {
  console.error('Error fetching image colors:', error);
}

};

Render Flatlist Item

const _renderItem = ({item}: any) => {

const bgColor = backgroundColors[item?.id] || 'coolGray.200';
if (!backgroundColors[item?.id]) {
  fetchImageColor(item?.thumbnail || item?.images[0], item?.id);
}
return (
  <VStack
    bg={bgColor}
    h={60}
    rounded={'md'}
    marginX={2}
    marginY={2}
    style={{
      shadowColor: '#000',
      shadowOffset: {
        width: 0,
        height: 2,
      },
      shadowOpacity: 0.25,
      shadowRadius: 3.84,
      elevation: 5,
    }}>
    {/* Image Container */}
    <Image
      size={60}
      alt={item?.title}
      borderRadius={100}
      mx={2}
      source={{
        uri: item?.thumbnail,
        cache: 'force-cache',
      }}
      fallbackSource={{
        uri: item?.images[0],
      }}
    />
  </VStack>
);

};

FlatList

<FlatList
data={products}
keyExtractor={(item: any, index: any) => index}
ListEmptyComponent={_listEmptyComponent}
renderItem={_renderItem}
/>

Screenshot_1701674120

iOS build error related to Swift

If you face about a 100 build errors similar to the following:

ld: warning: Could not find auto-linked library 'swiftFoundation'
ld: warning: Could not find auto-linked library 'swiftDarwin'
ld: warning: Could not find auto-linked library 'swiftCoreFoundation'
ld: warning: Could not find auto-linked library 'swiftCore'
ld: warning: Could not find auto-linked library 'swiftCoreGraphics'
ld: warning: Could not find auto-linked library 'swiftObjectiveC'
ld: warning: Could not find auto-linked library 'swiftDispatch'
ld: warning: Could not find auto-linked library 'swiftSwiftOnoneSupport'
Undefined symbols for architecture arm64:

Creating a blank swift file using xcode in my iOS project seems to alleviate this issue.
You can follow this (although there was no need to create a bridging header in my case or change any build settings).

If someone knows how to fix this automatically, please let me know. Thanks! ๐Ÿ™

Need to update kotlin-gradle-plugin to 1.6.20 as kotlin-android-extensions needs gradle plugin version >= 1.6.20

We are using react native 0.71.1 and this uses

error Failed to install the app. Make sure you have the Android development environment set up: https://reactnative.dev/docs/environment-setup.
Error: Command failed: ./gradlew app:installProdDebug -PreactNativeDevServerPort=8081

FAILURE: Build failed with an exception.

  • What went wrong:
    The Android Gradle plugin supports only kotlin-android-extensions Gradle plugin version 1.6.20 and higher.
    The following dependencies do not satisfy the required version:
    project ':react-native-image-colors' -> org.jetbrains.kotlin:kotlin-gradle-plugin:1.6.0

Color edit

Awesome Package ,
But is there any way to edit the colors ??

pod install error

Bug

  • when i try to use the command pod install in ios folder, it happens.
[!] The following Swift pods cannot yet be integrated as static libraries:

The Swift pod `RNImageColors` depends upon `React-Core`, which does not define modules. To opt into those targets generating module maps (which is necessary to import them from Swift when building as static libraries), you may set `use_modular_headers!` globally in your Podfile, or specify `:modular_headers => true` for particular dependencies.
Couldn't install Pods. Updating the Pods project and trying again...
Command `pod install` failed.
โ””โ”€ Cause: The following Swift pods cannot yet be integrated as static libraries:

The Swift pod `RNImageColors` depends upon `React-Core`, which does not define modules. To opt into those targets generating module maps (which is necessary to import them from Swift when building as static libraries), you may set `use_modular_headers!` globally in your Podfile, or specify `:modular_headers => true` for particular dependencies.

Environment info

Library Version
react-native-image-colors 1.5.1
rreact 16.13.1
react-native 0.63.2

Steps To Reproduce

npm i --save -E react-native-image-colors@latest
cd ios
pod install

Reproducible sample code

n/a

Not able to test await ImageColors.getColors using jest

I'm not able to test await ImageColors.getColors method. I tried following approaches:

Code :
const fileContent = await RNFS.readFile(${imageSrc}, 'base64');
console.log('file',fileContent); // it prints in all the cases whether it's test case or app debugging.
const imageColor = await ImageColors.getColors(data:image/jpeg;base64,${fileContent}, {
fallback: DEFAULT_LAYER_COLOR,
});
console.log('imageColor',imageColor); // when running the test case it never prints, test fails with a timeout error.

Mocking the method :

jest.mock('react-native-image-colors', () => ({
getColors: jest.fn().mockReturnValue(Promise.resolve({
background: '#000000',
primary: '#d4d4d4',
secondary: '#e4e4e4',
detail: '#b4b4b4',
quality: 'high',
platform: 'ios',
})),
}));

OR

jest.mock('react-native-image-colors', () => ({
getColors: jest.fn(),
}));

Asserting the method call in different ways:

  1. expect(ImageColors.getColors as jest.Mock).toHaveBeenCalled();
  2. const getColorsSpy = jest.spyOn(ImageColors, 'getColors');
    getColorsSpy.mockReturnValue(Promise.resolve(colors)); // colors = constant
  3. (ImageColors.getColors as jest.Mock).mockReturnValue(Promise.resolve(color));
  4. await (ImageColors.getColors as jest.Mock).mockImplementation(() => Promise.resolve('ss'));

But none of them works. All of them results in a timeout failure.

Android always gives unknown color error when fallback color is #000

Bug

When I call getColors using the following example code.

import React from 'react'
import { getColors } from 'react-native-image-colors'

const useImageColors = () => {
  const [colors, setColors] = React.useState(null)

  React.useEffect(() => {
    const url = 'https://i.imgur.com/68jyjZT.jpg'

    getColors(url, {
      fallback: '#000',
      cache: true,
      key: url,
    }).then(setColors)
  }, [])

  return colors
}

I keep getting the following error "Unknown color":

Screenshot 2023-06-29 at 3 17 09 PM

Notice the #000 as the fallback.

Environment info

Library Version
react-native-image-colors 2.1.0

I'm using a Samsung Galaxy Tab S6 Lite (New - 2023)

Steps To Reproduce

  1. Use an Android device
  2. Use the example code above on version 2.1.0
  3. Make sure the fallback is set to #000, this is very important to reproduce the bug
  4. Check the console for the error "Unknown color"

Describe what you expected to happen:

  1. I expected it to detect the color like it does for iOS. This #000 fallback works fine for iOS but not for Android.
  2. I also think the error message could be improved it should say Unknown fallback color so its clear why this error is occurring. It took me awhile to figure this out.

Reproducible sample code

import React from 'react'
import { getColors } from 'react-native-image-colors'

const useImageColors = () => {
  const [colors, setColors] = React.useState(null)

  React.useEffect(() => {
    const url = 'https://i.imgur.com/68jyjZT.jpg'

    getColors(url, {
      fallback: '#000', // <---------------- IMPORTANT for bug to reproduce on Android
      cache: true,
      key: url,
    }).then(setColors)
  }, [])

  return colors
}

Unhandled Promise Rejection

Is this library support expo?

I face error unhandled Promise Rejection Null is not an object.
ImageColorsModule.getColors

Question: How to get the colors for a portion of an image

I'd like to use this library to control the color of the text component displayed in front of an image. I want to sample a small part of the image rather than the entire image. If this isn't possible with this lib could you point me in the right direction?

I'd be super grateful for some help! Thanks!

iOS - Module not able to Download file from Camera roll path e.g ph://19816598-0009-4C6B-BE19-2939E73737E8/L0/001

URI = ph://19816598-0009-4C6B-BE19-2939E73737E8/L0/001

local storage URI doesn't download the image.

const getColors = async (uri) => {
    try {
      const colors = await ImageColors.getColors(uri, {
        fallback: '#fff',
      });
      return Platform.OS === 'ios' ? colors.background :  colors.lightMuted;
    } catch (e) {
      console.log(e);
    }
  };

Error:

Error: Could not download image.
    at Object.promiseMethodWrapper [as getColors] (NativeModules.js:103)
    at Object.getColors (index.js:8)
    at getColors$ (index.js:40)
    at tryCatch (runtime.js:63)
    at Generator.invoke [as _invoke] (runtime.js:293)
    at Generator.next (runtime.js:118)
    at tryCatch (runtime.js:63)
    at invoke (runtime.js:154)
    at runtime.js:189
    at tryCallTwo (core.js:45)

Please help @osamaq

[Android] build failed

Bug

build failed on react-native 0.73, using openjdk 17

Here is the error message:

'compileDebugJavaWithJavac' task (current target is 17) and 'compileDebugKotlin' task (current target is 11) jvm target compatibility should be set to the same Java version. Consider using JVM toolchain: https://kotl.in/gradle/jvm/toolchain

Environment info

Library Version
react-native-image-colors 2.3.0

Steps To Reproduce

  1. Install this library and setup the expo modules
  2. run npm run android

Describe what you expected to happen:

1.build success with no error

Reproducible sample code

[Error: ImageColors: Invalid image URI โ€“ failed to get image]

Bug

Error: [Error: ImageColors: Invalid image URI โ€“ failed to get image]

ss

Library Version
react-native-image-colors 1.5.2
expo: ~47.0.12
react 18.1.0
react-native 0.70.5

I have an app the user enters url and the app gets the preview image of the url. Then I use this colors to show a gradient view for images. When trying to get the colors from the given url its not giving any warning and crashing the app directly.

iOS: It's not working with local URI returned by RNFS.LibraryDirectoryPath

It's not working with local URI, such as that returned by RNFS.LibraryDirectoryPath in the react-native-fs library.

In my case the URI value is /Users/aman.birdi/Library/Developer/CoreSimulator/Devices/674B2D17-A812-42C9-8E54-1D01D353967C/data/Containers/Data/Application/05897FAC-C6A7-4FD4-A118-E4199C98A8B4/Library/Caches/Books/ae038166-d3a3-49f9-920d-8fd35ec21ba2_small_cover.jpg.

I tried to pass it with and without require but no luck.

ImageColors: Illegal character in path

Bug

Environment info

Library Version
react-native-image-colors 1.5.2

when I try to get the image color for this path : "file:///storage/emulated/0/Images/Duck/Screenshot at Apr 29 08-52-35.png"

Error : ImageColors: Illegal character in path

Pod install not working after installing react-native-image-colors

Bug

Hi guys, I tried adding this library to a project I am working on, but after installing tha package, when I try to run npx pod-install I get this error

I already install the expo modules since I saw it was required, and if I unninstall the react-native-image-colors pod install works that's why I guess the issue can be around here, or something conflicting with library but I don't get any insight from the error message
image

Also if I run the pod install command with verbose flag, I get somewhat more information but nothing I consider really useful, since the android manifest do not anything but <manifest> tag

thanks beforehand

image

Environment info

Library Version
react-native-image-colors ^2.3.0

Android crash

image

Library Version
react-native-image-colors 1.3.0
react-native-native 0.64.2

See on the image more details on the device

Happens when calling ImageColors.getColors(url, { cache: true })

Android not working

I'm getting this error, tried to debug but no success, any help? iOS works fine btw

Error: ImageColors: Attempt to invoke interface method 'boolean com.facebook.react.bridge.ReadableMap.hasKey(java.lang.String)' on a null object reference

System:
OS: macOS 10.15.4
Shell: 5.7.1 - /bin/zsh
Binaries:
Node: 12.14.0
Yarn: 1.13.0
npm: 6.13.4
Managers:
CocoaPods: 1.9.1
SDKs:
iOS SDK:
Platforms: iOS 13.5, DriverKit 19.0, macOS 10.15, tvOS 13.4, watchOS 6.2
Android SDK:
API Levels: 16, 19, 22, 23, 25, 26, 27, 28, 29
Build Tools: 27.0.3, 28.0.1, 28.0.2, 28.0.3, 29.0.2, 30.0.1
System Images: android-27 | Google APIs Intel x86 Atom, android-28 | Google APIs Intel x86 Atom, android-28 | Google Play Intel x86 Atom
Android NDK: 17.1.4828580
IDEs:
Android Studio: 4.0 AI-193.6911.18.40.6514223
Xcode: 11.5/11E608c
Languages:
Java: 1.8.0_201
npmPackages:
react: 16.13.1 => 16.13.1
react-native: 0.63.2 => 0.63.2

TypeError: null is not an object (evaluating '_module.RNImageColors.getColors')

HEllo, running a very basic Expo Managed app using this library

What I have done:

  • npx create-expo-app ExpoProject

  • in ExpoProject replace the App.js with the one attached
    App.txt

  • cd ExpoProject

  • npx expo install expo-image-picker

  • npx expo install expo-image-manipulator

  • npm install react-native-image-colors

  • npx expo prebuild

  • npx expo start

TypeError: null is not an object (evaluating '_module.RNImageColors.getColors')

Expo "Possible Unhandled Promise Rejection: TypeError: Cannot read property 'getColors' of undefined" issue

I'm trying to paint the background of my card element according to image on the card, using this repo. These individual cards are rendered in a horizontal view by mapping.

The code of the card component is given below. I want to get the desired color of asset.imgUrl . And paint the background color of card to that color. But when I'm trying to get the color, getColor property is given me an warning

Possible Unhandled Promise Rejection (id: ): TypeError: Cannot read property 'getColors' of undefined

I've check the URLs and coming data. But everything was looking fine. Why getColor is not working and giving me an unhandled promise error ?

import {
  Text,
  StyleSheet,
  View,
  Image,
  Pressable,
  ActivityIndicator,
} from "react-native";
import { textStylesEQ } from "../constants/textStyles";
import { useNavigation } from "@react-navigation/native";
import ImageColors from "react-native-image-colors";
import { useEffect, useState } from "react";

const initialState = {
  colorOne: { value: "", name: "" },
  colorTwo: { value: "", name: "" },
  rawResult: "",
};

const AssetCard = ({ asset }) => {
  const [colors, setColors] = useState(initialState);
  const [loading, setLoading] = useState(true);

  const navigation = useNavigation();

  const navigateToAssetDetails = (asset) => {
    navigation.navigate("AssetDetails", { asset });
  };

  useEffect(() => {
    const fetchColors = async () => {
      const result = await ImageColors.getColors(asset.imageUrl, {
        fallback: "blue",
        quality: "high",
        pixelSpacing: 5,
        cache: true,
      });

      switch (result.platform) {
        case "android":
          setColors({
            colorOne: { value: result.lightVibrant, name: "lightVibrant" },
            colorTwo: { value: result.average, name: "average" },
            rawResult: JSON.stringify(result),
          });
          break;
        case "ios":
          setColors({
            colorOne: { value: result.detail, name: "detail" },
            colorTwo: { value: result.background, name: "background" },
            rawResult: JSON.stringify(result),
          });
          break;
        default:
          throw new Error("Unexpected platform");
      }

      console.log(colors);

      setLoading(false);
    };

    fetchColors();
  }, []);

  if (loading) {
    return <ActivityIndicator />;
  }

  return (
    <>
      <Pressable key={asset._id} onPress={() => navigateToAssetDetails(asset)}>
        <View style={styles.assetContainer}>
          <View
            style={{
              width: "100%",
              flexDirection: "row",
              alignItems: "center",
              justifyContent: "space-between",
            }}
          >
            <Image
              style={{ height: 40, width: 40, borderRadius: 50 }}
              source={{ uri: asset.imageUrl }}
              resizeMode="contain"
            />
            <Some stuff need to be secret />
          </View>
        </View>
      </Pressable>
    </>
  );
};

const styles = StyleSheet.create({
  assetContainer: {
    alignItems: "flex-start",
    justifyContent: "space-between",
    backgroundColor: "blue",
    padding: 10,
    marginRight: 20,
    borderRadius: 20,
    width: 135,
    height: 170,
  },
  assetImage: {
    width: "100%",
  },
});

export default AssetCard;

This is not working in Apple tv .

Bug

Getting this error in Apple tv simulator
TypeError: null is not an object (evaluating '_$$_REQUIRE(_dependencyMap[4], "./module").RNImageColors.getColors')

## Environment info
Apple tv- Not working
iOS mobile- Working
Android mobile- Working
Android mobile- Working
Web - Not working

Library
"react-native-image-colors": "^1.5.1",
"react": "17.0.2",
"react-native": "npm:[email protected]",

Reproducible sample code

//get primary color of the given image url
export const imgBGPrimaryColor=async(url)=>{
try {
console.log('--url------',url)
const result = await ImageColors.getColors(url, {
fallback: '#4d5152',
cache: false,
key: url,
})
return result;
} catch (e) {
throw e;
}
}

Please provide the support, Please help i am stuck here

Can not find native module ImageColors in react native cli

In my react native projects, It's thrwoing the error can not find native module ImageColors.
`import {useEffect, useState} from 'react';
import {colors} from '../constants/tokens';
import {getColors} from 'react-native-image-colors';

export const usePlayerBackground = imageUrl => {
const [imageColors, setImageColors] = useState(null);
console.log('imageColors: ', imageColors);

useEffect(() => {
getColors(imageUrl, {
fallback: colors.background,
cache: true,
key: imageUrl,
}).then(colors => setImageColors(colors));
}, [imageUrl]);

return {imageColors};
};
`

Getting different color in both platform

Hi, thanks for this awesome library, I am using this in one of my react native projects. But my client wants me to get the same exact color for IOS and Android as well, but this library gives different color for the same image. what should I do?

Error in fetching the image

On android getting the colour is failing with the below trace:

Error: ImageColors: https://mobile-a5b2257ca.hana.ondemand.com/mobilemediaimage/ImageSet(Objecttype='KLAH',Objectkey='MYM_L5',Doctype='B0')/$value
at Object.promiseMethodWrapper [as getColors] (NativeModules.js:103)
at Object.getColors (index.js:8)
at eval (VM6 RootHierarchyNode.bundle:62)
at commitHookEffectListMount (ReactNativeRenderer-dev.js:15561)
at commitPassiveHookEffects (ReactNativeRenderer-dev.js:15618)
at Object.invokeGuardedCallbackImpl (ReactNativeRenderer-dev.js:265)
at invokeGuardedCallback (ReactNativeRenderer-dev.js:476)
at flushPassiveEffectsImpl (ReactNativeRenderer-dev.js:18795)
at unstable_runWithPriority (scheduler.development.js:653)
at runWithPriority (ReactNativeRenderer-dev.js:5268)

The image is not public but the same link works when given like and the image loads perfectly:
<Image source={{uri: 'https://mobile-a5b2257ca.hana.ondemand.com/mobilemediaimage/ImageSet(Objecttype='KLAH',Objectkey='MYM_L5',Doctype='B0')/$value')}} />

this package is not working

Bug

i'm practicing in an expo app i follow all the instructions in the package and i get this error:

Possible Unhandled Promise Rejection (id: 0):
Error: Cannot find native module 'ImageColors', js engine: hermes

Environment info

Library Version
expo ~49.0.6
react-native 0.72.3
react-native-image-colors ^2.3.0

Steps To Reproduce

import { View, ActivityIndicator, Dimensions, ScrollView } from 'react-native';
import React from 'react';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import Carousel from 'react-native-snap-carousel';
import ImageColors from 'react-native-image-colors';
import { useMovies } from '../hooks/useMovies';
import { MoviePoster } from '../components/MoviePoster';
import HorizontalSlider from '../components/HorizontalSlider';
import GradientBackground from '../components/GradientBackground';

const windowWidth = Dimensions.get('window').width;

const HomeScreen = () => {
	const { top } = useSafeAreaInsets();

	const { nowPlaying, popular, topRated, upcoming, isLoading } = useMovies();

	const getPosterColors = (index: number) => {
		const movie = nowPlaying[index];
		const uri = `https://image.tmdb.org/t/p/w500${movie.poster_path}`;

		const colors = await ImageColors.getColors(uri, {});
                console.log(colors)


	};

	if (isLoading) {
		return (
			<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
				<ActivityIndicator color='red' size={20} />
			</View>
		);
	}

	return (
		<GradientBackground>
			<ScrollView>
				<View style={{ marginTop: top + 20 }}>
					{/* Main Carousel */}
					<View style={{ height: 440 }}>
						<Carousel
							data={nowPlaying}
							renderItem={({ item }) => <MoviePoster movie={item} />}
							sliderWidth={windowWidth}
							itemWidth={300}
							inactiveSlideOpacity={0.9}
							onSnapToItem={(index) => getPosterColors(index)}
						/>
					</View>

					{/* Popular Movie */}
					<HorizontalSlider title='Popular' movies={popular} />
					<HorizontalSlider title='Top Rated' movies={topRated} />
					<HorizontalSlider title='Upcoming' movies={upcoming} />
				</View>
			</ScrollView>
		</GradientBackground>
	);
};

export default HomeScreen;

Error when building for Android with Expo SDK 49 and React Native 0.72.1

Bug

After upgrading to Expo SDK 49, when building a new version for Android, an error pops up.

Could not set unknown property 'classifier' for task ':react-native-image-colors:androidSourcesJar' of type org.gradle.api.tasks.bundling.Jar.

Environment info

React native: 0.72.1
Expo: 49.0.0

Library Version
react-native-image-colors 2.2.0

Steps To Reproduce

  1. Upgrade to Expo SDK 49 and React Native 0.72.1
  2. Build a version for Android with yarn android

image

Can't access getColors

@osamaqarem When I use
import ImageColors from "react-native-image-colors";
I get error
TypeError: Cannot read property 'getColors' of undefined

When I use
import { getColors } from "react-native-image-colors";
I get error
TypeError: (0 , _reactNativeImageColors.getColors) is not a function

My code below:

import ImageColors from "react-native-image-colors";
class Expression extends Component {
async componentDidMount() {
const expressionBackground = await ImageColors.getColors(
this.props.data.expression.urls.max
);
console.log({ expressionBackground });
}
..... rest of code ....

I use Expo, could this be an issue?
I would really really like a solution to this.
This package is the most promising I've found to get image colors

Work with Data URIs on Android

There is an issue when we provide a base64 Data URI in android. On iOS it works fine.

On android it ends in error:

code:"Error"
message:"ImageColors: Invalid URL"
nativeStackAndroid:Array(0) []
stack:"Error: ImageColors: Invalid URL
    at Object.promiseMethodWrapper [as getColors] (/Users/shashwatjain/Repos/iconnect_rn/.vscode/.react/index.bundle:4597:36)
    at updateColor$ (/Users/shashwatjain/Repos/iconnect_rn/.vscode/.react/index.bundle:288053:83)
    at tryCatch (/Users/shashwatjain/Repos/iconnect_rn/.vscode/.react/index.bundle:25312:19)
    at Generator.invoke [as _invoke] (/Users/shashwatjain/Repos/iconnect_rn/.vscode/.react/index.bundle:25485:24)
    at Generator.next (/Users/shashwatjain/Repos/iconnect_rn/.vscode/.react/index.bundle:25355:23)
    at tryCatch (/Users/shashwatjain/Repos/iconnect_rn/.vscode/.react/index.bundle:25312:19)
    at invoke (/Users/shashwatjain/Repos/iconnect_rn/.vscode/.react/index.bundle:25385:22)
    at /Users/shashwatjain/Repos/iconnect_rn/.vscode/.react/index.bundle:25415:13
    at tryCallTwo (/Users/shashwatjain/Repos/iconnect_rn/.vscode/.react/index.bundle:27376:7)
    at doResolve (/Users/shashwatjain/Repos/iconnect_rn/.vscode/.react/index.bundle:27540:15)"

[Web] different color detection on mobile browser vs desktop

Bug

Mobile browsers and desktop browsers return a different set of colors for the same image. I'm not sure if this is a bug with node-vibrant or this library's Web approach. My guess is it's node vibrant?

Take this image:

On a desktop browser, I get these colors, which seem relatively correct. They're essentially grays.

{
  "dominant": "#3c3c3c",
  "vibrant": "#7f7f7f",
  "darkVibrant": "#424242",
  "lightVibrant": "#bcbcbc",
  "darkMuted": "#3c3c3c",
  "lightMuted": "#acacac",
  "muted": "#7c7c7c",
  "platform": "web"
}

However, on a mobile browser (Chrome or Safari on iOS), I get these colors:

{
  "dominant": "#443c3e",
  "vibrant": "#3fbf7f",
  "darkVibrant": "#040c08",
  "lightVibrant": "#9bddbc",
  "darkMuted": "#443c3e",
  "lightMuted": "#b4bcb4",
  "muted": "#847c81",
  "platform": "web"
}

Environment info

Library Version
react-native-image-colors 1.5.0

Steps To Reproduce

  1. Use this image URL: https://res.cloudinary.com/dn29xlaeh/image/upload/q_75,w_640/v1/beatgig-live/quhilykqgarpqnf9peyk
  2. Get the colors on a mobile browser
  3. Get the colors on a desktop browser

Describe what you expected to happen:

  1. The colors on both platforms should be the same.

Reproducible sample code

Here is a reproducible snack: https://snack.expo.dev/@beatgig/thankful-almond?supportedPlatforms=web

These are the colors it comes up with on a desktop browser:

Screen Shot 2022-04-05 at 11 26 50 AM

Meanwhile, here it is on a mobile browser (you'll have to turn your phone sideways to see it on Snack)

IMG_6045

Error in react native CLI

Bug

I installed the library (I use react native CLI), and created the custom hook from the example, but when using it, it showed me the following error:

1| import { requireNativeModule } from 'expo-modules-core';
| ^
2 | // It loads the native module object from the JSI or falls back to
3 | // the bridge module (from NativeModulesProxy) if the remote debugger is on.
4 | export default requireNativeModule('ImageColors');

I don't understand why expo imports a native react native CLI library, and if it is required, they should specify it when implementing the example.

Environment info

im using typescript and react native CLI, this is the content of package.json
{
"name": "AppPeliculas",
"version": "0.0.1",
"private": true,
"scripts": {
"android": "react-native run-android",
"ios": "react-native run-ios",
"lint": "eslint .",
"start": "react-native start",
"test": "jest"
},
"dependencies": {
"@react-navigation/native": "^6.1.7",
"@react-navigation/stack": "^6.3.17",
"@types/react-native-snap-carousel": "^3.8.5",
"axios": "^1.5.0",
"currency-formatter": "^1.5.9",
"fbjs": "^3.0.5",
"react": "18.2.0",
"react-native": "0.72.4",
"react-native-gesture-handler": "^2.13.1",
"react-native-image-colors": "^2.3.0",
"react-native-linear-gradient": "^2.8.3",
"react-native-safe-area-context": "^4.7.2",
"react-native-screens": "^3.25.0",
"react-native-snap-carousel": "^3.9.1",
"react-native-vector-icons": "^10.0.0"
},
"devDependencies": {
"@babel/core": "^7.20.0",
"@babel/preset-env": "^7.20.0",
"@babel/runtime": "^7.20.0",
"@react-native/eslint-config": "^0.72.2",
"@react-native/metro-config": "^0.72.11",
"@tsconfig/react-native": "^3.0.0",
"@types/currency-formatter": "^1.5.2",
"@types/react": "^18.0.24",
"@types/react-native-vector-icons": "^6.4.15",
"@types/react-test-renderer": "^18.0.0",
"babel-jest": "^29.2.1",
"eslint": "^8.19.0",
"jest": "^29.2.1",
"metro-react-native-babel-preset": "0.76.8",
"prettier": "^2.4.1",
"react-test-renderer": "18.2.0",
"typescript": "4.8.4"
},
"engines": {
"node": ">=16"
}

Steps To Reproduce

  1. my project works correctly
  2. I install the library with yarn (yarn add react-native-image-colors)
  3. I created a custom hook using the example code, as seen in the following code:

import { useEffect, useState } from 'react'
import { getColors } from 'react-native-image-colors'
export default function useColors(){
const [colors, setColors] = useState(null)

const get = async()=>{
const url = 'https://i.imgur.com/68jyjZT.jpg'
await getColors(url, {
fallback: '#228B22',
cache: true,
key: url,
}).then(res=>console.log(res))
}
useEffect(() => {
get()

}, [])

return {colors}

  1. send me the error

Describe what you expected to happen:

  1. my project works correctly
  2. I install the library with yarn (yarn add react-native-image-colors)
  3. I create a custom hook using the example code
  4. It compiles correctly with the library

Reproducible sample code

could see the code and run the code in the next repository:

https://github.com/victor291201/pelisApp-ReactNative

Expo Support

Can you provide any details on how to config for Expo workflow?

Evaluating 'ImageColorsModule.getColors' error

Hi,
I am getting the following error when trying to fetch colors from an image:
`[Unhandled promise rejection: TypeError: null is not an object (evaluating 'ImageColorsModule.getColors')]

  • node_modules/react-native-image-colors/index.js:7:26 in ImageColors.getColors`

The object (or the url of the image) is not null.

Looks like an awesome library and I really hope I can make it work :)

how to use on web

I've installed on my project reactjs and typescript but it doesn't work.

./node_modules/node-libs-browser/node_modules/url/url.js
Error: ENOENT: no such file or directory, open '/Users/.../node_modules/node-libs-browser/node_modules/url/url.js'

[Expo 51] Build failed on android

Bug

* Where:
Script '/home/***/Documents/project/****/node_modules/expo-modules-core/android/ExpoModulesCorePlugin.gradle' line: 43

* What went wrong:
A problem occurred evaluating project ':react-native-image-colors'.
> Failed to apply plugin 'kotlin-android'.
   > Extension of type 'JavaPluginExtension' does not exist. Currently registered extension types: [ExtraPropertiesExtension, VersionCatalogsExtension, KotlinAndroidProjectExtension, KotlinTestsRegistry]

Environment info

Library Version
react-native 0.74.0-rc.8
expo 51.0.0-preview.0
react-native-image-colors 2.4.0

Steps To Reproduce

  1. Running in bare react-native project
  2. npm i expo@next

Describe what you expected to happen:

  1. Build successfully

Reproducible sample code

Error: ImageColors: Illegal character in opaque part at index 98

I'm using react-native-android-installed-apps to receive base64 data for icons of app installed on the device and trying to get the colors for each one use getColors(). However this throws the following error:

Error: ImageColors: Illegal character in opaque part at index 98:

I manually had to append data:image/png;base64, to the beginning of the base64 data returned by react-native-android-installed-apps and wondering if that is part of the problem?

Here's what I'm trying:

const img = `data:image/png;base64,${this.props.item.icon.trim()}`;
const result = await ImageColors.getColors(img, {
        fallback: '#cccccc',
        cache: true,
        key: this.props.item.packageName,
 });

Getting the same result on emulators running Android 9 to 11.

I can provide an example of the base64 data I'm using if needed?

can get same color both ios and android?

I'm having a problem that I can get the same color between 2 operating systems android and ios. Is there any way to have the same color with the same photo? Thanks!

Not working with locally cached images

Bug

Hi
It works fine with network images but doesn't work with locally cached, for example in iOS simulator I get error Could not download image.

/Users/user/Library/Developer/CoreSimulator/Devices/9037008E-2E06-47F7-A73E-1000FC5D391A/data/Containers/Data/Application/3CB6B487-41AE-431A-B479-3A418EDA442A/Documents/app-app_development/1.jpg

Environment info

Library Version
react-native-image-colors 1.5.1

Steps To Reproduce

Cache image on device - try to use this lib - get error

expo compatibility

Hi it says that this package is supported on expo projects but I am still getting this error

TypeError: null is not an object (evaluating '_module.RNImageColors.getColors')

I am using this version "react-native-image-colors": "^1.5.0" with the sample provided on the example page

Performance issue

Bug

When I navigate to the screen where the package is used twice, the screen freezes and takes 1 sec or more to load.

Environment info

Library Version
react-native-image-colors 1.2.7

Reproducible sample code

try {
	if (isExpo) throw null;

	const ImageColors = require('react-native-image-colors').default;

	getColorFromImage = async (image, callback) => {
		ImageColors.getColors(image)
			.then((color) => {
				if (color.platform === 'android') {
					return callback(color.muted);
				}
			})
			.catch(() => {});
	};
} catch {
	getColorFromImage = (image, callback) => {
		callback(Colors.lightGreen);
	};
}

Possible Unhandled Promise: null is not an object

I am trying to use the package for the first time testing with the same sample code:

 async function imageToColors(imageUrl){
        const colors = await ImageColors.getColors(imageUrl, {
            average: true,
            defaultColor: "#000000"
        });

        if (colors.platform === "android") {
        // Access android properties
        // e.g.
        const averageColor = colors.average;
        } else {
        // Access iOS properties
        // e.g.
        const backgroundColor = colors.background;
        }
        console.log('====================================');
        console.log(colors);
        console.log('====================================');
    }

I get this error, when I run the function.
Possible Unhandled Promise Rejection (id: 18): TypeError: null is not an object (evaluating '_reactNativeImageColors.default.getColors')

build android error Plugin with id 'maven' not found.

Bug

FAILURE: Build failed with an exception.

  • Where:
    Build file '/Volumes/machd/angulare/app/Studiokore/node_modules/react-native-image-colors/android/build.gradle' line: 23

  • What went wrong:
    A problem occurred evaluating project ':react-native-image-colors'.

Plugin with id 'maven' not found.

  • 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.

Deprecated Gradle features were used in this build, making it incompatible with Gradle 8.0.

You can use '--warning-mode all' to show the individual deprecation warnings and determine if they come from your own scripts or plugins.

See https://docs.gradle.org/7.4.2/userguide/command_line_interface.html#sec:command_line_warnings

BUILD FAILED in 36s
antoniomarques@Mac-mini Studiokore %

Captura de Tela 2022-05-11 aฬ€s 10 53 26

Environment info

Library Version
"react": "16.13.1",
"react-native": "0.63.2",
Library Version
react-native-image-colors 1.2.4

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.