简体   繁体   中英

Base64 to image? JAVA

I am sending a binarized image from an android device to server as an encoded base64 string. However, when I decode the string and store in the.png file, it gives me an error. I place the same string in https://codebeautify.org/base64-to-image-converter and it works perfectly. I think there is an issue with my decode.

import java.util.Base64;
.
.
.
.

byte[] imageByteArray = orgIMGDataBase64.getBytes();
File imageFile = new File("image.png");
try{
   OutputStream imageWriter = new BufferedOutputStream(new FileOutputStream(imageFile));
   imageWriter.write(imageByteArray);
}catch(IOException e){
   e.printStackTrace();
}

When I use an online converter, I get a.png image even though all my image capture configs are set to.jpeg in the android device (I made my own camera app). I am a newbie in Computer Graphics so please bear with me:)

Edit: the code doesn't give an exception. The new.png file does show "an error occurred while loading the image" in vscode

Edit 2: I understood my mistake that I wasn't decoding. But decoding using java.util.Base64 gave an illegal character exception. Because this was a semester project, I was short on time and I decided to do it with python. I wrote the base64 to a textFile and converted it to image in python. I hope someone finds this useful

\\in java file
try{
    String[] commands = {"python", "Base64ToPNG.py"};
    ProcessBuilder builder = new ProcessBuilder(commands);
    //redirect the error stream to this error stream
    builder.redirectErrorStream(true);
    Process p = builder.start();
    BufferedReader reader = new BufferedReader(new 
                           InputStreamReader(p.getInputStream()));
    String lines = reader.readLine();
    while(lines != null){
       lines = reader.readLine();
    }
}catch(IOException e){
    e.printStackTrace();
}

And in Base64ToPNG.py

import base64

filehandle = open('imagedata.txt', 'r')
base64str = ""
for line in filehandle:
    base64str += line[:-1]
bytesData = bytes(base64str, 'utf-8')
imageHandle = open('image.png', 'wb')
imageHandle.write(base64.decodebytes(bytesData + b'=='))#in android, I removed the padding
imageHandle.close()

First off- why are you sending it in base 64? Base64 is a hack for when you need to send binary data over a text only channel. Unless you absolutely have to, you should not be using it. Rethink whether this is needed at all.

Secondly, you have no decode here. You're writing the data as is. Possibly you cut out the decode step, but unless you did you're writing base64 as a png. You need to convert it back to binary first.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM