Bytes to Bitmap - Android Graphics

Android examples for Graphics:Bitmap Byte Array

Description

Bytes to Bitmap

Demo Code


//package com.java2s;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

public class Main {
    static public Bitmap Bytes2Bimap(byte[] b) {

        if (b.length != 0) {

            return BitmapFactory.decodeByteArray(b, 0, b.length);

        } else {//from w w  w  .j  a  v a2  s .c  o m
            return null;
        }
    }

    static public Bitmap Bytes2Bimap(byte[] data, int w, int h) {

        if (data.length != 0) {
            final BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeByteArray(data, 0, data.length, options);

            // Calculate inSampleSize
            options.inSampleSize = calculateInSampleSize(options, w, h);

            // Decode bitmap with inSampleSize set
            options.inJustDecodeBounds = false;

            Bitmap bm = BitmapFactory.decodeByteArray(data, 0, data.length,
                    options);
            if (bm == null) {
                return null;
            }
            return bm;

        } else {
            return null;
        }
    }

    private static int calculateInSampleSize(BitmapFactory.Options options,
            int reqWidth, int reqHeight) {
        // Raw height and width of image
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {

            // Calculate ratios of height and width to requested height and
            // width
            final int heightRatio = Math.round((float) height
                    / (float) reqHeight);
            final int widthRatio = Math.round((float) width
                    / (float) reqWidth);

            inSampleSize = heightRatio < widthRatio ? widthRatio
                    : heightRatio;
        }

        return inSampleSize;
    }
}

Related Tutorials