Matthias Brück
Matthias Brück

Reputation: 204

Android: Get Bitmap from a 2D-Integer Array containing ARGB values

Currently I have a 2D integer Array containing ARGB values of an image. Now I want to get a Bitmap with those values to display it on the screen.

The Bitmap should get scaled as well, for example the image is 80x80 or 133x145, but I only want it to be 50x50. Something like this, but as it's Android the Java classes are not available:

    private static BufferedImage scale(BufferedImage image, int width, int height) {
        java.awt.Image temp = image.getScaledInstance(width, height, java.awt.Image.SCALE_SMOOTH);
        BufferedImage imageOut = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D bGr = imageOut.createGraphics();
        bGr.drawImage(temp, 0, 0, null);
        bGr.dispose();
        return imageOut;
    }

I already searched the API and Stack Overflow but I could not find any hints, classes or methods how to do so.

Upvotes: 1

Views: 820

Answers (1)

Bartek Lipinski
Bartek Lipinski

Reputation: 31438

First of all create a Bitmap object representing the original size image (your 80x80 or 133x145). You can do it with:

Bitmap.Config bitmapConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = Bitmap.createBitmap(width, height, bitmapConfig);

where width is your source width (80 or 133), and height is your source height (80 or 145).

Then fill this Bitmap with colors from your array. I don't know the exact way your array is built and the type of data it stores, so for the purpose of this simple concept explanation I will assume that it's just a regular, one-dimensional array that stores ARGB hex String values. Be sure to correct for loop to match your exact case:

int[] bitmapPixels = new int[width * height];
for (int i = 0, size = bitmapPixels.length; i < size; ++i) {
    bitmapPixels[i] = Color.parseColor(argbArray[i]);
}
bitmap.setPixels(bitmapPixels, 0, width, 0, 0, width, height);

Then create a scaled Bitmap and recycle the original size Bitmap you created before.

Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, 50, 50, false);
bitmap.recycle();

Upvotes: 2

Related Questions