imgbb-webp-uploader
Version:
A utility for converting images to WebP format and uploading them to ImgBB
238 lines (187 loc) • 6.47 kB
Markdown
# ImgBB WebP Uploader
A React package that simplifies uploading images to ImgBB with automatic WebP conversion to reduce file size. Created and maintained by [Qrinux](https://qrinux.com/).
## Features
- 🖼️ **WebP Conversion** - Automatically converts images to WebP format before uploading
- 📊 **Progress Tracking** - Real-time progress updates for both conversion and upload
- 📏 **Size Comparison** - Shows file size before and after WebP conversion
- 🧩 **Multiple Integration Options** - Use as a React component, hook, or direct API
## Installation
```bash
npm install imgbb-webp-uploader
# or
yarn add imgbb-webp-uploader
```
## Usage
### 1. React Component
The simplest way to use the package is with the included React component:
```jsx
import React from 'react';
import { ImgBBUploader } from 'imgbb-webp-uploader';
function App() {
return (
<div>
<h1>Image Upload</h1>
<ImgBBUploader
apiKey="YOUR_IMGBB_API_KEY"
onSuccess={(response) => console.log('Upload successful:', response)}
onError={(error) => console.error('Upload failed:', error)}
/>
</div>
);
}
```
### 2. React Hook
For more control over the UI, use the hook:
```jsx
import React from 'react';
import { useImgBBUploader } from 'imgbb-webp-uploader';
function CustomUploader() {
const {
selectedFile,
previewUrl,
isUploading,
uploadedImage,
error,
progress,
originalSize,
webpSize,
sizeReduction,
handleFileChange,
uploadImage,
resetUpload
} = useImgBBUploader({
apiKey: "YOUR_IMGBB_API_KEY",
webpQuality: 0.8,
maxWidth: 1920
});
return (
<div>
<input type="file" onChange={handleFileChange} />
{previewUrl && (
<img src={previewUrl} alt="Preview" style={{ maxWidth: '300px' }} />
)}
{isUploading && <p>Uploading: {progress}%</p>}
<button onClick={uploadImage} disabled={!selectedFile || isUploading}>
Upload
</button>
{uploadedImage && (
<div>
<p>Image URL: {uploadedImage.url}</p>
<p>Size reduction: {sizeReduction}%</p>
</div>
)}
</div>
);
}
```
### 3. Direct API
For non-React applications or more advanced use cases:
```javascript
import { uploadToImgBB } from 'imgbb-webp-uploader';
async function uploadImage(file) {
try {
const response = await uploadToImgBB(file, {
apiKey: "YOUR_IMGBB_API_KEY",
convertToWebP: true,
webpQuality: 0.8,
maxWidth: 1920,
onProgress: (progress) => {
console.log(`Upload progress: ${progress}%`);
}
});
console.log('Upload successful:', response);
} catch (error) {
console.error('Upload failed:', error);
}
}
// Use with file input
document.getElementById('fileInput').addEventListener('change', (e) => {
const file = e.target.files[0];
if (file) {
uploadImage(file);
}
});
```
### 4. React Hook Form Integration
To use with `react-hook-form`, first install the required dependencies:
```bash
npm install react-hook-form imgbb-webp-uploader
```
Here's an example implementation:
```typescript
import React from 'react';
import { useForm, Controller } from 'react-hook-form';
import { ImgBBUploader } from 'imgbb-webp-uploader';
interface FormValues {
image: string;
}
const ReactHookFormExample = () => {
const { control, handleSubmit } = useForm<FormValues>();
const onSubmit = (data: FormValues) => {
console.log('Form submitted with image URL:', data.image);
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<Controller
name="image"
control={control}
defaultValue=""
render={({ field }) => (
<ImgBBUploader
apiKey="your-api-key"
onUploadComplete={(response) => {
field.onChange(response.url);
}}
/>
)}
/>
<button type="submit">Submit</button>
</form>
);
};
export default ReactHookFormExample;
```
### Key Features
- Seamless integration with `react-hook-form`
- Controller pattern for form management
- Automatic URL field population
- Easy form submission handling
## API Reference
### ImgBBUploader Component Props
| Prop | Type | Default | Description |
|------|------|---------|-------------|
| apiKey | string | - | **Required**. Your ImgBB API key |
| webpQuality | number | 0.8 | Quality of WebP conversion (0-1) |
| maxWidth | number | 1920 | Maximum width of the converted image |
| convertToWebP | boolean | true | Whether to convert to WebP before upload |
| onSuccess | function | - | Callback when upload succeeds |
| onError | function | - | Callback when upload fails |
| showPreview | boolean | true | Whether to show image preview |
| showFileInfo | boolean | true | Whether to show file size info |
| buttonText | string | "Upload to ImgBB" | Text for upload button |
| processingText | string | "Processing..." | Text during upload |
### useImgBBUploader Hook Options
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| apiKey | string | - | **Required**. Your ImgBB API key |
| webpQuality | number | 0.8 | Quality of WebP conversion (0-1) |
| maxWidth | number | 1920 | Maximum width of the converted image |
| convertToWebP | boolean | true | Whether to convert to WebP before upload |
| onSuccess | function | - | Callback when upload succeeds |
| onError | function | - | Callback when upload fails |
### uploadToImgBB Function Parameters
| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| file | File | - | **Required**. The image file to upload |
| options | object | - | Upload options |
| options.apiKey | string | - | **Required**. Your ImgBB API key |
| options.webpQuality | number | 0.8 | Quality of WebP conversion (0-1) |
| options.maxWidth | number | 1920 | Maximum width of the converted image |
| options.convertToWebP | boolean | true | Whether to convert to WebP before upload |
| options.onProgress | function | - | Progress callback function |
## License
MIT
## Creator
This package is created and maintained by [Qrinux](https://qrinux.com/), a software development company specializing in web technologies and image optimization solutions.
## Support
For support, feature requests, or bug reports, please visit [Qrinux website](https://qrinux.com/) or open an issue on GitHub.