簡體   English   中英

裁剪后如何將裁剪后的圖像作為表單數據在反應中獲取

[英]How to get cropped image after crop as a form data in react

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() function 我正在使用e.target.files[0]獲取實際的圖像文件。

但是,當我在makeClientCrop() function 中打印croppedImageUrl時裁剪后,我得到了一張假圖像 url。

裁剪后如何獲得實際的圖像文件,就像我在onSelectChange() function while console.log()中一樣?

你可以做的是將blob文件保存在state中的canvas.toBlob中getCroppedImg function中,然后在保存文件時將其轉換為a。

  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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM