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

dy1byipe  于 2023-05-18  发布在  React
关注(0)|答案(1)|浏览(233)

所以我有一个API,它只需要ByteArray的图像,我只是想知道如何做到这一点,我已经使用世博会的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()的返回变量
任何输入都将是非常有帮助的,或者任何其他方法也将帮助我。

ctehm74n

ctehm74n1#

用这个
beatgammit/base64-js

import base64 from "base64-js";

base64.toByteArray(base64data)

相关问题