### Install webpfy using npm or yarn
Source: https://github.com/iamlizu/webpfy/blob/main/README.md
Installs the webpfy package for image conversion. This command is run in the terminal to add the utility to your project dependencies.
```bash
npm install webpfy
# or
yarn add webpfy
```
--------------------------------
### Convert Image and Upload via API using webpfy
Source: https://github.com/iamlizu/webpfy/blob/main/README.md
This example demonstrates converting an image to WebP using webpfy and then uploading the converted file to an API endpoint using the `fetch` API. It shows how to construct a `FormData` object with the WebP blob and file name, and how to send a POST request. Error handling for both the image conversion and the API call is included. The `webpfy` function can optionally accept a `quality` parameter.
```javascript
import webpfy from "webpfy";
// Specify the image file to be converted (replace with your file input)
const fileInput = document.getElementById("fileInput"); // Replace 'fileInput' with your HTML input ID
const imageFile = fileInput.files[0];
// Optionally, specify the quality (default is 75)
const quality = 75;
// Create options object for image conversion
const options = {
image: imageFile,
quality,
};
// Use webpfy to convert the image
webpfy(options)
.then(async (result) => {
// Create a FormData object
const formData = new FormData();
// Append the converted WebP image to the FormData object
formData.append(
"your-image-field-name-here",
result.webpBlob,
result.fileName
);
try {
// Make an API call using fetch to upload the converted WebP image
const response = await fetch("https://example.com/api/upload", {
method: "POST",
body: formData,
});
if (response.ok) {
const responseData = await response.json();
// Handle the API response
console.log("Image uploaded successfully:", responseData);
} else {
// Handle API call errors
console.error(
"API call failed:",
response.status,
response.statusText
);
}
} catch (error) {
// Handle network errors or other issues
console.error("API call failed:", error);
}
})
.catch((error) => {
// Handle errors during image conversion
console.error("Image conversion error:", error);
});
```
--------------------------------
### Batch Convert Multiple Images with Progress Tracking (TypeScript)
Source: https://context7.com/iamlizu/webpfy/llms.txt
This example demonstrates how to concurrently convert multiple images to WebP format using webpfy. It maps over a FileList, performs individual conversions, and aggregates results, including statistics on successful and failed conversions, total savings, and compression ratio. Error handling is included for each individual conversion.
```typescript
import webpfy from 'webpfy';
async function convertMultipleImages(files: FileList, quality: number = 75) {
const conversions = Array.from(files).map(async (file, index) => {
try {
console.log(`Converting ${index + 1}/${files.length}: ${file.name}`);
const result = await webpfy({ image: file, quality });
return {
success: true,
fileName: result.fileName,
blob: result.webpBlob,
originalSize: file.size,
convertedSize: result.webpBlob.size,
savings: file.size - result.webpBlob.size
};
} catch (error) {
return {
success: false,
fileName: file.name,
error: (error as Error).message
};
}
});
const results = await Promise.all(conversions);
// Calculate statistics
const successful = results.filter(r => r.success);
const totalOriginalSize = successful.reduce((sum, r) => sum + (r.originalSize || 0), 0);
const totalConvertedSize = successful.reduce((sum, r) => sum + (r.convertedSize || 0), 0);
const totalSavings = totalOriginalSize - totalConvertedSize;
return {
results,
stats: {
total: files.length,
successful: successful.length,
failed: results.length - successful.length,
totalSavings,
compressionRatio: ((totalSavings / totalOriginalSize) * 100).toFixed(2) + '%'
}
};
}
// Usage with multiple file input
const multiFileInput = document.getElementById('multiUpload') as HTMLInputElement;
multiFileInput.addEventListener('change', async (e) => {
const files = (e.target as HTMLInputElement).files;
if (files && files.length > 0) {
const result = await convertMultipleImages(files, 80);
console.log('Batch conversion complete:', result.stats);
console.log('Individual results:', result.results);
}
});
```
--------------------------------
### Complete React Image Converter Component using webpfy
Source: https://github.com/iamlizu/webpfy/blob/main/README.md
This example provides a full React component that allows users to select an image, converts it to WebP using webpfy, and then displays the converted image for preview and download. It utilizes React's `useState` hook to manage the converted blob and file name, and `URL.createObjectURL` to display and link the WebP image. The `webpfy` function is imported and used within the `handleFileChange` function.
```javascript
import React, { useState } from "react";
import webpfy from "webpfy";
function ImageConverter() {
const [webpBlob, setWebpBlob] = useState(null);
const [fileName, setFileName] = useState("");
const handleFileChange = (event) => {
const imageFile = event.target.files[0];
if (imageFile) {
webpfy({ image: imageFile })
.then((result) => {
const { webpBlob, fileName } = result;
setWebpBlob(webpBlob);
setFileName(fileName);
})
.catch((error) => {
console.error("Image conversion error:", error);
});
}
};
return (
);
}
export default ImageConverter;
```
--------------------------------
### Convert Image to WebP using webpfy (JavaScript)
Source: https://github.com/iamlizu/webpfy/blob/main/README.md
Demonstrates how to use the webpfy utility in JavaScript to convert an image to WebP format. It requires importing the function and providing an image (File or Blob) and optional quality settings. The function returns a Promise that resolves with the WebP Blob and a suggested file name, or rejects with an error.
```javascript
import webpfy from 'webpfy';
// Specify the image you want to convert (e.g., a File or Blob)
const image = /* Provide your image here */;
// Optionally, specify the quality (default is 75)
const quality = 75;
// Create options object
const options = {
image,
quality
};
// Use webpfy to convert the image
webpfy(options)
.then(result => {
// Handle the result
console.log(`WebP Blob: ${result.webpBlob}`);
console.log(`WebP File Name: ${result.fileName}`);
// Save or use the WebP Blob or file name as needed
})
.catch(error => {
// Handle errors
console.error(error);
});
```
--------------------------------
### React Integration - File Upload Component
Source: https://context7.com/iamlizu/webpfy/llms.txt
A complete React component demonstrating file selection, conversion, preview, and download functionality with state management and error handling using the webpfy library.
```APIDOC
## React Integration - File Upload Component
### Description
Provides a reusable React component for image conversion to WebP, including file selection, preview, download, and error handling.
### Usage
```jsx
import React from 'react';
import ImageConverter from './ImageConverter'; // Assuming ImageConverter.tsx is in the same directory
function App() {
return (
);
}
export default ImageConverter;
```
### Props
This component does not accept any direct props. Its functionality is self-contained.
### State Variables
* **webpBlob**: Stores the converted WebP Blob.
* **fileName**: Stores the suggested filename for the WebP image.
* **previewUrl**: Stores the URL for previewing the converted image.
* **isConverting**: Boolean flag to indicate if a conversion is in progress.
* **error**: Stores any error message during conversion.
```
--------------------------------
### TypeScript Drag-and-Drop with WebP Conversion
Source: https://context7.com/iamlizu/webpfy/llms.txt
Implements a drag-and-drop zone using TypeScript. It listens for drag events, provides visual feedback, validates dropped files to ensure they are images, and uses the webpfy library to convert valid image files to WebP format. The converted WebP Blob and original filename are then passed to a callback function.
```typescript
import webpfy from 'webpfy';
class ImageDropZone {
private dropZone: HTMLElement;
private onConvert: (blob: Blob, fileName: string) => void;
constructor(elementId: string, onConvert: (blob: Blob, fileName: string) => void) {
this.dropZone = document.getElementById(elementId)!;
this.onConvert = onConvert;
this.setupListeners();
}
private setupListeners() {
['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
this.dropZone.addEventListener(eventName, this.preventDefaults, false);
});
['dragenter', 'dragover'].forEach(eventName => {
this.dropZone.addEventListener(eventName, () => {
this.dropZone.classList.add('highlight');
}, false);
});
['dragleave', 'drop'].forEach(eventName => {
this.dropZone.addEventListener(eventName, () => {
this.dropZone.classList.remove('highlight');
}, false);
});
this.dropZone.addEventListener('drop', this.handleDrop.bind(this), false);
}
private preventDefaults(e: Event) {
e.preventDefault();
e.stopPropagation();
}
private async handleDrop(e: DragEvent) {
const dt = e.dataTransfer;
const files = dt?.files;
if (files && files.length > 0) {
const file = files[0];
if (!file.type.startsWith('image/')) {
console.error('Not an image file');
return;
}
try {
const { webpBlob, fileName } = await webpfy({
image: file,
quality: 85
});
this.onConvert(webpBlob, fileName);
} catch (error) {
console.error('Conversion failed:', error);
}
}
}
}
// Usage
const dropZone = new ImageDropZone('dropArea', (blob, fileName) => {
console.log('Converted:', fileName, blob.size, 'bytes');
// Display preview
const img = document.getElementById('preview') as HTMLImageElement;
img.src = URL.createObjectURL(blob);
});
```
--------------------------------
### React Image to WebP Conversion Component (TypeScript)
Source: https://context7.com/iamlizu/webpfy/llms.txt
A React component that integrates the webpfy library to allow users to select an image file, convert it to WebP, display a preview, and download the converted file. It manages state for the converted blob, filename, preview URL, loading status, and errors. This component requires React and the webpfy library.
```typescript
import React, { useState } from 'react';
import webpfy from 'webpfy';
function ImageConverter() {
const [webpBlob, setWebpBlob] = useState(null);
const [fileName, setFileName] = useState('');
const [previewUrl, setPreviewUrl] = useState('');
const [isConverting, setIsConverting] = useState(false);
const [error, setError] = useState('');
const handleFileChange = async (event: React.ChangeEvent) => {
const imageFile = event.target.files?.[0];
if (!imageFile) return;
setIsConverting(true);
setError('');
try {
const { webpBlob, fileName } = await webpfy({
image: imageFile,
quality: 85
});
setWebpBlob(webpBlob);
setFileName(fileName);
// Create preview URL
const url = URL.createObjectURL(webpBlob);
setPreviewUrl(url);
} catch (err) {
setError('Image conversion failed: ' + (err as Error).message);
console.error('Conversion error:', err);
} finally {
setIsConverting(false);
}
};
const handleDownload = () => {
if (webpBlob && previewUrl) {
const link = document.createElement('a');
link.href = previewUrl;
link.download = fileName;
link.click();
}
};
return (
{isConverting &&
Converting...
}
{error &&
{error}
}
{webpBlob && (
Converted WebP Image:
Size: {(webpBlob.size / 1024).toFixed(2)} KB
)}
);
}
export default ImageConverter;
```
--------------------------------
### Convert Image to WebP in Browser (TypeScript)
Source: https://context7.com/iamlizu/webpfy/llms.txt
Demonstrates the primary use of the webpfy function to convert an image file selected by the user into WebP format. It handles user input, performs the conversion asynchronously, logs results, and initiates a download of the converted WebP blob. Dependencies include the webpfy library and browser DOM APIs.
```typescript
import webpfy from 'webpfy';
// Basic usage with file input
const fileInput = document.getElementById('imageUpload') as HTMLInputElement;
fileInput.addEventListener('change', async (event) => {
const file = (event.target as HTMLInputElement).files?.[0];
if (file) {
try {
const { webpBlob, fileName } = await webpfy({
image: file,
quality: 80 // Optional: 0-100, default is 75
});
console.log('Conversion successful!');
console.log('Blob size:', webpBlob.size, 'bytes');
console.log('Filename:', fileName);
// Create download link
const url = URL.createObjectURL(webpBlob);
const downloadLink = document.createElement('a');
downloadLink.href = url;
downloadLink.download = fileName;
downloadLink.click();
URL.revokeObjectURL(url);
} catch (error) {
console.error('Conversion failed:', error);
}
}
});
```
--------------------------------
### Upload Converted WebP Image to API using FormData and Fetch (TypeScript)
Source: https://context7.com/iamlizu/webpfy/llms.txt
This snippet shows how to convert an image to WebP using webpfy, then upload the resulting WebP blob to a REST API endpoint via FormData and the Fetch API. It includes error handling for the API request and processes the JSON response. Dependencies include the webpfy library and standard browser Fetch API.
```typescript
import webpfy from 'webpfy';
async function convertAndUploadImage(imageFile: File, apiEndpoint: string) {
try {
// Step 1: Convert image to WebP
const { webpBlob, fileName } = await webpfy({
image: imageFile,
quality: 75
});
// Step 2: Create FormData for API upload
const formData = new FormData();
formData.append('image', webpBlob, fileName);
formData.append('userId', '12345');
formData.append('description', 'Converted WebP image');
// Step 3: Upload to API
const response = await fetch(apiEndpoint, {
method: 'POST',
body: formData,
headers: {
'Authorization': 'Bearer YOUR_TOKEN_HERE'
}
});
if (!response.ok) {
throw new Error(`Upload failed: ${response.status} ${response.statusText}`);
}
const result = await response.json();
console.log('Upload successful:', result);
return {
success: true,
data: result,
originalSize: imageFile.size,
convertedSize: webpBlob.size,
compressionRatio: ((1 - webpBlob.size / imageFile.size) * 100).toFixed(2) + '%'
};
} catch (error) {
console.error('Process failed:', error);
return {
success: false,
error: (error as Error).message
};
}
}
// Usage
const fileInput = document.getElementById('upload') as HTMLInputElement;
fileInput.addEventListener('change', async (e) => {
const file = (e.target as HTMLInputElement).files?.[0];
if (file) {
const result = await convertAndUploadImage(file, 'https://api.example.com/upload');
console.log('Result:', result);
}
});
```
--------------------------------
### Convert Image to WebP in React using webpfy
Source: https://github.com/iamlizu/webpfy/blob/main/README.md
This snippet shows how to use the webpfy function within a React component to convert a user-selected image file to WebP format. It handles file selection, conversion, and error logging. The function `webpfy` takes an `image` file as input and returns a Promise that resolves with the `webpBlob` and `fileName`.
```javascript
/* rest of the relevant code */
const handleFileUpload = async (e) => {
const file = e.target.files[0];
try {
const { webpBlob, fileName } = await webpfy({ image: file }); // keeping the quality default
// Pass the webpBlob and fileName to the parent component to make API calls
getImage(webpBlob, fileName);
} catch (error) {
console.error("Error converting image to WebP:", error);
}
};
/* rest of the relevant code */
;
/* rest of the relevant code */
```
--------------------------------
### webpfy() - Main Conversion Function
Source: https://context7.com/iamlizu/webpfy/llms.txt
The primary function that converts any image (File or Blob) to WebP format using the browser-native Canvas API. It accepts an options object with the image and optional quality parameter, returning a Promise that resolves with the converted WebP blob and filename.
```APIDOC
## webpfy() - Main Conversion Function
### Description
Converts a given image file or Blob to WebP format using the browser's Canvas API.
### Method
`webpfy(options: { image: File | Blob; quality?: number }) => Promise<{ webpBlob: Blob; fileName: string }>`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
* **image** (File | Blob) - Required - The image file or Blob to convert.
* **quality** (number) - Optional - The quality of the WebP image (0-100). Defaults to 75.
### Request Example
```javascript
import webpfy from 'webpfy';
const fileInput = document.getElementById('imageUpload') as HTMLInputElement;
fileInput.addEventListener('change', async (event) => {
const file = (event.target as HTMLInputElement).files?.[0];
if (file) {
try {
const { webpBlob, fileName } = await webpfy({
image: file,
quality: 80 // Optional: 0-100, default is 75
});
console.log('Conversion successful!');
console.log('Blob size:', webpBlob.size, 'bytes');
console.log('Filename:', fileName);
// Create download link
const url = URL.createObjectURL(webpBlob);
const downloadLink = document.createElement('a');
downloadLink.href = url;
downloadLink.download = fileName;
downloadLink.click();
URL.revokeObjectURL(url);
} catch (error) {
console.error('Conversion failed:', error);
}
}
});
```
### Response
#### Success Response (Promise resolves with)
* **webpBlob** (Blob) - The converted image in WebP format.
* **fileName** (string) - A suggested filename for the converted image.
#### Response Example
```json
{
"webpBlob": Blob { ... },
"fileName": "converted_image.webp"
}
```
#### Error Handling
Throws an error if the conversion process fails.
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.