react-native-image-editor icon indicating copy to clipboard operation
react-native-image-editor copied to clipboard

Wrong crop of image

Open YanisKondakov opened this issue 5 years ago • 10 comments

Bug

Wrong crop output.

Environment info

React native info output:

 System:
    OS: Windows 10 10.0.18362
    CPU: (8) x64 Intel(R) Core(TM) i7-9700 CPU @ 3.00GHz
    Memory: 16.44 GB / 31.87 GB
  Binaries:
    Node: 12.4.0 - C:\Program Files\nodejs\node.EXE
    Yarn: 1.17.3 - C:\Program Files (x86)\Yarn\bin\yarn.CMD
    npm: 6.9.0 - C:\Program Files\nodejs\npm.CMD
  SDKs:
    Android SDK:
      API Levels: 28, 29
      Build Tools: 28.0.3
      System Images: android-22 | Google APIs Intel x86 Atom, android-23 | Google APIs Intel x86 Atom, android-28 | Intel x86 Atom_64, android-28 | Google APIs Intel x86 Atom, android-28 | Google Play Intel x86 Atom, android-29 | Google APIs Intel x86 Ato
m, android-29 | Google APIs Intel x86 Atom_64
  IDEs:
    Android Studio: Version  3.4.0.0 AI-183.6156.11.34.5692245
  npmPackages:
    react: 16.9.0 => 16.9.0
    react-native: 0.61.5 => 0.61.5

Library version: image

Steps To Reproduce

I have image with sizes: Original Image image Original sizes: image

Then i prepare a crop data to crop image image

How i prepare this data: image

As you can see, target width(1 on image above) of image is smaller than original width(2 on image above) and target height is equal to original height.

Describe what you expected to happen:

So, what i expected after crop: image

What i actually have after crop: image

YanisKondakov avatar Dec 16 '19 12:12 YanisKondakov

@YanisKondakov. That issue is caused by the device scale factor, for example you run your app in an iPhone X that has the scale factor equals to 3, if you have and image with the dimensions w = 200, h = 200, the device represents those dimensions as w = 600, h = 600;

Check this link for a better answer.

weymanator avatar Jan 18 '20 00:01 weymanator

I have the same problem. How I solve that?

MariaPereiraMindera avatar Aug 24 '20 15:08 MariaPereiraMindera

The same

jakubgrzelak avatar Sep 03 '20 11:09 jakubgrzelak

I found a solution

export default function cropImage(imageURI, imageWidth, imageHeight, x, y) {
  let screenWidth = PixelRatio.getPixelSizeForLayoutSize(
    Dimensions.get('window').width,
  );
  let screenHeight = PixelRatio.getPixelSizeForLayoutSize(
    Dimensions.get('window').height,
  );

  let scaleFactor = imageHeight / screenHeight;

  x *= scaleFactor;
  y *= scaleFactor;
  screenWidth *= scaleFactor;
  screenHeight *= scaleFactor;

  let newSize = 8 * scaleFactor;

  let offsetX = (imageWidth - screenWidth) / 2 + (x - newSize / 2);
  let offsetY = y - newSize / 2;

  const cropData = {
    offset: {
      x: offsetX,
      y: offsetY,
    },
    size: {
      width: newSize,
      height: newSize,
    },
  };

  return ImageEditor.cropImage(imageURI, cropData);
}

imageHeight: PixelRatio.getPixelSizeForLayoutSize(imageHeight) imageWidth: PixelRatio.getPixelSizeForLayoutSize(imageWidth)

MariaPereira1 avatar Sep 15 '20 15:09 MariaPereira1

Hi I want only selected rectangular area to be cropped but with below code getting warning only

Error: rectangle is outside the image

Or If I set dummy x and y then error gone but proper cropped image not getting

I have implemented RNCamera then cropping the captured image

Emulator camera image

Screenshot_1609160761

Code

