Git Product home page Git Product logo

Comments (13)

AndriiHnedko avatar AndriiHnedko commented on July 24, 2024 7

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.

from react-native-image-editor.

ermankuruoglu avatar ermankuruoglu commented on July 24, 2024 3

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

from react-native-image-editor.

weymanator avatar weymanator commented on July 24, 2024

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

from react-native-image-editor.

MariaPereiraMindera avatar MariaPereiraMindera commented on July 24, 2024

I have the same problem. How I solve that?

from react-native-image-editor.

jakubgrzelak avatar jakubgrzelak commented on July 24, 2024

The same

from react-native-image-editor.

MariaPereira1 avatar MariaPereira1 commented on July 24, 2024

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)

from react-native-image-editor.

rajneshbiz avatar rajneshbiz commented on July 24, 2024

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.

from react-native-image-editor.

krlol avatar krlol commented on July 24, 2024

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

from react-native-image-editor.

rubydeve avatar rubydeve commented on July 24, 2024
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)

from react-native-image-editor.

limouren avatar limouren commented on July 24, 2024

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.

from react-native-image-editor.

dmtuan97 avatar dmtuan97 commented on July 24, 2024

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~

from react-native-image-editor.

olegmilan avatar olegmilan commented on July 24, 2024

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

from react-native-image-editor.

retyui avatar retyui commented on July 24, 2024

It should be fixed in the 4.0.0 release.

from react-native-image-editor.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.