Reputation: 77
How can I crop image after uploading in react js?
Hello there, how can I crop or modify the image after uploading or before? I wanna crop it in a constant aspect ratio but I don't know how to make it. I tried to use react-easy-crop but I still don't know to implement it. anyone may help me?
import React from "react";
import { Uploader, Icon, Alert, Loader, ControlLabel } from "rsuite";
import localStorage from "../../utils/lib/local-storage";
const dataUser = localStorage().get("auth");
const previewFile = (file, callback) => {
const reader = new FileReader();
reader.onloadend = () => {
callback(reader.result);
};
reader.readAsDataURL(file);
};
const Avatar = ({
image = false,
styles = {
width: 120,
height: 120,
margin: 0,
borderRadius: "50%",
border: "1px solid #ddd"
},
label = false,
urlUpload = "/users/set-avatar"
}) => {
const [uploading, setUploading] = React.useState(false);
const [fileInfo, setFileInfo] = React.useState(image);
return (
<div style={{ marginBottom: label ? 15 : 0 }}>
{label && <ControlLabel>{label}</ControlLabel>}
<Uploader
fileListVisible={false}
listType="picture"
onUpload={file => {
setUploading(true);
previewFile(file.blobFile, value => {
setFileInfo(value);
});
}}
onSuccess={response => {
setUploading(false);
Alert.success("Uploaded successfully");
window.location.reload();
}}
onError={() => {
setFileInfo(null);
setUploading(false);
Alert.error("Upload failed");
}}
name="images"
action={${process.env.REACT_APP_BASE_URL}${urlUpload}}
headers={{
Authorization: "Bearer " + dataUser.token
}}
>
<button type="button" style={styles}>
{uploading && <Loader backdrop center />}
{fileInfo ? (
<img
src={fileInfo}
alt="avatar"
width="100%"
height="100%"
/>
) : (
<Icon icon="avatar" size="5x" />
)}
</button>
</Uploader>
</div>
);
};
export default Avatar;
in my code.
Upvotes: 2
Views: 530
Reputation: 2854
Put the image inside a container div of the dimensions you want the image to be cropped to. Then give the container a style of overflow: “hidden”.
Upvotes: 1