繁体   English   中英

React Native Android]调整图片大小并上传到后端服务器

[英]React Native Android] Resize image and upload to backend server

用设备拍摄的照片很大。 我想将它们调整大小(缩放)到更合理的大小(小于800x800)后,将它们上传到后端服务器。 我希望使用ImageEditor模块的coprImage()函数,但是以较大的图像运行它会导致OutOfMemory异常。 我假设由于模块尝试解码大图像并将其存储在内存中,因此应用程序崩溃了。

我需要的是以下内容:

输入项

{
  width: 3100,
  height: 2500,
  uri: content://android/1 (some location in Android device)
}

产量

{
  width: 800,
  height: 650,
  uri: content://android/1/resized (some location in Android device)
}

然后,我可以抓住这个uri将图片发送到我的后端服务器,然后从设备中删除已调整大小的照片。

我假设必须编写NativeModule以便可以调整图像的大小,而无需将大的已解码图像加载到内存中。 React Native的Image组件在渲染它们之前使用Fresco来处理大小调整,但是我认为它没有提供调整图像大小并将其临时保存在fs中的方法。

任何帮助,将不胜感激。

参考文献:

  1. https://developer.android.com/training/displaying-bitmaps/load-bitmap.html
  2. http://frescolib.org/docs/resizing-rotating.html
  3. https://facebook.github.io/react-native/docs/images.html
  4. Android中具有内存效率的图像调整大小

在我的应用中,我使用react-native-image-picker效果很好。

如果您不想使用它,请查看此函数源,以了解如何调整大小。 干杯。

您是否尝试过react-native-image-resizer 对我来说,它工作得很好,我将它与react-native-camera一起使用 ,它看起来像这样:

  fromCamera() {
    let newWidth = 800;
    let newHeight = 650;
    this.refs.camera.capture()
    .then((data) => {
      ImageResizer.createResizedImage(data.path, newWidth, newHeight, 'JPEG', 100, rotation)
      .then(uri => {
        // send to backend
      }
    })
  }

原始图像通过uri: data.path保存在设备上,因此内存没有问题。

世博库有一个图像操纵器,可以调整大小以及更多功能:

import { ImageManipulator } from 'expo';

...

const manipResult = await ImageManipulator.manipulate(
    imageUri,
    [{ resize: { width: 640, height: 480 } }],
    { format: 'jpg' }
);

manipResult将返回具有新uri,宽度和高度的对象。

在这里找到: https : //docs.expo.io/versions/latest/sdk/imagemanipulator.html

让我们看看这个 它将为您提供有关调整大小并上载到后端服务器的问题的详细说明。

如果要发送Base64字符串,可以检查以下代码

如何安装并与android链接,请检查此链接

https://github.com/TBouder/react-native-asset-resize-to-base64

//此代码仅用于调整大小并推入数组

let images = [];
NativeModules.RNAssetResizeToBase64.assetToResizedBase64(
            response.uri,
            newWidth,
            newHeight,
            (err, base64) => {
              if (base64 != null) {
                const imgSources = { uri: base64 };
                this.setState({
                  image: this.state.image.concat(imgSources)
                });
                 this.state.image.map((item, index) => {
                  images.push(item);
                });
                if (err) {
                  console.log(err, "errors");
                }
              }
            }
          );

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM