get Thumb Bitmap - Android Graphics

Android examples for Graphics:Bitmap Thumbnail

Description

get Thumb Bitmap

Demo Code


//package com.java2s;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

public class Main {
    public static Bitmap getThumbBitmap(String absolutePath, int squareWidth) {
        Bitmap bitmapReal = BitmapFactory.decodeFile(absolutePath);
        if (bitmapReal == null)
            return null;

        Bitmap centerSquareScaleBitmap = centerSquareScaleBitmap(
                bitmapReal, squareWidth);
        bitmapReal.recycle();/*from   w ww.j  a  va 2s .com*/

        return centerSquareScaleBitmap;
    }

    public static Bitmap centerSquareScaleBitmap(Bitmap bitmap,
            int edgeLength) {
        if (null == bitmap || edgeLength <= 0) {
            return null;
        }

        Bitmap result = bitmap;
        int widthOrg = bitmap.getWidth();
        int heightOrg = bitmap.getHeight();

        if (widthOrg > edgeLength && heightOrg > edgeLength) {
  
            int longerEdge = (int) (edgeLength
                    * Math.max(widthOrg, heightOrg) / Math.min(widthOrg,
                    heightOrg));
            int scaledWidth = widthOrg > heightOrg ? longerEdge
                    : edgeLength;
            int scaledHeight = widthOrg > heightOrg ? edgeLength
                    : longerEdge;

            Bitmap scaledBitmap;

            try {
                scaledBitmap = Bitmap.createScaledBitmap(bitmap,
                        scaledWidth, scaledHeight, true);
            } catch (Exception e) {
                return null;
            }

            int xTopLeft = (scaledWidth - edgeLength) / 2;
            int yTopLeft = (scaledHeight - edgeLength) / 2;

            try {
                result = Bitmap.createBitmap(scaledBitmap, xTopLeft,
                        yTopLeft, edgeLength, edgeLength);
                scaledBitmap.recycle();
            } catch (Exception e) {
                return null;
            }
        }

        return result;
    }
}

Related Tutorials