您能帮我如何通过react-image-crop模块获取输出(裁剪图像的来源)吗? 上传组件如下:
class MyUpload extends Component {
constructor() {
super();
this.state = {
src: 'source-to-image',
crop: {
x: 10,
y: 10,
aspect: 9 / 16,
width: 100
}
}
}
onCropComplete = (crop, pixelCrop) => {
this.setState({
crop
})
};
render() {
return (
<ReactCrop
src={this.state.src}
onComplete={this.onCropComplete}
/>
);
} }
onCropComplete方法仅返回裁剪图像的坐标,宽度和高度,而不返回源。我想获取Blob文件。
编辑(有效的解决方案-感谢MosèRaguzzini的回复):
如果有人遇到类似问题,请在组件中的教程中调用 getCropptedImg 函数,并从返回的Blob对象创建url,如下所示:
getCroppedImg(this.state.image, pixelCrop, 'preview.jpg')
.then((res) => {
const blobUrl = URL.createObjectURL(res);
console.log(blobUrl); // it returns cropped image in this shape of url: "blob:http://something..."
})
答案 0 :(得分:1)
react-image-crop并不用于产生斑点,而仅用于内联裁剪图像。可能您需要类似https://foliotek.github.io/Croppie/
的东西更新: 检查“如何在客户端上显示作物”部分。在底部 https://www.npmjs.com/package/react-image-crop,该Blob可用作隐藏功能
/**
* @param {File} image - Image File Object
* @param {Object} pixelCrop - pixelCrop Object provided by react-image-crop
* @param {String} fileName - Name of the returned file in Promise
*/
function getCroppedImg(image, pixelCrop, fileName) {
const canvas = document.createElement('canvas');
canvas.width = pixelCrop.width;
canvas.height = pixelCrop.height;
const ctx = canvas.getContext('2d');
ctx.drawImage(
image,
pixelCrop.x,
pixelCrop.y,
pixelCrop.width,
pixelCrop.height,
0,
0,
pixelCrop.width,
pixelCrop.height
);
// As Base64 string
// const base64Image = canvas.toDataURL('image/jpeg');
// As a blob
return new Promise((resolve, reject) => {
canvas.toBlob(file => {
file.name = fileName;
resolve(file);
}, 'image/jpeg');
});
}
async test() {
const croppedImg = await getCroppedImg(image, pixelCrop, returnedFileName);
}