简体   繁体   English

如何从Android中的位图获取图像的原始字符串?

[英]How to get raw string of an image from Bitmap in android?

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. 我目前有一个表示照片的Bitmap对象,我想将其发布到服务器上。

Unfortunately, the server expects raw text of the jpg (like what you would see if you typed cat /path/to/jpg on linux). 不幸的是,服务器期望jpg的原始文本(就像您在Linux上键入cat /path/to/jpg所看到的一样)。

How can I convert my Bitmap into a String of this kind? 如何将我的Bitmap转换为这种String

I would guess that your server expects a Base64 encoded image string, not just the string from cat /path/to/jpg . 我猜想您的服务器需要一个Base64编码的图像字符串,而不仅仅是cat /path/to/jpg的字符串。

To get a Base64 string, you could use: 要获取Base64字符串,可以使用:

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引用了-

Bitmap bitmapImage = //your code for getting Bitmap

Now create a ByteOutputStream 现在创建一个ByteOutputStream

ByteArrayOutputStream byteOutptuStream = new ByteArrayOutputStream();  
bitmapImage.compress(Bitmap.CompressFormat.JPEG, 100, byteOutptuStream); 
byte[] byteArray = byteOutptuStream.toByteArray();  

Then encode the image using Base64 encoding - 然后使用Base64编码对图像进行编码-

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 - 更新:如果您想跳过Base64编码,则可以使用以下任一代码段-

String imageAsString2 = new String(byteArray, "UTF-8"); 
String imageAsString3 = new String(byteArray);
String imageAsString4 = new byteArray.toString();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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