Tanner Summers
Tanner Summers

Reputation: 663

Sending Images via JSON using base64 Encoding

I am testing out if it is possible to send a JSON file with a image or two. Currently, I have the images converted into bytes and I use

Base64.encodeToString(temp_arr, Base64.NO_WRAP);

(this is Androids base64 class, and I have to use .NO_WRAP feature to make it work after reading other stack overflow pages)

to convert it to a string. At this point, I pass that string object into my JSON file (Using GSON library) and add the string go it. This data will be sent to a PHP page.

I have test converting the bytes into base64 and saving to a text file, copying that text file into my php page, running it through my php page using

 base64_decode($);

and that is able to properly recreate the image just fine (sha hashes match). So now I needed to test it sending it over a network and using json. Is the only difference is that base64 string is put int other json file rather then a text file, the json is sent to php, i grab the data and decode it in PHP.

now the problem is the image is corrupt, looking at both files in a hex editor, the first 20 lines or so in the hex editor match fine, but after that it does not match. Oddly enough the very end of the files have same data except the uploaded copy has extra characters making it larger in size.

So my problem is trying to find out, can it be GSON (JSON) causing the problem or something else, and if so, what can I do about it.

Sadly, the way my work is, my boss needs the data (json with text, data and etc) to be sent at same time, to same php page with the images, this is why I am sending the images via json.

Upvotes: 0

Views: 8506

Answers (2)

Tanner Summers
Tanner Summers

Reputation: 663

I believe I found my solution, problem was the Base64.encodeToString() would encode the images bytes to characters that included "+", where on the PHP side, the data would be send except all the "+" became spaces. I just had to replace all spaces with the + and it worked.

Upvotes: 0

Rathod Vijay
Rathod Vijay

Reputation: 417

Try this work for me,convert image into base64

 public static String getStringImage(Bitmap bmp)
    {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.JPEG, 60, baos);
        byte[] imageBytes = baos.toByteArray();
        String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
        Log.e("SignUp", "Image Decode : " + encodedImage);
        String asa = encodedImage;
        return encodedImage;
    }

//pass bitmap image and return string of base64

Upvotes: 1

Related Questions