Android 如何将图像转换为Base64字符串?
将图像(最大200KB)转换为Base64字符串的代码是什么 我需要知道如何使用Android,因为我必须在我的主应用程序中添加将图像上传到远程服务器的功能,将它们作为字符串放入数据库的一行中Android 如何将图像转换为Base64字符串?,android,base64,Android,Base64,将图像(最大200KB)转换为Base64字符串的代码是什么 我需要知道如何使用Android,因为我必须在我的主应用程序中添加将图像上传到远程服务器的功能,将它们作为字符串放入数据库的一行中 我在Google和Stack Overflow中搜索,但我找不到我能负担得起的简单示例,我也找到了一些示例,但它们并不是要转换成字符串。然后我需要转换成字符串,通过JSON上传到我的远程服务器。您可以使用Base64 Android类: String encodedImage = Base64.encod
我在Google和Stack Overflow中搜索,但我找不到我能负担得起的简单示例,我也找到了一些示例,但它们并不是要转换成字符串。然后我需要转换成字符串,通过JSON上传到我的远程服务器。您可以使用Base64 Android类:
String encodedImage = Base64.encodeToString(byteArrayImage, Base64.DEFAULT);
不过,您必须将图像转换为字节数组。下面是一个例子:
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();
*更新*
如果您使用的是较旧的SDK库(因为您希望它能在具有较旧版本操作系统的手机上工作),那么就不会打包Base64类(因为它刚刚在API级别8即版本2.2中发布)
查看本文以了解解决方法:
如果您需要Base64而不是JSON,请检查:它在低级别(JsonParser、JsonGenerator)和数据绑定级别都明确支持二进制数据读/写为Base64。因此,您可以只使用with byte[]属性,并自动处理编码/解码
如果这很重要的话,也非常有效。您也可以通过一个简单的
输入流来代替使用位图
。嗯,我不确定,但我觉得有点效率
InputStream inputStream = new FileInputStream(fileName); // You can get an inputStream using any I/O 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);
此代码在我的项目中运行良好:
profile_image.buildDrawingCache();
Bitmap bmap = profile_image.getDrawingCache();
String encodedImageData = getEncoded64ImageStringFromBitmap(bmap);
public String getEncoded64ImageStringFromBitmap(Bitmap bitmap) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 70, stream);
byte[] byteFormat = stream.toByteArray();
// Get the Base64 string
String imgString = Base64.encodeToString(byteFormat, Base64.NO_WRAP);
return imgString;
}
如果您在Android上执行此操作,以下是从
使用此代码:
byte[] decodedString = Base64.decode(Base64String.getBytes(), Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
下面是可以帮助您的伪代码:
public String getBase64FromFile(String path)
{
Bitmap bmp = null;
ByteArrayOutputStream baos = null;
byte[] baat = null;
String encodeString = null;
try
{
bmp = BitmapFactory.decodeFile(path);
baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
baat = baos.toByteArray();
encodeString = Base64.encodeToString(baat, Base64.DEFAULT);
}
catch (Exception e)
{
e.printStackTrace();
}
return encodeString;
}
以下是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)
}
在Android中将图像转换为Base64字符串:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.yourimage);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String imageString = Base64.encodeToString(imageBytes, Base64.DEFAULT);
对于那些正在寻找一种高效方法将图像文件转换为Base64字符串而无需先进行压缩或将文件转换为位图的用户,您可以改为
希望这有帮助 这是图像编码和解码的代码
在XML文件中
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="yyuyuyuuyuyuyu"
android:id="@+id/tv5"
/>
在Java文件中:
TextView textView5;
Bitmap bitmap;
textView5 = (TextView) findViewById(R.id.tv5);
bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.logo);
new AsyncTask<Void, Void, String>() {
@Override
protected String doInBackground(Void... voids) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 70, stream);
byte[] byteFormat = stream.toByteArray();
// Get the Base64 string
String imgString = Base64.encodeToString(byteFormat, Base64.NO_WRAP);
return imgString;
}
@Override
protected void onPostExecute(String s) {
textView5.setText(s);
}
}.execute();
TextView TextView 5;
位图;
textView5=(TextView)findViewById(R.id.tv5);
位图=BitmapFactory.decodeResource(getResources(),R.drawable.logo);
新建异步任务(){
@凌驾
受保护的字符串背景(无效…无效){
ByteArrayOutputStream=新建ByteArrayOutputStream();
压缩(bitmap.CompressFormat.JPEG,70,流);
字节[]byteFormat=stream.toByteArray();
//获取Base64字符串
字符串imgString=Base64.encodeToString(byteFormat,Base64.NO_WRAP);
返回imgString;
}
@凌驾
受保护的void onPostExecute(字符串s){
text视图5.设置文本;
}
}.execute();
我创建了一个静态函数。我认为这样更有效率
public static String file2Base64(String filePath) {
FileInputStream fis = null;
String base64String = "";
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
fis = new FileInputStream(filePath);
byte[] buffer = new byte[1024 * 100];
int count = 0;
while ((count = fis.read(buffer)) != -1) {
bos.write(buffer, 0, count);
}
fis.close();
} catch (Exception e) {
e.printStackTrace();
}
base64String = Base64.encodeToString(bos.toByteArray(), Base64.DEFAULT);
return base64String;
}
简单和容易 Kotlin版本:
fun File.toBase64(): String? {
val result: String?
inputStream().use { inputStream ->
val sourceBytes = inputStream.readBytes()
result = Base64.encodeToString(sourceBytes, Base64.DEFAULT)
}
return result
}
好的,我可以用PHP+JSON把这个字符串(encondimage)放到远程数据库列中????哪个类型必须是数据库的列?VARCHAR?使用VARCHAR,您需要指定它的大小,所以文本可能会更好。图像可以是任何大小范围…嗨,我正在测试它,但它在Base64中给了我错误。这对全班都不起作用。我使用Ctrl+shift+O来获取导入,但不获取导入。。。?如何解决它?对于我来说,在替换后正在工作:字符串encodedImage=Base64.encode(byteArrayImage,Base64.DEFAULT);By:String encodedImage=Base64.encodeToString(byteArrayImage,Base64.DEFAULT);有人意识到这个方法对文件进行了无意义的重新压缩吗??为什么投票率如此之高??钱德拉·塞哈尔的答案是最有效的。对我来说太难了,我的技能很低,我在谷歌上查了一下,找不到简单的例子。。。也许如果你能给我一些像xil3这样的代码示例,我会明白这当然更有效;只需将文件转换为其base64表示形式,并避免对图像进行毫无意义的重新压缩。此处的文件名是文件的路径还是实际的文件名???请不要忘记标记我:)谢谢。@user2247689当您试图访问文件时,显然您必须给出文件的完整路径,包括文件名。如果文件与源程序所在的路径相同,那么文件名就足够了。一个问题,“8192”在这里表示什么,是文件大小还是什么?这段代码不起作用,浪费了我很多时间来补充这个问题。虽然这段代码可以回答这个问题,提供关于此代码为什么和/或如何回答此问题的附加上下文可提高其长期价值。需要进行解释。(将分配一个大字符串并可能导致OOM崩溃)那么,在这种情况下,解决方案是什么?这正是相反的。这实际会编译吗?您遗漏了什么吗?它正在向字符串添加下一行,我们能克服这个问题吗?获取java.io.FileNotFoundException:/storage/emulated/0/1417462683.jpg(没有这样的文件或目录),即使文件路径正确
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="yyuyuyuuyuyuyu"
android:id="@+id/tv5"
/>
TextView textView5;
Bitmap bitmap;
textView5 = (TextView) findViewById(R.id.tv5);
bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.logo);
new AsyncTask<Void, Void, String>() {
@Override
protected String doInBackground(Void... voids) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 70, stream);
byte[] byteFormat = stream.toByteArray();
// Get the Base64 string
String imgString = Base64.encodeToString(byteFormat, Base64.NO_WRAP);
return imgString;
}
@Override
protected void onPostExecute(String s) {
textView5.setText(s);
}
}.execute();
public static String file2Base64(String filePath) {
FileInputStream fis = null;
String base64String = "";
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
fis = new FileInputStream(filePath);
byte[] buffer = new byte[1024 * 100];
int count = 0;
while ((count = fis.read(buffer)) != -1) {
bos.write(buffer, 0, count);
}
fis.close();
} catch (Exception e) {
e.printStackTrace();
}
base64String = Base64.encodeToString(bos.toByteArray(), Base64.DEFAULT);
return base64String;
}
fun File.toBase64(): String? {
val result: String?
inputStream().use { inputStream ->
val sourceBytes = inputStream.readBytes()
result = Base64.encodeToString(sourceBytes, Base64.DEFAULT)
}
return result
}