Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Re-size bitmap to smaller bitmap

I have a list of bitmaps. What I want is to take these bitmaps and, with the help of canvas, create a new bitmap with scaled down images (meaning, make them quite tiny) from the list I have of bitmaps.

I've manage to do this but, the image looks quite horrible due to the down-scaling. I've tried many things, settings, creating new canvases etc.

The simple first solution looks like this (code below), but, as I said, the images looks awful.

public static Bitmap folderBitmap(Bitmap bitmap[]) {

    Bitmap b = Bitmap.createBitmap(100, 100, Bitmap.Config.RGB_565);
    Canvas c = new Canvas(b);

    c.drawARGB(255, 255, 255, 255);

    Paint paint = new Paint();
    paint.setAntiAlias(false);
    paint.setFilterBitmap(false);
    paint.setDither(true);

    c.drawBitmap(getBit(bitmap), 4, 4, paint);
    c.drawBitmap(getBit(bitmap), 35, 4, paint);
    c.drawBitmap(getBit(bitmap), 67, 4, paint);

    c.drawBitmap(getBit(bitmap), 4, 35, null);
    c.drawBitmap(getBit(bitmap), 35, 35, null);
    c.drawBitmap(getBit(bitmap), 67, 35, null);

    c.drawBitmap(getBit(bitmap), 4, 67, null);
    c.drawBitmap(getBit(bitmap), 35, 67, null);
    c.drawBitmap(getBit(bitmap), 67, 67, null);

    return b;
}

private static Bitmap getBit(Bitmap[] b) {
    Bitmap newBitmap = Bitmap.createScaledBitmap(b[getR()], 28, 28, false);

    return newBitmap;
}

private static int getR() {
    Random r = new Random();
    int rint = r.nextInt(8);
    return rint;
}

By awful I mean, they look pixelated and un-sharp.

like image 719
Joakim Engstrom Avatar asked Jun 14 '26 10:06

Joakim Engstrom


1 Answers

Use inSampleSize to scale a Bitmap. From the documentation

If set to a value > 1, requests the decoder to subsample the original image, returning a smaller image to save memory. The sample size is the number of pixels in either dimension that correspond to a single pixel in the decoded bitmap. For example, inSampleSize == 4 returns an image that is 1/4 the width/height of the original, and 1/16 the number of pixels. Any value <= 1 is treated the same as 1. Note: the decoder uses a final value based on powers of 2, any other value will be rounded down to the nearest power of 2.

For instance:

 BitmapFactory.Options opts = new BitmapFactory.Options();
 opt.inSampleSize = 4;
 Bitmap newBitmap = BitmapFactory.decodeFile(filePath, opts);
like image 105
Blackbelt Avatar answered Jun 17 '26 23:06

Blackbelt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!