java – Flip a Bitmap image horizontally or vertically-ThrowExceptions

Exception or error:

By using this code we can rotate an image:

public static Bitmap RotateBitmap(Bitmap source, float angle) {
      Matrix matrix = new Matrix();
      matrix.postRotate(angle);
      return Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), matrix, true);
}

But how can we flip an image horizontally or vertically?

How to solve:

Given cx,cy is the centre of the image:

Flip in x:

matrix.postScale(-1, 1, cx, cy);

Flip in y:

matrix.postScale(1, -1, cx, cy);

###

Short extension for Kotlin

private fun Bitmap.flip(x: Float, y: Float, cx: Float, cy: Float): Bitmap {
    val matrix = Matrix().apply { postScale(x, y, cx, cy) }
    return Bitmap.createBitmap(this, 0, 0, width, height, matrix, true)
}

And usage:

For horizontal flip :-

val cx = bitmap.width / 2f
val cy = bitmap.height / 2f
val flippedBitmap = bitmap.flip(-1f, 1f, cx, cy)
ivMainImage.setImageBitmap(flippedBitmap)

For vertical flip :-

val cx = bitmap.width / 2f
val cy = bitmap.height / 2f
val flippedBitmap = bitmap.flip(1f, -1f, cx, cy)
ivMainImage.setImageBitmap(flippedBitmap)

###

For kotlin,

fun Bitmap.flip(): Bitmap {
    val matrix = Matrix().apply { postScale(-1f, 1f, width/2f, width/2f) }
    return Bitmap.createBitmap(this, 0, 0, width, height, matrix, true)
}

###

Horizontal and vertical flips for Bitmap bms (source).

Matrix matrix = new Matrix();
// for horizontal flip
matrix.setScale(-1, 1);
matrix.postTranslate( bms.getWidth(),0);
// for vertical flip
matrix.setScale( 1,-1);
matrix.postTranslate( 0, bms.getHeight());
Bitmap bm = Bitmap.createBitmap( bms, 0, 0, bms.getWidth(), bms.getHeight(), matrix, true);

###

Its all about the matrix you use. To flip it around the x axes, use [[-1,0],[0, 1]]. For the y axes, use [[1,0],[0,-1]]. The important thing here is that the absolute value of the determinant is 1, so it won’t scale. And the – basically inverses the location around the given axes.

Leave a Reply

Your email address will not be published. Required fields are marked *