user1203692
user1203692

Reputation: 21

How to convert String to Image (Java)

I have an issue about my Application in detail. - I have a java servlet receive data from mms gateway (MM7 protocol) I get inputstream (image content , message content ) convert to string

ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
//String orgin = new String(byteArrayOutputStream.toByteArray(),"UTF-8");
String orgin = Streams.asString(request.getInputStream(), "ISO-8859-1");

Then I substring orgin for image content and convert to base64 and save to image file but string that I convert to base64 can not save to image because this error

not a jpeg file 

I print out string base64 does not start with /9j that mean not jpg format

please suggest or give an example for me

Best reqard

lieang noob noob

sorry for my english :)

Upvotes: 1

Views: 24931

Answers (4)

Bhaskara Arani
Bhaskara Arani

Reputation: 1657

Use the below code the for the String to Image here "origin" is a String

import org.apache.commons.codec.binary.Base64;


byte[] imgByteArray = Base64.decodeBase64(origin);
FileOutputStream imgOutFile = new FileOutputStream("C:\\Workspaces\\String_To_Image.jpg");
imgOutFile.write(imgByteArray);
imgOutFile.close();

Upvotes: 0

Venkatesh S
Venkatesh S

Reputation: 5494

Encoding of image is very simple.

Encoding Source:

    Bitmap bm = BitmapFactory.decodeFile(picturePath);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            bm.compress(Bitmap.CompressFormat.JPEG, 100, baos);
            byte[] byteArray = baos.toByteArray();

            encodedImage = Base64.encodeToString(byteArray, Base64.DEFAULT);

    ImageView imageView = (ImageView) findViewById(R.id.imageView1);
            imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));

Decoding Source:

    byte[] decodedString;
        decodedString = Base64.decode(picture, Base64.DEFAULT);

        imageView1.setImageBitmap( BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length));

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500385

This is at least part of your problem:

String orgin = Streams.asString(request.getInputStream(), "ISO-8859-1");

You shouldn't be converting it into a string to start with. It's binary data, right? So read it from the stream as binary data.

Now it sounds like you basically want to get separate "chunks" of that binary data - but converting the data into a string format to start with is not appropriate, unless that binary data really is encoded text.

Upvotes: 2

Related Questions