How to convert a Base64 string into a Bitmap image to show it in a ImageView?

后端 未结 6 2076
臣服心动
臣服心动 2020-11-22 10:23

I have a Base64 String that represents a BitMap image.

I need to transform that String into a BitMap image again to use it on a ImageView in my Android app

H

6条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-22 11:03

    To check online you can use

    http://codebeautify.org/base64-to-image-converter

    You can convert string to image like this way

    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);
        }
    }
    

    http://www.thecrazyprogrammer.com/2016/10/android-convert-image-base64-string-base64-string-image.html

提交回复
热议问题