Android Bitmap Tutorial and Examples.

 

import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.util.Base64;
import android.util.Log;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class ImageUtils {

    private static final String TAG = "ImageUtils";

    public static byte[] bitmap2Bytes(Bitmap bitmap, int quality, Bitmap.CompressFormat format){
        if (bitmap == null){
            return null;
        }else {
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            bitmap.compress(format,quality,outputStream);
            try {
                outputStream.flush();
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return outputStream.toByteArray();
        }
    }

    public static String bitmap2Base64(Bitmap bitmap, int quality, Bitmap.CompressFormat format){
        byte[] bytes = bitmap2Bytes(bitmap,quality,format);
        return Base64.encodeToString(bytes,Base64.DEFAULT)
                .replace("n","")
                .replace("r","")
                .replace("t","");
    }

    public static Bitmap scaleBitmap(Bitmap srcBitmap, int maxWidth, int maxHeight){

        int width = srcBitmap.getWidth();
        int height = srcBitmap.getHeight();

        Log.d(TAG, "scaleBitmap: nwidth = " + width + "nheight = " + height);

        int desiredWidth = Math.min(width,maxWidth);
        int desiredHeight = Math.min(height,maxHeight);

        float scaleWidth = ((float) desiredWidth / width);
        float scaleHeight = ((float) desiredHeight / height);

        float scaled = Math.min(scaleHeight,scaleWidth);

        Matrix matrix = new Matrix();
        matrix.postScale(scaled,scaled);
        return Bitmap.createBitmap(srcBitmap,0,0,width,height,matrix,true);
    }

    public static Bitmap convert2Gray(Bitmap bitmap) {
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();

        int[] pixs = new int[width * height];

        bitmap.getPixels(pixs, 0, width, 0, 0, width, height);

        int alpha = 0xFF << 24;

        for (int i = 0; i < height; i++) {
            for (int j = 0; j < width; j++) {
                int color = pixs[width * i + j];

                int red = (color & 0x00FF0000) >> 16;

                int green = (color & 0x0000FF00) >> 8;

                int blue = (color & 0x000000FF);

                color = (red + green + blue) / 3;

                color = alpha | (color << 16) | (color << 8)| color;

                pixs[width * i + j] = color;

            }
        }

        Bitmap result = Bitmap.createBitmap(width,height, Bitmap.Config.RGB_565);
        result.setPixels(pixs,0,width,0,0,width,height);
        return result;
    }

}

1. Download Bitmap From the Web

Let’s see how we can download bitmap from the internet via HttpURLConnection class.

private Bitmap downloadUrl(String myurl) throws IOException {

        try {
            URL url = new URL(myurl);
            HttpURLConnection connection = (HttpURLConnection) url
                    .openConnection();
            connection.setDoInput(true);
            connection.connect();
            InputStream input = connection.getInputStream();
            Bitmap myBitmap = BitmapFactory.decodeStream(input);
            return myBitmap;

        } catch (IOException e) {
            return null;
        }
}   

Here’s the full example with AsyncTask:

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpImageGetTask extends AsyncTask<String, Void, Bitmap> {
    private OnImageDownloadCompleted listener;

    public HttpImageGetTask(OnImageDownloadCompleted listener) {
        this.listener = listener;
    }

    @Override
    protected Bitmap doInBackground(String... urls) {
        try {
            return downloadUrl(urls[0]);
        } catch (IOException e) {
            return null;
        }
    }

    @Override
    protected void onPostExecute(Bitmap result) {
        listener.onBitmapCompleted(result);
    }

    private Bitmap downloadUrl(String myurl) throws IOException {

        try {
            URL url = new URL(myurl);
            HttpURLConnection connection = (HttpURLConnection) url
                    .openConnection();
            connection.setDoInput(true);
            connection.connect();
            InputStream input = connection.getInputStream();
            Bitmap myBitmap = BitmapFactory.decodeStream(input);
            return myBitmap;

        } catch (IOException e) {
            return null;
        }

    }

}
2. How to Get MD5 of a String

This is a helper method we will use in some of the following examples.


    public static String getMD5(String content) {

        try {

            MessageDigest digest = MessageDigest.getInstance("MD5");

            digest.update(content.getBytes());

            return getHashString(digest);

        } catch (Exception e) {

        }

        return null;

    }
3. How to Load Bitmap into ImageView From File System

You cam also load a Bitmap from the file system. You need however to pass the image path instead of url.

    public static Bitmap getBitmap2(String imagePath) {

        if (!(imagePath.length() > 5)) {

            return null;

        }

        File cache_file = new File(new File(
                Environment.getExternalStorageDirectory(), "xxxx"),
                "cachebitmap");

        cache_file = new File(cache_file, getMD5(imagePath));

        if (cache_file.exists()) {

            return BitmapFactory.decodeFile(getBitmapCache(imagePath));

        } else {

            try {

                URL url = new URL(imagePath);

                HttpURLConnection conn = (HttpURLConnection) url
                        .openConnection();

                conn.setConnectTimeout(5000);

                if (conn.getResponseCode() == 200) {

                    InputStream inStream = conn.getInputStream();

                    File file = new File(new File(
                            Environment.getExternalStorageDirectory(), "xxxx"),
                            "cachebitmap");

                    if (!file.exists()) {
                        file.mkdirs();
                    }

                    file = new File(file, getMD5(imagePath));

                    FileOutputStream out = new FileOutputStream(file);

                    byte buff[] = new byte[1024];

                    int len = 0;

                    while ((len = inStream.read(buff)) != -1) {

                        out.write(buff, 0, len);

                    }

                    out.close();

                    inStream.close();

                    return BitmapFactory.decodeFile(getBitmapCache(imagePath));

                }

            } catch (Exception e) {
            }

        }

        return null;

    }
4. How to Get Bitmap Cache
public static String getBitmapCache(String url) {

        File file = new File(new File(
                Environment.getExternalStorageDirectory(), "xxxx"),
                "cachebitmap");

        file = new File(file, getMD5(url));

        if (file.exists()) {

            return file.getAbsolutePath();

        }

        return null;

    }
5. How to Load Bitmap into ImageView via Glide
    public static void displayImageBitmap(String url,ImageView imageView) {

        Glide.with(MainApp.getContext())
                .load(url)
                .asBitmap()
                .thumbnail(0.2f)
                .placeholder(R.drawable.pictures_no)
                .diskCacheStrategy(DiskCacheStrategy.SOURCE)
                .into(imageView);

    }
6. How to Get a Hash string of a MessageDigest
    private static String getHashString(MessageDigest digest) {
        StringBuilder builder = new StringBuilder();
        for (byte b : digest.digest()) {
            builder.append(Integer.toHexString((b >> 4) & 0xf));
            builder.append(Integer.toHexString(b & 0xf));
        }
        return builder.toString().toLowerCase();
    }
7. How to Save a Bitmap to Local File

You pass the File object onto which we wish to save our Bitmap. The Bitmap also is passed as a parameter to our method.

    public static String saveBitmapToLocal(File file , Bitmap bitmap) {
        try {
            if(!file.exists()) {
                file.createNewFile();
            }
            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(file));
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, bufferedOutputStream);
            bufferedOutputStream.close();
            LogUtil.d(TAG, "photo image from data, path:" + file.getAbsolutePath());
            return file.getAbsolutePath();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
8. How to Extract Thumbnail From Image

Then we return a Bitmap. The path to the image is provided to us alongside the dimensions of the thumbanial as well as whether to crop the image.

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public static Bitmap extractThumbNail(final String path, final int width, final int height,  final boolean crop) {
        Assert.assertTrue(path != null && !path.equals("") && height > 0 && width > 0);

        BitmapFactory.Options options = new BitmapFactory.Options();

        try {
            options.inJustDecodeBounds = true;
            Bitmap tmp = BitmapFactory.decodeFile(path);
            if (tmp != null) {
                tmp.recycle();
                tmp = null;
            }

            LogUtil.d(TAG, "extractThumbNail: round=" + width + "x" + height + ", crop=" + crop);
            final double beY = options.outHeight * 1.0 / height;
            final double beX = options.outWidth * 1.0 / width;
            LogUtil.d(TAG, "extractThumbNail: extract beX = " + beX + ", beY = " + beY);
            options.inSampleSize = (int) (crop ? (beY > beX ? beX : beY) : (beY < beX ? beX : beY));
            if (options.inSampleSize <= 1) {
                options.inSampleSize = 1;
            }

            // NOTE: out of memory error
            while (options.outHeight * options.outWidth / options.inSampleSize > MAX_DECODE_PICTURE_SIZE) {
                options.inSampleSize++;
            }

            int newHeight = height;
            int newWidth = width;
            if (crop) {
                if (beY > beX) {
                    newHeight = (int) (newWidth * 1.0 * options.outHeight / options.outWidth);
                } else {
                    newWidth = (int) (newHeight * 1.0 * options.outWidth / options.outHeight);
                }
            } else {
                if (beY < beX) {
                    newHeight = (int) (newWidth * 1.0 * options.outHeight / options.outWidth);
                } else {
                    newWidth = (int) (newHeight * 1.0 * options.outWidth / options.outHeight);
                }
            }

            options.inJustDecodeBounds = false;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                options.inMutable = true;
            }
            LogUtil.i(TAG, "bitmap required size=" + newWidth + "x" + newHeight + ", orig=" + options.outWidth + "x" + options.outHeight + ", sample=" + options.inSampleSize);
            Bitmap bm = BitmapFactory.decodeFile(path);
            setInNativeAlloc(options);
            if (bm == null) {
                Log.e(TAG, "bitmap decode failed");
                return null;
            }

            LogUtil.i(TAG, "bitmap decoded size=" + bm.getWidth() + "x" + bm.getHeight());
            final Bitmap scale = Bitmap.createScaledBitmap(bm, newWidth, newHeight, true);
            if (scale != null) {
                bm.recycle();
                bm = scale;
            }

            if (crop) {
                final Bitmap cropped = Bitmap.createBitmap(bm, (bm.getWidth() - width) >> 1, (bm.getHeight() - height) >> 1, width, height);
                if (cropped == null) {
                    return bm;
                }

                bm.recycle();
                bm = cropped;
                LogUtil.i(TAG, "bitmap croped size=" + bm.getWidth() + "x" + bm.getHeight());
            }
            return bm;

        } catch (final OutOfMemoryError e) {
            LogUtil.e(TAG, "decode bitmap failed: " + e.getMessage());
            options = null;
        }

        return null;
    }
