Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Taking square photo with react native camera

By default the react-native-camera takes photos in standard aspect ratio of the phone and outputs them in Base64 png, if the Camera.constants.CaptureTarget.memory target is set.

I am looking for a way to create square photos - either directly using the camera, or by converting the captured imagedata. Not sure if something like that is possible with React Native, or I should go entirely for native code instead.

The aspect prop changes only how the camera image is displayed in the viewfinder.

Here is my code:

<Camera
  ref={(cam) => {
    this.cam = cam;
  }}
  captureAudio={false}
  captureTarget={Camera.constants.CaptureTarget.memory}
  aspect={Camera.constants.Aspect.fill}>
</Camera>;

async takePicture() {
  var imagedata;
  try {
    var imagedata = await this.cam.capture();// Base64 png, not square
  } catch (err) {
    throw err;
  }
  return imagedata;
}
like image 778
Peter G. Avatar asked Jan 11 '17 15:01

Peter G.


1 Answers

Use the getSize method on the Image and pass the data to the cropImage method of ImageEditor.

Looking at the cropData object, you can see that I pass the width of the image as the value for both the width and the height, creating a perfect square image.

Offsetting the Y axis is necessary so that the center of the image is cropped, rather than the top. Dividing the height in half, and then subtracting half of the size of the image from that number ((h/2) - (w/2)), should ensure that you're always cropping from the center of the image, no matter what device you're using.

Image.getSize(originalImage, (w, h) => {
  const cropData = {
    offset: {
      x: 0,
      y: h / 2 - w / 2,
    },
    size: {
      width: w,
      height: w,
    },
  };
  ImageEditor.cropImage(
    originalImage,
    cropData,
    successURI => {
      // successURI contains your newly cropped image
    },
    error => {
      console.log(error);
    },
  );
});
like image 70
Jeremy Avatar answered Oct 01 '22 00:10

Jeremy