有人能告诉我将图像(最大200KB)转换为Base64字符串的代码吗?
我需要知道如何使用android,因为我必须添加上传图像的功能到我的主应用程序中的远程服务器,将它们作为字符串放入数据库的一行.
我在谷歌和StackOverflow中搜索,但我找不到我能负担得起的简单示例,而且我找到了一些例子,但他们并没有谈到转换成字符串.然后我需要转换为字符串以通过JSON上传到我的远程服务器.
xil*_*il3 320
您可以使用Base64 Android类:
String encodedImage = Base64.encodeToString(byteArrayImage, Base64.DEFAULT);
Run Code Online (Sandbox Code Playgroud)
您必须将图像转换为字节数组.这是一个例子:
Bitmap bm = BitmapFactory.decodeFile("/path/to/image.jpg");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap object
byte[] b = baos.toByteArray();
Run Code Online (Sandbox Code Playgroud)
*更新*
如果您使用较旧的SDK库(因为您希望它可以在具有较旧版本操作系统的手机上运行),您将不会打包Base64类(因为它刚刚出现在API级别8又称2.2版本).
查看本文以获得解决方法:
http://androidcodemonkey.blogspot.com/2010/03/how-to-base64-encode-decode-android.html
Cha*_*har 99
而不是使用Bitmap
,你也可以通过琐碎的方式做到这一点InputStream
.嗯,我不确定,但我觉得它有点高效
InputStream inputStream = new FileInputStream(fileName);//You can get an inputStream using any IO API
byte[] bytes;
byte[] buffer = new byte[8192];
int bytesRead;
ByteArrayOutputStream output = new ByteArrayOutputStream();
try {
while ((bytesRead = inputStream.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
} catch (IOException e) {
e.printStackTrace();
}
bytes = output.toByteArray();
String encodedString = Base64.encodeToString(bytes, Base64.DEFAULT);
Run Code Online (Sandbox Code Playgroud)
Kotlin 中的编码和解码代码如下:
fun encode(imageUri: Uri): String {
val input = activity.getContentResolver().openInputStream(imageUri)
val image = BitmapFactory.decodeStream(input , null, null)
// Encode image to base64 string
val baos = ByteArrayOutputStream()
image.compress(Bitmap.CompressFormat.JPEG, 100, baos)
var imageBytes = baos.toByteArray()
val imageString = Base64.encodeToString(imageBytes, Base64.DEFAULT)
return imageString
}
fun decode(imageString: String) {
// Decode base64 string to image
val imageBytes = Base64.decode(imageString, Base64.DEFAULT)
val decodedImage = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.size)
imageview.setImageBitmap(decodedImage)
}
Run Code Online (Sandbox Code Playgroud)
// put the image file path into this method
public static String getFileToByte(String filePath){
Bitmap bmp = null;
ByteArrayOutputStream bos = null;
byte[] bt = null;
String encodeString = null;
try{
bmp = BitmapFactory.decodeFile(filePath);
bos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, bos);
bt = bos.toByteArray();
encodeString = Base64.encodeToString(bt, Base64.DEFAULT);
}catch (Exception e){
e.printStackTrace();
}
return encodeString;
}
Run Code Online (Sandbox Code Playgroud)