takePicture = async () => {
    if (this.camera) {
      const options = {
        quality: 0.5,
        base64: true,
      };
      this.camera
        .takePictureAsync(options)
        .then((capturedImg) => {
          // 2a) Extract a reference to the captured image,
          //    along with its natural dimensions
          const {uri, width, height} = capturedImg;
          console.log(capturedImg);
          console.log('Capture uri:', uri);
          console.log('Capture width heigth:', width, height);
          console.log('X: ', this.state.captureBoxXAxis);
          console.log('Y: ', this.state.captureBoxYAxis);
         
          let imageHeight = PixelRatio.getPixelSizeForLayoutSize(height);
          let imageWidth = PixelRatio.getPixelSizeForLayoutSize(width);
          cropImage(uri, imageWidth, imageHeight, this.state.captureBoxXAxis,this.state.captureBoxYAxis).then((url) => {

            console.log('Cropped image uri', url);
              this.setState({ image: url });
          });
     
        })
        .catch((error) => {
          console.log('Could not capture image.', error);
        });
    }
  };
}

function cropImage(imageURI, imageWidth, imageHeight, x, y) {
  let screenWidth = PixelRatio.getPixelSizeForLayoutSize(
    Dimensions.get('window').width,
  );
  let screenHeight = PixelRatio.getPixelSizeForLayoutSize(
    Dimensions.get('window').height,
  );

  let scaleFactor = imageHeight / screenHeight;

  x *= scaleFactor;
  y *= scaleFactor;
  screenWidth *= scaleFactor;
  screenHeight *= scaleFactor;

  let newSize = 8 * scaleFactor;

  let offsetX = (imageWidth - screenWidth) / 2 + (x - newSize / 2);
  let offsetY = y - newSize / 2;

  const cropData = {
    offset: {
      x: offsetX,
      y: offsetY,
    },
    size: {
      width: newSize,
      height: newSize,
    },
  };

  return ImageEditor.cropImage(imageURI, cropData);
}

  handleLayoutChange() {

    this.myComponent.measure( (fx, fy, width, height, px, py) => {

      this.setState({
        captureBoxXAxis: px,
        captureBoxYAxis: py,
        captureBoxWidth: width,
        captureBoxHeight: height,
      });

    })        
  }

 return (
        <SafeAreaView style={styles.safeAreaContainer}>
          <RNCamera
            ref={(ref) => {
              this.camera = ref;
            }}
            style={styles.cameraStyle}
            type={this.state.type}
            flashMode={this.state.flash}
            androidCameraPermissionOptions={{
              title: 'Permission to use camera',
              message: 'We need your permission to use your camera',
              buttonPositive: 'Ok',
              buttonNegative: 'Cancel',
            }}
            androidRecordAudioPermissionOptions={{
              title: 'Permission to use audio recording',
              message: 'We need your permission to use your audio',
              buttonPositive: 'Ok',
              buttonNegative: 'Cancel',
            }}>
            <View style={styles.mainContainer}>
              <View
                style={[
                  { height: maskTopRowHeight },
                  styles.maskRow,
                  styles.maskFrame,
                ]}>
                <Text style={styles.titleLabel}>Back Image</Text>
              </View>
              <View style={[styles.maskCenter]}>
                <View style={[{ width: maskColWidth }, styles.maskFrame]} />
                <View
                ref={view => { this.myComponent = view; }}
                  style={styles.boxContainer}
                  onLayout={(event) => this.handleLayoutChange(event)} >
                  <Text style={styles.topLabel}>Top of Card</Text>
                  <Text style={styles.bottomLabel}>Bottom of Card</Text>
                </View>
                <View style={[{ width: maskColWidth }, styles.maskFrame]} />
              </View>
              <View
                style={[
                  { height: maskBottomRowHeight },
                  styles.maskRow,
                  styles.maskFrame,
                ]}>
                <View style={styles.actionContainer}>
                  <TouchableOpacity
                    onPress={this.takePicture.bind(this)}
                    style={styles.captureContainer}>
                    <Image
                      source={require('../images/circle-camera.png')}
                      size={26}
                      style={[styles.clickButton]}
                    />
                  </TouchableOpacity>
                  <TouchableOpacity
                    style={styles.flashContainer}
                    onPress={this.toggleFlash.bind(this)}>
                    <Image
                      source={
                        this.state.flash === 'on'
                          ? require('../images/flash-on.png')
                          : require('../images/flash-off.png')
                      }
                      size={26}
                      style={[styles.flashButton]}
                    />
                  </TouchableOpacity>
                </View>
              </View>
            </View>
          </RNCamera>
        </SafeAreaView>
      );

