Image Format Converter

This component allows you to convert images to different formats (PNG, JPEG, WebP).

Original

Image in JPG format

Format Conversion

Compressed

Edited Image

Installation

Install dependencies

1npm install pixel-craft --save

Copy the source code

components/ImageCompressor.tsx

1import React, { useEffect, useRef, useState } from 'react';
2
3type FormatConverterProps = {
4  src: string;
5  format?: 'image/png' | 'image/jpeg' | 'image/webp';
6  quality?: number;
7  alt?: string;
8  width?: number;
9  height?: number;
10};
11
12const ImageFormatConverter: React.FC<FormatConverterProps> = ({
13  src,
14  format = 'image/png',
15  quality = 0.92,
16  alt = 'Converted Image',
17  width,
18  height,
19}) => {
20  const canvasRef = useRef<HTMLCanvasElement>(null);
21  const [convertedSrc, setConvertedSrc] = useState<string | null>(null);
22
23  useEffect(() => {
24    const img = new Image();
25    img.crossOrigin = 'anonymous';
26    img.src = src;
27
28    img.onload = () => {
29      const canvas = canvasRef.current;
30      if (canvas) {
31        canvas.width = width || img.width;
32        canvas.height = height || img.height;
33        const ctx = canvas.getContext('2d');
34        if (ctx) {
35          ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
36          const newDataUrl = canvas.toDataURL(format, quality);
37          setConvertedSrc(newDataUrl);
38        }
39      }
40    };
41  }, [src, format, quality, width, height]);
42
43  return (
44    <div>
45      <canvas ref={canvasRef} style={{ display: 'none' }} />
46      {convertedSrc && (
47        <>
48          <h4>Preview - Format: {format}</h4>
49          <img src={convertedSrc} alt={alt} width={width} height={height} style={{ border: '1px solid #ccc' }} />
50        </>
51      )}
52    </div>
53  );
54};
55
56export default ImageFormatConverter;

Props

string
Prop nameTypeDefaultDescription
srcStringRequiredSource of the original image. Can be a URL or base64 data URI.
format'image/png' | 'image/jpeg' | 'image/webp''image/png'Output image format.
qualitynumber0.92Compression quality (0.0 to 1.0) for JPEG/WebP. Ignored for PNG.
alt
'Converted Image'
Alternative text for the img element.
widthnumberOriginal widthWidth of the output image (resized via canvas).
heightnumberOriginal heightHeight of the output image (resized via canvas).

Possible Errors and User Measures

Error/ IssueCauseUser's Measures/ Fixes
Image doesn't loadInvalidsrcor cross-origin restrictions Ensure the source image supports CORS or use same-origin URLs
Converted image is blankcanvas.getContext('2d') is null, or image draws before it finishes loadingEnsure image is fully loaded before drawing, and always check context availability
Unsupported formatBrowser doesn't support image/webp or chosen formatUse HTMLCanvasElement.toDataURL() conditionally based on format support
Quality out of boundsQuality 0 or 1 causes errors or unexpected outputClamp quality to range [0, 1]
Image dimensions mismatchUser-definedwidth/height do not preserve aspect ratioProvide optional auto-scaling or aspect ratio lock
Large images cause memory issues Using canvas with high-res images may cause performance drops or crashesWarn users or add client-side image resizing before rendering

Real World Uses

Image format conversion before upload

Compress JPEG or convert PNG/WebP to reduce upload size

Dynamic format delivery

Allow users to preview and download images in different formats

Cross-browser compatibility

Convert images into formats supported by specific browsers

Media export tool

Enable export of images to various formats for download or sharing

Optimization Techniques



TechniquesBenefits
Use WebP or AVIF formats Smaller size with similar or better quality than JPEG/PNG
Lazy load and off-screen canvasPrevents unnecessary canvas usage when not visible
Compress before conversion Reduces memory usage and faster rendering
Cache converted images Improve performance by saving and reusing data URLs
Use responsive srcSet for displayImprove clarity on high-DPI devices while keeping file size low