liyaodong
5/25/2016 - 6:35 AM

Crop avatar before upload to server

Crop avatar before upload to server

// import crop package
import crop from 'crop-image';

// input file onChange callback
this.upload = e => {
  const files = e.target.files;
  if (files && files[0]) {
    const image = new Image();

    image.onload = () => {
      // crop img first
      const { width, height } = image;
      const isHoriz = width > height;
      const minMax = isHoriz ? [height, width] : [width, height];
      const distance = minMax[1] - minMax[0];
      const CROP_SIZE = minMax[1] > 500 ? 500 : minMax[1];
      const blob = crop(image, isHoriz ? distance : 0, isHoriz ? 0 : distance, minMax[0], minMax[0], CROP_SIZE, CROP_SIZE);

      // send blob to server
      const f = new FormData();
      f.append('user[avatar]', blob, files[0].name);
      uploadAvatar(f)
        .done(user => {
          this.props.dispatch(showSuccessMessage('头像更新成功'));
        })
        .fail(xhr => showXHRError(xhr, this.props.dispatch));
    };
    image.src = window.URL.createObjectURL(files[0]);
  }
};

// read full commit
// https://github.com/GeekPark/gpk_account/pull/117/commits/1ad250a25e52bc2bd085eebf1177b170ecd44aae