我如何在React Native中将图像转换为字节数组

时间:2018-06-21 13:04:38

标签: react-native base64 react-native-android react-native-ios expo

所以我有一个API,该API只需要用于图像的ByteArray,我只想知道如何做到这一点,我已经使用了Expo的ImagePicker

let pickerResult = await ImagePicker.launchCameraAsync({
  allowsEditing: true,

  aspect: [4, 3],
});

并且我正在尝试将此URI转换为Base64,然后将Base64转换为ByteArray,但是图像在某处变得混乱,并且我无法获得图像的完整性,

这是我的转化

        function test(base64StringFromURL)
{
   var parts = base64StringFromURL.split(";base64,");
   var contentType = parts[0].replace("data:", "");
   var base64 = parts[1];
   var byteArray = base64ToByteArray(base64);
   //console.log("ByteARRAY "+byteArray);
   return byteArray;

}

function toDataUrl(url, callback) {
    var xhr = new XMLHttpRequest();
    xhr.onload = function() {
        var reader = new FileReader();
        reader.onloadend = function() {
            callback(reader.result);
        }
        reader.readAsDataURL(xhr.response);
    };
    xhr.open('GET', url);
    xhr.responseType = 'blob';
    xhr.send();
}

function base64ToByteArray(base64String) {
        try {            
            var base64 = require('base-64');
            var sliceSize = 1024;
            var byteCharacters = base64.decode(base64String);
            var bytesLength = byteCharacters.length;
            var slicesCount = Math.ceil(bytesLength / sliceSize);
            var byteArrays = new Array(slicesCount);

            for (var sliceIndex = 0; sliceIndex < slicesCount; ++sliceIndex) {
                var begin = sliceIndex * sliceSize;
                var end = Math.min(begin + sliceSize, bytesLength);

                var bytes = new Array(end - begin);
                for (var offset = begin, i = 0; offset < end; ++i, ++offset) {
                    bytes[i] = byteCharacters[offset].charCodeAt(0);
                }
                byteArrays[sliceIndex] = new Uint8Array(bytes);
            }
            return byteArrays;
        } catch (e) {
            console.log("Couldn't convert to byte array: " + e);
            return undefined;
        }
    }

我不确定我在这里缺少什么,这就是我将数据发送到API的方式

     let options = {
    method: 'POST',
   body: JSON.stringify({
    CustomerId: custData.customerId,//'68c439f8-c474-46a9-84b8-79fe31168563',
    CustomerName: custData.customerName,
    UserId:'user2',
    VehicleCompanyName:custData.vehicleCompanyName,
    VehicleModelType:custData.vehicleModelType,
    VehicleNumber:custData.vehicleNumber,
    CustomerImage:bytearray,
    Location:'',
    CustomerImageType:'jpg'
  }),
  headers: new Headers({
            'Content-Type': 'application/json', // <-- Specifying the Content-Type
  }),
  };

  return fetch(apiUrl, options);

byteArray变量不过是方法test()的返回变量

任何输入都会真正有帮助,或者任何其他方法也会帮助我。

0 个答案:

没有答案