App.jsx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 |
// React.js Project to Build Image Cropper Editor Using react-image-crop Library import React, { useState, useRef } from 'react'; import ReactCrop, { centerCrop, makeAspectCrop } from 'react-image-crop'; import 'react-image-crop/dist/ReactCrop.css'; function ImageCropper() { const [image, setImage] = useState(null); const [crop, setCrop] = useState({ unit: '%', x: 25, y: 25, width: 50, height: 50, }); const [completedCrop, setCompletedCrop] = useState(null); const [croppedImageUrl, setCroppedImageUrl] = useState(null); const imgRef = useRef(null); const canvasRef = useRef(null); const onImageLoad = (e) => { const { naturalWidth: width, naturalHeight: height } = e.currentTarget; setCrop(centerCrop(makeAspectCrop({ unit: '%', width: 50 }, 1, width, height), width, height)); }; const onCropComplete = (crop) => { setCompletedCrop(crop); if (crop && imgRef.current) { generateCroppedImage(crop); } }; const generateCroppedImage = (crop) => { const image = imgRef.current; const canvas = canvasRef.current; const scaleX = image.naturalWidth / image.width; const scaleY = image.naturalHeight / image.height; canvas.width = crop.width; canvas.height = crop.height; const ctx = canvas.getContext('2d'); ctx.drawImage( image, crop.x * scaleX, crop.y * scaleY, crop.width * scaleX, crop.height * scaleY, 0, 0, crop.width, crop.height ); const url = canvas.toDataURL('image/jpeg'); setCroppedImageUrl(url); }; const handleImageChange = (e) => { const file = e.target.files[0]; if (file) { const url = URL.createObjectURL(file); setImage(url); } }; const downloadCroppedImage = () => { if (croppedImageUrl) { const link = document.createElement('a'); link.href = croppedImageUrl; link.download = 'cropped-image.jpg'; link.click(); } }; return ( <div style={{ textAlign: 'center', padding: '20px' }}> <h2>React Image Crop Demo</h2> <input type="file" accept="image/*" onChange={handleImageChange} /> {image && ( <ReactCrop crop={crop} onChange={(newCrop) => setCrop(newCrop)} onComplete={onCropComplete} aspect={1} > <img ref={imgRef} src={image} alt="To Crop" style={{ maxWidth: '100%' }} onLoad={onImageLoad} /> </ReactCrop> )} <div style={{ margin: '20px 0' }}> {croppedImageUrl && ( <> <h3>Cropped Image Preview:</h3> <img src={croppedImageUrl} alt="Cropped Preview" style={{ maxWidth: '100%' }} /> <button style={{ marginTop: '10px' }} onClick={downloadCroppedImage}> Download Cropped Image </button> </> )} </div> <canvas ref={canvasRef} style={{ display: 'none' }} /> </div> ); } export default ImageCropper; |