Reputation: 321
In my project, There is a cropper used react-cropper package. But the result "cropData" is in base6 format. Then convert the cropped image from base64 to a file and I want to display that result image in a div.
import React, { useState } from "react";
import Cropper from "react-cropper";
import { dataUrlToFile } from "./utils";
import "./Demo.css";
import "cropperjs/dist/cropper.css";
type Props = {
LabelName?: string;
};
export const Demo = (props: Props) => {
const { LabelName } = props;
const [image, setImage] = useState("");
const [file, setFile] = useState({});
const [cropData, setCropData] = useState("#");
const [cropper, setCropper] = useState<any>();
const onChange = (e: any) => {
e.preventDefault();
console.log("e value", e);
let files;
if (e.dataTransfer) {
files = e.dataTransfer.files;
} else if (e.target) {
files = e.target.files;
}
const reader = new FileReader();
reader.onload = () => {
setImage(reader.result as any);
};
reader.readAsDataURL(files[0]);
};
const getCropData = () => {
if (typeof cropper !== "undefined") {
setCropData(cropper.getCroppedCanvas().toDataURL());
}
};
const handleUpload = async (url: string) => {
console.log("url", url);
const file = dataUrlToFile(url, "output.png");
console.log(
`We have File "${file.name}", now we can upload it wherever we want!`
);
setFile(file)
};
console.log("cropData", cropData);
return (
<div>
<div style={{ width: "100%" }}>
<input type="file" onChange={onChange} />
<br />
<div className="container">
<Cropper
style={{
height: 600,
width: 800,
margin: "0 auto",
marginTop: 25,
}}
zoomOnTouch={true}
zoomOnWheel={true}
// zoomable={true}
// zoomTo={0.5}
aspectRatio={4}
preview=".img-preview"
src={image}
viewMode={3}
minCropBoxWidth={800}
minCropBoxHeight={200}
background={false}
responsive={true}
checkOrientation={false}
onInitialized={(instance) => {
console.log("instance", instance);
setCropper(instance);
}}
guides={true}
cropBoxResizable={false}
dragMode="move"
/>
</div>
</div>
<br style={{ clear: "both" }} />
<div
className="box"
style={{ width: "50%", float: "right", height: "300px" }}
>
<h1>
<span>Crop</span>
<button style={{ float: "right" }} onClick={getCropData}>
Crop Image
</button>
</h1>
<img style={{ width: "100%" }} src={cropData} alt="cropped" />
</div>
{cropData && (
<button
style={{ float: "right" }}
onClick={() => handleUpload(cropData)}
>
Upload
</button>
)}
<h1>
Result image
</h1>
<img style={{ width: "100%" }} src=*To display image* alt="cropped" />
</div>
);
};
export default Demo;
When console the "file" then it look like this.
The file is an object so confused about how to call the "src" inside the . Please give me some suggestions to correct this situation. https://codesandbox.io/s/old-snow-fkw3l?file=/src/Demo.tsx:1240-1253
Upvotes: 0
Views: 551