本文共 2811 字,大约阅读时间需要 9 分钟。
In this tutorial you will learn how to convert image to base64 string or base64 string to image in android.
在本教程中,您将学习如何在android中将图像转换为base64字符串或将base64字符串转换为图像。
Base64 is an encoding schema that represents binary data in an ASCII string. It becomes really helpful in case you want to or save the image in database.
Base64是一种编码模式,表示ASCII字符串中的二进制数据。 如果您要将或将图像保存在数据库中,它将非常有用。
Image to Base64 String
图像到Base64字符串
First convert the image into bitmap.
首先将图像转换为位图。
Then compress bitmap to ByteArrayOutputStream.
然后将位图压缩到ByteArrayOutputStream。
Convert ByteArrayOutputStream to byte array.
将ByteArrayOutputStream转换为字节数组。
Finally convert byte array to base64 string.
最后将字节数组转换为base64字符串。
Base64 String to Image
Base64字符串到图像
Convert the base64 string to byte array.
将base64字符串转换为字节数组。
Now convert byte array to bitmap.
现在将字节数组转换为位图。
Create new android studio project with package name com.base64example.
使用包名称com.base64example创建新的android studio项目。
Add an image in res/drawable folder. This is the image that we will convert. See below screenshot I have added an image with name logo.png.
在res / drawable文件夹中添加图像。 这是我们将转换的图像。 参见下面的屏幕截图,我添加了一个名称为logo.png的图像。
Now add following code in respectively files.
现在分别在文件中添加以下代码。
acitivity_main.xml
acitivity_main.xml
MainActivity.java
MainActivity.java
package com.base64example; import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.util.Base64;import android.widget.ImageView; import java.io.ByteArrayOutputStream; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ImageView image =(ImageView)findViewById(R.id.image); //encode image to base64 string ByteArrayOutputStream baos = new ByteArrayOutputStream(); Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.logo); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos); byte[] imageBytes = baos.toByteArray(); String imageString = Base64.encodeToString(imageBytes, Base64.DEFAULT); //decode base64 string to image imageBytes = Base64.decode(imageString, Base64.DEFAULT); Bitmap decodedImage = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length); image.setImageBitmap(decodedImage); }}
Run the project.
运行项目。
I am converting the image to base64 string and then converting back to bitmap and finally showing it in ImageView.
我将图像转换为base64字符串,然后转换回位图,最后在ImageView中显示。
Screenshot
屏幕截图
翻译自:
转载地址:http://arggb.baihongyu.com/