mhafizhasan
3/11/2016 - 8:10 AM

Reusable image converter class

Reusable image converter class

Base 64 image converter class

How to's

  1. Save as ImageConverter.java class
  2. Import to your activity
  3. Usage sample: String image64 = ImageConverter.toBase64(fileUri.toString()); to convert Image -> base64
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Base64;

import java.io.ByteArrayOutputStream;

/**
 * Created by Dermis on 10,March,2016.
 */
public class ImageConverter {

    public static String toBase64(String imagePath) {
        Bitmap bm = BitmapFactory.decodeFile(imagePath.replace("file:",""));
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.JPEG, 50, baos);
        byte[] byteArrayImage = baos.toByteArray();
        String encodedImage = Base64.encodeToString(byteArrayImage, Base64.DEFAULT);
        return encodedImage;
    }

    public static Bitmap toBitmap(String encodedImage) {
        byte[] decodedString = Base64.decode(encodedImage, Base64.DEFAULT);
        Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
        return decodedByte;
    }
}