Johni Deep
Johni Deep

Reputation: 563

Convert Base64 encoded String into Image file back on Java Server

I want to send Image from Android to Server. I decoded image into Base64 String and send it to the server. I use following code to convert Image to String

    Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.icon);  
    ByteArrayOutputStream bao = new ByteArrayOutputStream();  
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bao);  
    byte [] byteArray = bao.toByteArray();  
    String imageToString=Base64.encodeToString(byteArray,Base64.DEFAULT);  
    return imageToString; 

Now i am unable to convert it back to Image on server side. I tried this

   byte[] imageBytes=Base64.decode(imageString);  
   InputStream in =  new ByteArrayInputStream(imageBytes);  
   BufferedImage bImageFromConvert = ImageIO.read(in);  
   ImageIO.write(bImageFromConvert, "jpg", new File("D:\\myImage.jpg")); 

i am getting Bogus Huffman table definition exception and sometime im = null exception. plz tell me what mistake i am making

Edit: Error Message javax.imageio.IIOException: Bogus Huffman table definition at this line

  BufferedImage bImageFromConvert = ImageIO.read(in); 

Upvotes: 2

Views: 9675

Answers (2)

frost
frost

Reputation: 64

Try this

        byte[] imageBytes=Base64.decode(imageString,Base64.NO_WRAP);
        InputStream in = new ByteArrayInputStream(imageBytes);
        Bitmap b = BitmapFactory.decodeStream(in);

Upvotes: 2

Shivan Dragon
Shivan Dragon

Reputation: 15219

Well there might be multiple issues here. The first one I think is the fact that you convert the image bytes to String (encoding them with whatever default encoding you Android environment has) and the decoding that String back to bytes without ensuring that you use the same text encoding (and thus get the same bytes).

Why not send the bytes directly? Or better yet just upload the file directly via HTTP multi-part form. There's a tutorial on this here:

http://flo.dauran.com/194-android-uploader-une-image-sur-une-serveur-web/

(it's in french, but there's detailed code examples)

Upvotes: 1

Related Questions