有人可以告诉我将图像(最大200KB)转换为Base64字符串的代码吗?
我需要知道如何使用android,因为我必须添加上传图像的功能到我的主应用程序中的远程服务器,将它们作为字符串放入数据库的一行。
我在谷歌和StackOverflow中搜索,但我找不到简单的例子 我还能找到一些例子,但他们并没有谈到转变为String。然后我需要转换为字符串以通过JSON上传到我的远程服务器。
答案 0 :(得分:309)
您可以使用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)。
查看本文以获取解决方法:
http://androidcodemonkey.blogspot.com/2010/03/how-to-base64-encode-decode-android.html
答案 1 :(得分:94)
您也可以通过简单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);
答案 2 :(得分:6)
如果您需要base64 over JSON,请查看Jackson:它明确支持二进制数据读/写为低级别(JsonParser,JsonGenerator)和数据绑定级别的base64。因此,您可以使用具有byte []属性的POJO,并自动处理编码/解码。 而且非常有效,应该重要。
答案 3 :(得分:4)
// 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;
}
答案 4 :(得分:3)
此代码完成在我的项目中运行
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 base 64 string
String imgString = Base64.encodeToString(byteFormat, Base64.NO_WRAP);
return imgString;
}
答案 5 :(得分:2)
如果您在 Android 上执行此操作,请从React Native codebase复制帮助:
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import android.util.Base64;
import android.util.Base64OutputStream;
import android.util.Log;
// You probably don't want to do this with large files
// (will allocate a large string and can cause an OOM crash).
private String readFileAsBase64String(String path) {
try {
InputStream is = new FileInputStream(path);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Base64OutputStream b64os = new Base64OutputStream(baos, Base64.DEFAULT);
byte[] buffer = new byte[8192];
int bytesRead;
try {
while ((bytesRead = is.read(buffer)) > -1) {
b64os.write(buffer, 0, bytesRead);
}
return baos.toString();
} catch (IOException e) {
Log.e(TAG, "Cannot read file " + path, e);
// Or throw if you prefer
return "";
} finally {
closeQuietly(is);
closeQuietly(b64os); // This also closes baos
}
} catch (FileNotFoundException e) {
Log.e(TAG, "File not found " + path, e);
// Or throw if you prefer
return "";
}
}
private static void closeQuietly(Closeable closeable) {
try {
closeable.close();
} catch (IOException e) {
}
}
答案 6 :(得分:0)
Error: Could not find sdk.jar (com.appunfold:sdk:1.0.2).
Searched in the following locations:
http://dl.bintray.com/appunfold/android/com/appunfold/sdk/1.0.2/sdk-1.0.2.jar
答案 7 :(得分:0)
以下是可能对您有用的伪代码:
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;
}
答案 8 :(得分:0)
这是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)
}
答案 9 :(得分:0)
在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);
答案 10 :(得分:0)
对于那些寻求将图像文件转换为Base64字符串而不进行压缩或先将其转换为位图的有效方法的人,可以改而encode the file as base64
val base64EncodedImage = FileInputStream(imageItem.localSrc).use {inputStream - >
ByteArrayOutputStream().use {outputStream - >
Base64OutputStream(outputStream, Base64.DEFAULT).use {
base64FilterStream - >
inputStream.copyTo(base64FilterStream)
base64FilterStream.flush()
outputStream.toString()
}
}
}
希望这会有所帮助!
答案 11 :(得分:0)
这是image encode
和dcode
的代码
在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 base 64 string
String imgString = Base64.encodeToString(byteFormat, Base64.NO_WRAP);
return imgString;
}
@Override
protected void onPostExecute(String s) {
textView5.setText(s);
}
}.execute();
答案 12 :(得分:0)
我做一个静态函数。我认为它更有效。
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;
}
简单又容易!
答案 13 :(得分:0)
Kotlin 版本:
fun File.toBase64(): String? {
val result: String?
inputStream().use { inputStream ->
val sourceBytes = inputStream.readBytes()
result = Base64.encodeToString(sourceBytes, Base64.DEFAULT)
}
return result
}
答案 14 :(得分:-1)
使用此代码:
byte[ ] decodedString = Base64.decode(Base64String.getBytes(), Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);