React Native:在Android上裁剪图像

时间:2017-02-06 14:31:03

标签: android react-native base64 crop android-bitmap

以下功能适用于iOS,但不适用于Android。我想在两个平台上实现相同的结果。

基于this official documentation,原因在ImageStore Android包中缺少react-native

import {
  ImageEditor,
  ImageStore
} from 'react-native';

react-native for Android中裁剪图像(如方形)的替代方法是什么?

cropImage(base64ImageData) {
    return new Promise((resolve, reject)=>{
      ImageStore.addImageFromBase64(
        base64ImageData,
        (photoURI)=>{
          ImageEditor.cropImage(
            photoURI,
            {offset:{x:0,y:(1920-1080)/2},size:{width:1080, height:1080}},
            (croppedURI)=>{
              ImageStore.getBase64ForTag(
                croppedURI,
                (base64CroppedData)=>{
                  ImageStore.removeImageForTag(croppedURI);
                  resolve(base64CroppedData);
                },
                (err)=>{
                  reject(err);
                }
              );
              ImageStore.removeImageForTag(photoURI);
            },
            (err)=>{
              reject(err);
            }
          );
        },
        (err)=>{
          reject(err);
        }
      );
    });
  }

更新

有一个项目https://github.com/seancunningham/react-native-image-store-ext(最后一次提交2016年10月28日),但只有implements

  • Boolean removeImageForTag(String file_uri)

其余的遗失:

  • static addImageFromBase64(base64ImageData,success,failure)

我的初步解决方案:

  private static final String IMAGE_STORAGE_URL_SCHEME = "rct-image-store";

  @ReactMethod
  public void addImageFromBase64(String base64_image_data, Callback successCallback, Callback failureCallback){
    String imageStorageDir = this.reactContext.getApplicationContext().getFilesDir()+"/"+IMAGE_STORAGE_URL_SCHEME+"/";
    byte[] buffer = new byte[BUFFER_SIZE];
    String file_uri = imageStorageDir+"1";
    try {
      File f = new File(imageStorageDir);
      if(!f.exists()) {
        f.mkdir();
      }
      FileOutputStream fos = new FileOutputStream(file_uri, false);
      byte[] decodedImage = Base64.decode(base64_image_data, Base64.DEFAULT);
      fos.write(decodedImage);
      fos.close();
      successCallback.invoke("file://"+file_uri);
    } catch (IOException ioe) {
      failureCallback.invoke("Failed to add image from base64String"+ioe.getMessage());
    } catch (Exception e) {
      failureCallback.invoke("Failed to add image from base64String"+e.getMessage());
    }
  }
  • static getBase64ForTag(uri,success,failure)

this file ImageStorageManager.java

中实施
  • static hasImageForTag(uri,callback)

1 个答案:

答案 0 :(得分:0)

问题必须是偏移量+大小之和大于接受的高度,然后尝试:

{offset:{x:0,y:(1920-1080)/2},size:{width:1080, height:1080 - (1920-1080)/2)}},

看看它是否有效,如果可以,只需尝试调整您的size.height大小,然后看看哪种方法对您有效! :)