I am making an app where people can take and upload photos. I currently have a Bitmap
object that represents the photo, and I'd like to post this to a server.
Unfortunately, the server expects raw text of the jpg (like what you would see if you typed cat /path/to/jpg
on linux).
How can I convert my Bitmap
into a String
of this kind?
I would guess that your server expects a Base64 encoded image string, not just the string from cat /path/to/jpg
.
To get a Base64 string, you could use:
ByteArrayOutputStream out = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out); // '100' is quality
byte[] byteArray = out.toByteArray();
String encoded = Base64.encodeToString(byteArray, Base64.DEFAULT);
Assuming you have your Bitmap image referenced by bitmapImage
-
Bitmap bitmapImage = //your code for getting Bitmap
Now create a ByteOutputStream
ByteArrayOutputStream byteOutptuStream = new ByteArrayOutputStream();
bitmapImage.compress(Bitmap.CompressFormat.JPEG, 100, byteOutptuStream);
byte[] byteArray = byteOutptuStream.toByteArray();
Then encode the image using Base64 encoding -
String imageAsString = Base64.encodeToString(byteArray, Base64.DEFAULT);
Update: If you want to skip the Base64
encoding then you can use the either of code snippet -
String imageAsString2 = new String(byteArray, "UTF-8");
String imageAsString3 = new String(byteArray);
String imageAsString4 = new byteArray.toString();
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.