Please help @MariaMindera.

rajneshbiz avatar Dec 28 '20 13:12 rajneshbiz

Is there any update on this? I have the same problem on android manily. If I multiply the coordinates and image size by the device scale I get to work on some devices, but still get wrong cropping in other ones.

if (Platform.OS === 'android') {
          const xFactor = Dimensions.get('screen').scale;
          const yFactor = Dimensions.get('screen').scale;
          imageWidth = imageWidth * xFactor;
          imageHeight = imageHeight * yFactor;
          cropData = {
            offset: { x: cropOffset.x * xFactor, y: cropOffset.y * yFactor },
            size: { width: imageWidth, height: imageHeight },
          };
        }

krlol avatar Jan 05 '21 15:01 krlol

handleLayoutChange(event) {
	    this.myComponent.measure( (fx, fy, width, height, px, py) => {
		    this.setState({
			captureBoxXAxis: px,
		        captureBoxYAxis: py,
		        captureBoxWidth: width,
		        captureBoxHeight: height,
	         });
	    })        
    }
const width = Dimensions.get('window').width
const height = Dimensions.get('window').height
const cropData = {
   offset: {x: ((this.state.captureBoxXAxis)/width)*imageWidth, y:((this.state.captureBoxYAxis)/height)*imageHeight},
   size: {width: ((this.state.captureBoxWidth)/width)*imageWidth, height: this.state.captureBoxHeight/height*imageHeight},
};
ImageEditor.cropImage(imageURI, cropData)

rubydeve avatar Aug 18 '21 11:08 rubydeve

Before call ImageEditor.cropImage you need to prepare the target image. Use react-native-image-resizer for just resize the image by a few pixels. As a result this will create a new image with the correct metadata.

AndriiHnedko avatar Nov 04 '21 11:11 AndriiHnedko

@AndriiHnedko Thank you so much. I tried what you suggest and it worked! I think this issue is not related about device pixel ratio, size or something, it is related about image metadata. You guys if you try to create a new image with new metadata with react-native-image-resizer library, you'll see this library is working like a charm.

ermankuruoglu avatar Jan 16 '22 12:01 ermankuruoglu

For me, on certain platform (in my case android) and for certain images, the image width and height reported by Image.onLoad callback is different from the actual size of the image file. A work around is to read the actual image size using Image.getSize and use it to calculate the actual coordinates to crop.

limouren avatar Mar 15 '22 19:03 limouren

Before call ImageEditor.cropImage you need to prepare the target image. Use react-native-image-resizer for just resize the image by a few pixels. As a result this will create a new image with the correct metadata.

Work like a charm~

dmtuan97 avatar Jan 11 '24 07:01 dmtuan97

Before call ImageEditor.cropImage you need to prepare the target image. Use react-native-image-resizer for just resize the image by a few pixels. As a result this will create a new image with the correct metadata.

Your workaround did work. Thanks. Unfortunately we have to perform an extra step here, but it is what it is..

olegmilan avatar Feb 01 '24 13:02 olegmilan

It should be fixed in the 4.0.0 release.

retyui avatar Feb 25 '24 13:02 retyui