callstack / react-native-image-editor

A library providing an API for cropping images from the web and the local file system.
MIT License
376 stars 118 forks source link

Wrong crop of image #54

Closed ghost closed 6 months ago

ghost commented 4 years ago

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

weymanator commented 4 years ago

@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.

MariaPereiraMindera commented 4 years ago

I have the same problem. How I solve that?

jakubgrzelak commented 4 years ago

The same

MariaPereira1 commented 3 years ago

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)

rajneshbiz commented 3 years ago

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.

krlol commented 3 years ago

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 },
          };
        }
rubydeve commented 3 years ago
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)
AndriiHnedko commented 2 years ago

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.

ermankuruoglu commented 2 years ago

@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.

limouren commented 2 years ago

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.

dmtuan97 commented 8 months ago

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~

olegmilan commented 7 months ago

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..

retyui commented 6 months ago

It should be fixed in the 4.0.0 release.

sajal-flymeout commented 1 day ago

Still facing same issue