osamaqarem / react-native-image-colors Goto Github PK
View Code? Open in Web Editor NEWFetch prominent colors from an image.
License: MIT License
Fetch prominent colors from an image.
License: MIT License
It would be great if this supported cached images (just like react-native-fast-image
)
NOT WORKING IN REACT_NATIVE_CLI
Library | Version |
---|---|
react-native-image-colors | ^2.3.0 |
Describe what you expected to happen:
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}
/>
https://github.com/jathu/UIImageColors is archived and quite outdated.
Consider a popular fork: https://github.com/FelixHerrmann/UIImageColors
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! ๐
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.
Awesome Package ,
But is there any way to edit the colors ??
[!] 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.
Library | Version |
---|---|
react-native-image-colors | 1.5.1 |
rreact | 16.13.1 |
react-native | 0.63.2 |
npm i --save -E react-native-image-colors@latest
cd ios
pod install
n/a
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:
But none of them works. All of them results in a timeout failure.
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":
Notice the #000 as the fallback.
Library | Version |
---|---|
react-native-image-colors | 2.1.0 |
I'm using a Samsung Galaxy Tab S6 Lite (New - 2023)
#000
, this is very important to reproduce the bugDescribe what you expected to happen:
#000
fallback works fine for iOS but not for Android.Unknown fallback color
so its clear why this error is occurring. It took me awhile to figure this out.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
}
The lib works fine on iOS, but on android I'm getting this error - I'm not quite sure how to resolve - could you please advise
Is this library support expo?
I face error unhandled Promise Rejection Null is not an object.
ImageColorsModule.getColors
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!
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
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
Library | Version |
---|---|
react-native-image-colors | 2.3.0 |
npm run android
Describe what you expected to happen:
1.build success with no error
Can wrap node-vibrant.
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.
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.
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
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
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
Library | Version |
---|---|
react-native-image-colors | ^2.3.0 |
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
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')
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;
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]",
//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;
}
}
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};
};
`
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?
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')}} />
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
Library | Version |
---|---|
expo | ~49.0.6 |
react-native | 0.72.3 |
react-native-image-colors | ^2.3.0 |
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;
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.
React native: 0.72.1
Expo: 49.0.0
Library | Version |
---|---|
react-native-image-colors | 2.2.0 |
yarn android
@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
Is there any way I can pass in an Image blob as the source instead of a url?
I get error "could not download image"
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)"
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"
}
Library | Version |
---|---|
react-native-image-colors | 1.5.0 |
Describe what you expected to happen:
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:
Meanwhile, here it is on a mobile browser (you'll have to turn your phone sideways to see it on Snack)
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.
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"
}
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}
Describe what you expected to happen:
could see the code and run the code in the next repository:
Can you provide any details on how to config for Expo workflow?
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')]
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 :)
The package is unable to install using yarn and npm package manager.
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'
* 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]
Library | Version |
---|---|
react-native | 0.74.0-rc.8 |
expo | 51.0.0-preview.0 |
react-native-image-colors | 2.4.0 |
npm i expo@next
Describe what you expected to happen:
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?
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!
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
Library | Version |
---|---|
react-native-image-colors | 1.5.1 |
Cache image on device - try to use this lib - get error
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
When I navigate to the screen where the package is used twice, the screen freezes and takes 1 sec or more to load.
Library | Version |
---|---|
react-native-image-colors | 1.2.7 |
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);
};
}
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')
I need to use the functionality in expo, is it supported for expo 40.0.0
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.
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 %
Library | Version |
---|---|
"react": | "16.13.1", |
"react-native": | "0.63.2", |
Library | Version |
---|---|
react-native-image-colors | 1.2.4 |
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.