Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
/*
 * Licensed Materials - Property of IBM
 *  Copyright IBM Corporation 2015. All Rights Reserved.
 */

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import java.io.ByteArrayOutputStream;

public class Main {
    /**
     * The lowest quality, highest compression value used by
     * {@link #encodeBase64Image(android.content.Context, int, int)}.
     */
    public static final int LOWEST_QUALITY = 0;
    /**
     * The highest quality, lowest compression value used by
     * {@link #encodeBase64Image(android.content.Context, int, int)}.
     */
    public static final int HIGHEST_QUALITY = 100;

    /**
     * Encodes an ImageView into a base-64 byte array representation. Encoding compression uses
     * highest quality available.
     *
     * @param context
     * @param res     the resource id of an ImageView
     * @return the raw base-64 image data
     */
    public static byte[] encodeBase64Image(Context context, int res) {
        return encodeBase64Image(context, res, HIGHEST_QUALITY);
    }

    /**
     * Encodes an ImageView into a base-64 byte array representation. Encoding compression depends
     * on the quality parameter passed. 0 is the most compressed (lowest quality) and 100 is the
     * least compressed (highest quality).
     *
     * @param context
     * @param res     the resource id of an ImageView
     * @param quality The amount of compression, where 0 is the lowest quality and 100 is the
     *                highest
     * @return the raw base-64 image data compressed accordingly
     */
    public static byte[] encodeBase64Image(Context context, int res, int quality) {
        // ensure quality is between 0 and 100 (inclusive)
        quality = Math.max(LOWEST_QUALITY, Math.min(HIGHEST_QUALITY, quality));

        Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), res);
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, quality, stream);
        return stream.toByteArray();
    }
}