【问题标题】:Taking square photo with react native camera使用 React Native 相机拍摄方形照片
【发布时间】:2017-01-11 15:24:27
【问题描述】:

如果设置了Camera.constants.CaptureTarget.memory 目标,默认情况下react-native-camera 以手机的标准纵横比拍摄照片并以Base64 png 输出。

我正在寻找一种方法来创建 方形 照片 - 直接使用相机,或者通过转换捕获的 imagedata。不确定 React Native 是否可以实现类似的功能,或者我应该完全使用原生代码。

aspect 属性仅更改相机图像在取景器中的显示方式。

这是我的代码:

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

【问题讨论】:

  • 查看这个内置实用程序-ImageEditor.cropImage,我没用过,但看起来你可以用它把图像裁剪成正方形。
  • 看起来 ImageEditor 只适用于 ImageStore 中的图像。对于传递给 URI 参数的 Base64 图像,它会抛出 No suitable image URL loader found for (null) 错误。

标签: ios camera react-native base64 react-native-camera


【解决方案1】:

在Image上使用getSize方法,将数据传给ImageEditor的cropImage方法。

查看cropData对象,您可以看到我将图像的宽度作为宽度和高度的值传递,创建了一个完美的方形图像。

需要偏移 Y 轴,以便裁剪图像的中心,而不是顶部。将高度除以一半,然后从该数字中减去图像大小的一半((h/2)-(w/2)),应该确保您始终从图像的中心进行裁剪,无论您使用的是什么设备。

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

【讨论】:

  • 为什么计算总是得到图像的中心?我似乎无法理解它:(
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-05
  • 2018-12-20
相关资源
最近更新 更多