Convert image to BLOB (bytes array) & vice-versa using Base64 encoder in Android App? - API 34

Опубликовано: 15 Ноябрь 2023
на канале: Programmer World
308
7

This video shows the steps to read an image file from the download folder of the android device. Then convert it in to a Blob type, basically a bytes array. Then it encodes it into string type using Base64 character encoding. And it decodes it back.

It displays both encoded and decoded images in 2 separate ImageView widgets.
For API 34 | Android 14 version.

I hope you like this video. For any questions, suggestions or appreciation please contact us at: https://programmerworld.co/contact/ or email at: [email protected]

Complete source code and other details/ steps of this video are posted in the below link:
https://programmerworld.co/android/ho...


However, the main Java code is copied below also for reference:

package com.programmerworld.imagetoblob;

import static android.Manifest.permission.READ_MEDIA_IMAGES;

import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.storage.StorageManager;
import android.os.storage.StorageVolume;
import android.view.View;
import android.widget.ImageView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.Base64;

public class MainActivity extends AppCompatActivity {
private ImageView imageView1, imageView2;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

ActivityCompat.requestPermissions(this,
new String[]{READ_MEDIA_IMAGES},
PackageManager.PERMISSION_GRANTED);

imageView1 = findViewById(R.id.imageView1);
imageView2 = findViewById(R.id.imageView2);
}

public void buttonImageToBlob(View view){
StorageManager storageManager = (StorageManager) getSystemService(STORAGE_SERVICE);
StorageVolume storageVolume = storageManager.getStorageVolumes().get(0);// 0 for internal storage
// initial image
Bitmap bitmap1 = BitmapFactory.decodeFile(storageVolume.getDirectory().getPath() + "/Download/flower.jpg");
imageView1.setImageBitmap(bitmap1);

// Encoding
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap1.compress(Bitmap.CompressFormat.PNG, 0, byteArrayOutputStream);
byte[] bytesImageEncoded = byteArrayOutputStream.toByteArray();
String stringImageBytes = Base64.getEncoder().encodeToString(bytesImageEncoded);

// Decoding
byte[] bytesImageDecoded = Base64.getDecoder().decode(stringImageBytes);
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytesImageDecoded);
Bitmap bitmap2 = BitmapFactory.decodeStream(byteArrayInputStream);
imageView2.setImageBitmap(bitmap2);
}
}


--