react-native-nitro-image-colors
v0.4.0
Published
High-performance React Native library for extracting prominent colors from images. Built with Nitro Modules for optimal performance on iOS and Android with smart caching and TypeScript support.
Maintainers
Readme
🎨 React Native Nitro Image Colors
A high-performance React Native library for extracting prominent colors from images. Built with Nitro Modules for optimal performance on both iOS and Android.
✨ Features
- 🚀 High Performance: Native implementation using Kotlin and Swift
- 🎯 Accurate Color Extraction: Advanced algorithms for precise color detection
- 📱 Cross-Platform: Consistent API across iOS and Android
- 🔄 Smart Caching: Built-in caching to avoid reprocessing
- 🎨 Rich Color Palette: Extract multiple color variants (dominant, vibrant, muted, etc.)
- ⚡ Lightweight: Minimal bundle size impact
- 🔧 TypeScript Support: Full TypeScript definitions included
📸 Demo
Extract beautiful color palettes from your images with just a few lines of code!
🚀 Installation
npm install react-native-nitro-image-colors react-native-nitro-modulesOr using Yarn:
yarn add react-native-nitro-image-colors react-native-nitro-modulesNote:
react-native-nitro-modulesis required as this library relies on Nitro Modules.
iOS Configuration
For iOS, you need to install the native dependencies:
cd ios && pod installAndroid Configuration
No additional configuration required for Android.
📖 Usage
Basic Usage
import { getColors } from 'react-native-nitro-image-colors';
// Extract colors from a remote image
const colors = await getColors({
uri: 'https://example.com/image.jpg',
});
console.log(colors);
// Output:
// {
// platform: 'ios',
// background: '#3A506B',
// primary: '#1C2541',
// secondary: '#5BC0BE',
// detail: '#0B132B'
// }Advanced Configuration
import { getColors, type Config } from 'react-native-nitro-image-colors';
const config: Config = {
fallback: '#000000', // Color used if extraction fails
pixelSpacing: 5, // Pixel sampling rate (Android only)
cache: true, // Enable caching
headers: {
// HTTP headers for remote images
Authorization: 'Bearer token',
},
key: 'custom-cache-key', // Custom cache key
};
const colors = await getColors(
{ uri: 'https://example.com/image.jpg' },
config
);React Component Example
import React, { useState, useEffect } from 'react';
import { View, Text, Image } from 'react-native';
import { getColors, type ImageColors } from 'react-native-nitro-image-colors';
const ColorExtractor = ({ imageUri }: { imageUri: string }) => {
const [colors, setColors] = useState<ImageColors | null>(null);
const [loading, setLoading] = useState(false);
useEffect(() => {
const extractColors = async () => {
setLoading(true);
try {
const extractedColors = await getColors({ uri: imageUri });
setColors(extractedColors);
} catch (error) {
console.error('Failed to extract colors:', error);
} finally {
setLoading(false);
}
};
extractColors();
}, [imageUri]);
if (loading) {
return <Text>Extracting colors...</Text>;
}
if (!colors) {
return <Text>No colors extracted</Text>;
}
return (
<View>
<Image source={{ uri: imageUri }} style={{ width: 200, height: 200 }} />
<View style={{ flexDirection: 'row', flexWrap: 'wrap' }}>
{Object.entries(colors)
.filter(([key, value]) => key !== 'platform' && typeof value === 'string')
.map(([key, color]) => (
<View
key={key}
style={{
backgroundColor: color,
width: 50,
height: 50,
margin: 4,
borderRadius: 8,
justifyContent: 'center',
alignItems: 'center'
}}
>
<Text style={{ fontSize: 8, color: 'white', fontWeight: 'bold' }}>
{key}
</Text>
</View>
))}
</View>
</View>
);
};🎨 API Reference
getColors(uri, config?)
Extracts prominent colors from an image.
Parameters
uri:number | ImageSourcePropType- Image URI or resource IDconfig?:Config- Optional configuration object
Returns
Promise<ImageColors> - Object containing extracted colors
Configuration Options
| Option | Type | Default | Description |
| -------------- | ------------------------ | ----------- | ---------------------------------- |
| fallback | string | '#000000' | Fallback color if extraction fails |
| pixelSpacing | number | 5 | Pixel sampling rate (Android only) |
| headers | Record<string, string> | {} | HTTP headers for remote images |
| cache | boolean | true | Enable in-memory caching |
| key | string | Image URI | Custom cache key |
ImageColors Response
The returned object contains platform-specific color properties:
iOS Colors
background: Primary background colorprimary: Main primary colorsecondary: Secondary accent colordetail: Detail/text color
Android Colors
dominant: Most frequent coloraverage: Average color of the imagevibrant: Vibrant color variantdarkVibrant: Dark vibrant variantlightVibrant: Light vibrant variantdarkMuted: Dark muted variantlightMuted: Light muted variantmuted: Muted color variant
Common Property
platform:'ios' | 'android'- Platform where colors were extracted
🔧 TypeScript Support
Full TypeScript definitions are included:
import {
getColors,
type ImageColors,
type Config,
} from 'react-native-nitro-image-colors';🚨 Error Handling
try {
const colors = await getColors({ uri: 'https://example.com/image.jpg' });
// Use colors...
} catch (error) {
if (error instanceof Error) {
console.error('Color extraction failed:', error.message);
}
// Use fallback colors or show error message
}🎯 Best Practices
1. Cache Wisely
// Use caching for better performance
const config: Config = {
cache: true,
key: 'unique-image-key', // Required for long URIs
};2. Handle Network Images
// Add headers for authenticated images
const config: Config = {
headers: {
Authorization: 'Bearer your-token',
},
};3. Optimize Performance
// Adjust pixel spacing for balance between accuracy and performance
const config: Config = {
pixelSpacing: 10, // Higher values = faster but less accurate
};📱 Example App
Check out the example app for a complete implementation:
cd example
yarn install
yarn ios # or yarn android🔍 Troubleshooting
Common Issues
Colors not extracted
- Check image URI is accessible
- Verify network permissions for remote images
- Try with a different image format
Performance issues
- Increase
pixelSpacingvalue - Enable caching with
cache: true - Use local images when possible
- Increase
TypeScript errors
- Ensure you have TypeScript installed
- Check import statements
🤝 Contributing
We welcome contributions! Please see our Contributing Guide for details.
Development Workflow
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests if applicable
- Submit a pull request
📄 License
This project is licensed under the MIT License - see the LICENSE file for details.
🙏 Acknowledgments
- Built with Nitro Modules
- Inspired by color extraction algorithms from both platforms
- Thanks to all contributors who help improve this library
Made with ❤️ by Yogesh Solanki
