ImageUpload
Component for uploading, previewing, and cropping images with constrained aspect ratios.
The ImageUpload component is a framework tool for uploading, previewing, and cropping images. It provides an interactive interface, where users can either drag and drop an image or choose one via the file explorer. Upon uploading, a preview is presented within a canvas element, allowing users to adjust the crop area according to the provided aspect ratios before saving.
This component is primarily designed to work in conjunction with an image API, providing a graphical interface to specify crop values, which are then forwarded to the API for server-side cropping.
The ImageUpload component accepts the following props:
title: (optional) The title displayed in the modal of the component.savedImageUrl: (optional) The source URL of the saved image, which is previewed inside the trigger button of the modal. If provided, the component also starts with this image pre-loaded.savedCrop: (optional) The saved crop settings from a previous session. If provided, the cropper initializes with this selection.aspectRatio: (required) The desired aspect ratio for the uploaded image. It accepts ‘1:1’, ‘16:9’, or ‘32:9’.onSave: (optional) A callback function that gets triggered when the user confirms the crop area by hitting save. This function receives an object that includes the crop details and the uploaded image.isLoading: (optional) A boolean that, when true, displays a loading spinner inside the modal trigger button.
The aspectRatio prop defines the desired aspect ratio for the uploaded image. It is a required prop and accepts three possible values: '1:1', '16:9', and '32:9'.
You need to pass the aspectRatio prop using the ImageUploadAspectRatio enum exported by the ImageUpload component. Here is an example:
import { ImageUpload, ImageUploadAspectRatio } from "@caspeco/casper-ui-library";
export default function Demo() { return ( <ImageUpload title="Upload Image" aspectRatio={ImageUploadAspectRatio.OneByOne} onSave={console.log}
/* * * * Extra space to make room for the demo * * * * * * * * */ /> );}When the onSave callback is triggered, it returns an ImageData object. The ImageData type is also exported by the ImageUpload component:
type ImageData = { crop: Crop, file: { imageFilename: string, imageUploadData: string, },};
type Crop = { left: number, top: number, width: number, height: number,};The canvas previews the uploaded image, constraining its size according to the modal’s dimensions if needed. The returned crop values from the onSave callback correspond to the full size of the uploaded image, not the constrained preview.