首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在react中获得裁剪后的图像作为表单数据

如何在react中获得裁剪后的图像作为表单数据
EN

Stack Overflow用户
提问于 2019-11-05 01:33:56
回答 1查看 1.8K关注 0票数 2
代码语言:javascript
复制
import React, { PureComponent } from 'react';
import ReactCrop from 'react-image-crop';
import 'react-image-crop/dist/ReactCrop.css';

class CoachDashboard extends PureComponent {
  state = {
    src: null,
    crop: {
      unit: '%',
      width: 50,
      aspect: 20 / 16,
    },
  };

  onSelectFile = e => {
    if (e.target.files && e.target.files.length > 0) {
      const reader = new FileReader();
      reader.addEventListener('load', () =>
        this.setState({ src: reader.result })
      );
      reader.readAsDataURL(e.target.files[0]);
      console.log(e.target.files[0])
    }
  };

  onImageLoaded = image => {
    this.imageRef = image;
  };

  onCropComplete = crop => {
    this.makeClientCrop(crop);
  };

  onCropChange = (crop, percentCrop) => {
    this.setState({ crop });
  };

  async makeClientCrop(crop) {
    if (this.imageRef && crop.width && crop.height) {
      const croppedImageUrl = await this.getCroppedImg(
        this.imageRef,
        crop,
        'newFile.jpeg'
      );
      console.log(croppedImageUrl)
      this.setState({ croppedImageUrl });
    }
  }

  getCroppedImg(image, crop, fileName) {
    const canvas = document.createElement('canvas');
    const scaleX = image.naturalWidth / image.width;
    const scaleY = image.naturalHeight / image.height;
    canvas.width = crop.width;
    canvas.height = crop.height;
    const ctx = canvas.getContext('2d');

  ctx.drawImage(
      image,
      crop.x * scaleX,
      crop.y * scaleY,
      crop.width * scaleX,
      crop.height * scaleY,
      0,
      0,
      crop.width,
      crop.height
    );

    return new Promise((resolve, reject) => {
      canvas.toBlob(blob => {
        if (!blob) {
          console.error('Canvas is empty');
          return;
        }
        blob.name = fileName;
        window.URL.revokeObjectURL(this.fileUrl);
        this.fileUrl = window.URL.createObjectURL(blob);
        resolve(this.fileUrl);
      }, 'image/jpeg');
    });
  }




  render() {
    const { crop, croppedImageUrl, src } = this.state;

    return (
      <div className="App">
        <br/><br/><br/><br/><br/>
        <div>
          <input type="file" onChange={this.onSelectFile} />
        </div>
        <div style={{ width:'500px' }}>
        {src && (
          <ReactCrop
            src={src}
            crop={crop}
            ruleOfThirds
            onImageLoaded={this.onImageLoaded}
            onComplete={this.onCropComplete}
            onChange={this.onCropChange}
            width= '200'
            height= '200'
          />
        )}
        </div>
        {croppedImageUrl && (
          <img alt="Crop" style={{ height:'200px' }} src={croppedImageUrl} />
        )}
      </div>
    );
  }
}


export default CoachDashboard;

在这里,我正在使用react-image-crop裁剪图像。

我必须将该图像文件发送到后台并存储到数据库中。

但是,在onSelectChange()函数中,我使用e.target.files[0]获取实际的图像文件。

但在裁剪之后,当我在makeClientCrop()函数中打印croppedImageUrl时,我得到了一个假图像url。

怎样才能在裁剪后获得实际的图像文件,就像我在console.log()中使用onSelectChange()函数一样

EN

回答 1

Stack Overflow用户

发布于 2020-03-05 14:20:28

您可以做的是将blob文件保存在getCroppedImg函数的canvas.toBlob中的状态中,然后在保存文件时将其转换为文件。

代码语言:javascript
复制
  getCroppedImg(image, crop, fileName) {
    const canvas = document.createElement('canvas');
    const scaleX = image.naturalWidth / image.width;
    const scaleY = image.naturalHeight / image.height;
    canvas.width = crop.width;
    canvas.height = crop.height;
    const ctx = canvas.getContext('2d');

  ctx.drawImage(
      image,
      crop.x * scaleX,
      crop.y * scaleY,
      crop.width * scaleX,
      crop.height * scaleY,
      0,
      0,
      crop.width,
      crop.height
    );

    return new Promise((resolve, reject) => {
      canvas.toBlob(blob => {
        if (!blob) {
          console.error('Canvas is empty');
          return;
        }
        blob.name = fileName;
        window.URL.revokeObjectURL(this.fileUrl);
        this.fileUrl = window.URL.createObjectURL(blob);
        this.setState({blobFile:blob}) // Set blob image inside the state here 
        resolve(this.fileUrl);
      }, 'image/jpeg');
    });
  }

// To save file 
onFileSave(){
const {blobFile} = this.state;
const newImage = new File([blobFile], blobFile.name, { type: blobFile.type });
let fd = new FormData();
fd.append(newImage.name, newImage);
saveImageToServer(fd);
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58698458

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档