9. How to Decode a Stream into Bitmap
    public static Bitmap decodeStream(InputStream stream , float dip) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        if(dip != 0.0F) {
            options.inDensity = (int)(160.0F * dip);
        }
        options.inPreferredConfig = Bitmap.Config.ARGB_8888;
        setInNativeAlloc(options);
        try {
            Bitmap bitmap = BitmapFactory.decodeStream(stream, null,options);
            return bitmap;
        } catch (OutOfMemoryError e) {
            options.inPreferredConfig = Bitmap.Config.RGB_565;
            setInNativeAlloc(options);
            try {
                Bitmap bitmap = BitmapFactory.decodeStream(stream, null,options);
                return bitmap;
            } catch (OutOfMemoryError e2) {
            }
        }
        return null;
    }
10. How to Create a new Bitmap
  public static Bitmap newBitmap(int width, int height,Bitmap.Config config) {
        try {
            Bitmap bitmap = Bitmap.createBitmap(width, height,config);
            return bitmap;
        } catch (Throwable localThrowable) {
            LogUtil.e(TAG, localThrowable.getMessage());
        }
        return null;
    }
11. How to Convert a Bitmap to an Array

You pass the Bitmap as a parameter and we compress it and convert it to a byte array.

    public static byte[] bmpToByteArray(final Bitmap bmp, final boolean needRecycle) {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.PNG, 100, output);
        if (needRecycle) {
            bmp.recycle();
        }
        byte[] result = output.toByteArray();
        try {
            output.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
12. How to load a Bitmap From a File name

Here’s an even simpler example of loading a bitmap from a file name and returning it.

public static Bitmap loadFromFile(String filename) {
        try {
            File f = new File(filename);
            if (!f.exists()) {
                return null;
            }
            Bitmap tmp = BitmapFactory.decodeFile(filename);
            // tmp = setExifInfo(filename, tmp);
            return tmp;
        } catch (Exception e) {
            return null;
        }

    }
13. How to Compress an Image

We will compress the image and return it as a Bitmap. Basically you pass us a bitmap and we compress it and return it to you.

public Bitmap compressImage(Bitmap image) {

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        int options = 100;
        while (baos.toByteArray().length / 1024 > 128) { 
            baos.reset();
            image.compress(Bitmap.CompressFormat.JPEG,options, baos);/
            options -= 10;
        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);
        // bitmap.
        return bitmap;

    }
14. How to load a Bitmap From a Path

Just pass us the image path then we will decode that file using the BitmapFactory‘s decodeFile method.

public static Bitmap loadBitmap(String imgpath) {
        return BitmapFactory.decodeFile(imgpath);
    }
15. How to Scale a Bitmap

Pass us the Bitmap, it’s width and height then we scale it.

    private static Bitmap scaleBitmap(Bitmap bitmap, float ww, float hh) {
        double scaleWidth = 1;
        double scaleHeight = 1;
        int widthOri = bitmap.getWidth();
        int heightOri = bitmap.getHeight();

        if (widthOri > heightOri && widthOri > ww) {
            scaleWidth = 1.0 / (double) (widthOri / ww);
            scaleHeight = scaleWidth;
        } else if (widthOri < heightOri && heightOri > hh) {
            scaleHeight = 1.0 / (double) (heightOri / hh);
            scaleWidth = scaleHeight;
        }

        Matrix matrix = new Matrix();
        matrix.postScale((float) scaleWidth, (float) scaleHeight);

        Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,
                bitmap.getWidth(), bitmap.getHeight(), matrix, true);
16. How to Capture Screenshot and Return it as a Byte
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.View;

public class ScreenShotUtil {
    public static Bitmap capture(View view, float width, float height, boolean scroll, Bitmap.Config config) {
        if (!view.isDrawingCacheEnabled()) {
            view.setDrawingCacheEnabled(true);
        }
        if(width==0){
            width= MainApp.getInstance().getScreenWidth();
        }
        if(height==0){
            height= MainApp.getInstance().getScreenHeight();
        }

        Bitmap bitmap = Bitmap.createBitmap((int) width, (int) height, config);
        bitmap.eraseColor(Color.WHITE);
        Canvas canvas = new Canvas(bitmap);
        int left = view.getLeft();
        int top = view.getTop();
        if (scroll) {
            left = view.getScrollX();
            top = view.getScrollY();
        }
        int status = canvas.save();
        canvas.translate(-left, -top);
        float scale = width / view.getWidth();
        canvas.scale(scale, scale, left, top);
        view.draw(canvas);
        canvas.restoreToCount(status);
        Paint alphaPaint = new Paint();
        alphaPaint.setColor(Color.TRANSPARENT);
        canvas.drawRect(0f, 0f, 1f, height, alphaPaint);
        canvas.drawRect(width - 1f, 0f, width, height, alphaPaint);
        canvas.drawRect(0f, 0f, width, 1f, alphaPaint);
        canvas.drawRect(0f, height - 1f, width, height, alphaPaint);
        canvas.setBitmap(null);
        return bitmap;
    }

}
17. How to Convert Bitmap to Base64 String
    public static String convertBitmapToString(Bitmap bitmap) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();// outputstream
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
        byte[] b = baos.toByteArray();
        return Base64.encodeToString(b, Base64.DEFAULT);

    }
18. How to Convert String to Bitmap
    public static Bitmap convertStringToBitmap(String st) {
        // OutputStream out;
        Bitmap bitmap = null;
        try
        {
            // out = new FileOutputStream("/sdcard/aa.jpg");
            byte[] bitmapArray;
            bitmapArray = Base64.decode(st, Base64.DEFAULT);
            bitmap = BitmapFactory.decodeByteArray(bitmapArray, 0, bitmapArray.length);
            // bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
            return bitmap;
        }
        catch (Exception e)
        {
            return null;
        }
19. How to Create a bitmap from the supplied view.

You supply the View from which you want us to create the bitmap.

    public static Bitmap createBitmapFromView(View view) {
        final Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
        final Canvas canvas = new Canvas(bitmap);

        view.layout(view.getLeft(), view.getTop(), view.getRight(), view.getBottom());
        view.draw(canvas);

        return bitmap;
    }