1

I am trying to convert image into byte array. Here is my code which returns base64String of that image:

 $scope.imageAdded = function (files) {
        angular.forEach(files,
            function (flowFile, i) {
                var fileReader = new FileReader();
                fileReader.onload = function (event) {
                    var uri = event.target.result;
                    $scope.imageStrings[i] = uri;
                };
                fileReader.readAsDataURL(flowFile.file);
                event.preventDefault(); //prevent file from uploading
            });
    }

Any kind of help will be appreciated

2 Answers 2

1

Try this

 $scope.base64toByteArray = function(b64Data, contentType = '', sliceSize = 512) => {
        const byteCharacters = atob(b64Data);
        const byteArrays = [];
    
        for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
          const slice = byteCharacters.slice(offset, offset + sliceSize);
    
          const byteNumbers = new Array(slice.length);
          for (let i = 0; i < slice.length; i++) {
            byteNumbers[i] = slice.charCodeAt(i);
          }
    
          const byteArray = new Uint8Array(byteNumbers);
          byteArrays.push(byteArray);
        } 
        return byteArrays;
      }
Sign up to request clarification or add additional context in comments.

Comments

1
$scope.imageAdded = async function imageAdded (flowFiles) {
    const arrayBuffer = await flowFiles[0].file.arrayBuffer()
    const uint8array = new Uint8Array(arrayBuffer)
}

3 Comments

you can thank people by accepting a answer as a accepted solution and giving them +1 (at the left side). By doing so you will let others know that this question have been answered and you got what you were looking for. it will also help others know which one is the best/correct way of solving similar issues when they found you exact same problem
yeah! whatever you are saying is absolutely right. But my reputation is less than 10 so according to the website's rule, I can't vote :(
Anyone who can ask a question can mark an answer as accepted even if you can't yet upvote. (See What does it mean to accept an answer? for information) @AliHamza

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.