Android Bitmap Encode generateEncodedUrlForImage(byte[] bitMapData)

Here you can find the source of generateEncodedUrlForImage(byte[] bitMapData)

Description

Generates a base64 encoded data URI from the provided byte array

License

Apache License

Parameter

Parameter Description
bitMapData a byte array representation of a jpg image

Return

String representation of a Base64 encoded data URI

Declaration

public static String generateEncodedUrlForImage(byte[] bitMapData) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import android.graphics.Bitmap;

import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.Base64;
import java.io.ByteArrayOutputStream;

public class Main {
    /**//  ww  w  .  jav  a  2s  . c  om
     * Generates a Base64 encoded data URI from the provided Drawable
     *
     * @param drawable a valid BirmapDrawable to be encoded
     * @return String representation of a Base64 encoded data URI
     */
    public static String generateEncodedUrlForImage(Drawable drawable) {
        if (drawable != null && drawable instanceof BitmapDrawable) {
            Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
            return generateEncodedUrlForImage(bitmap);
        } else {
            return null;
        }
    }

    /**
     * Generates a base64 encoded data URI from the provided Bitmap
     *
     * @param bitmap a Bitmap to be encoded and compressed
     * @return String representation of a Base64 encoded data URI
     */
    public static String generateEncodedUrlForImage(Bitmap bitmap) {
        if (bitmap != null) {
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 80, stream);
            byte[] bitMapData = stream.toByteArray();
            return generateEncodedUrlForImage(bitMapData);
        } else {
            return null;
        }
    }

    /**
     * Generates a base64 encoded data URI from the provided byte array
     *
     * @param bitMapData a byte array representation of a jpg image
     * @return String representation of a Base64 encoded data URI
     */
    public static String generateEncodedUrlForImage(byte[] bitMapData) {
        if (bitMapData != null) {
            try {
                return "data:image/jpg;base64,"
                        + Base64.encodeToString(bitMapData, Base64.NO_WRAP);
            } catch (AssertionError assertionError) {
                return null;
            }
        } else {
            return null;
        }
    }
}

Related

  1. generateEncodedUrlForImage(Bitmap bitmap)
  2. generateEncodedUrlForImage(Drawable drawable)