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 |
// How to Crop Images in React: Easy Guide with react-cropper Library import React, { useRef, useState } from 'react'; import Cropper from 'react-cropper'; import 'cropperjs/dist/cropper.css'; // Import the CSS for Cropper const ImageCropper = () => { const cropperRef = useRef(null); const [image, setImage] = useState(""); // Image source const [croppedImage, setCroppedImage] = useState(""); // Handle image selection const onImageChange = (e) => { if (e.target.files && e.target.files.length > 0) { const file = e.target.files[0]; const reader = new FileReader(); reader.onload = () => { setImage(reader.result); }; reader.readAsDataURL(file); } }; // Crop the image and get the result const cropImage = () => { const cropper = cropperRef.current?.cropper; if (cropper) { const croppedCanvas = cropper.getCroppedCanvas(); // Get the cropped canvas setCroppedImage(croppedCanvas.toDataURL()); // Convert it to a data URL } }; return ( <div style={{ padding: '20px' }}> <h2>React Cropper Example</h2> {/* Image Input */} <input type="file" accept="image/*" onChange={onImageChange} style={{ marginBottom: '20px' }} /> {/* Cropper Component */} {image && ( <Cropper src={image} style={{ height: 400, width: '100%' }} aspectRatio={16 / 9} // Set the aspect ratio (optional) guides={true} // Show guides (optional) ref={cropperRef} cropBoxResizable={true} // Allow resizing of crop box viewMode={1} // Restrict cropping to the image boundary /> )} {/* Buttons */} <div style={{ marginTop: '20px' }}> <button onClick={cropImage} style={{ marginRight: '10px' }}> Crop Image </button> </div> {/* Cropped Image Preview */} {croppedImage && ( <div> <h3>Cropped Image</h3> <img src={croppedImage} alt="Cropped" style={{ maxWidth: '100%', marginTop: '10px' }} /> </div> )} </div> ); }; export default ImageCropper; |