Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flip a Bitmap image horizontally or vertically

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?

like image 372
activity Avatar asked Apr 08 '16 07:04

activity


People also ask

How do you flip a bitmap?

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.

How do you flip an image horizontally or vertically?

To flip an image or icon, simply: Select the object you would like to flip. Right click on that object, and select 'Flip Horizontal' or 'Flip Vertical'.”

What is flip vertically and horizontally?

You can flip the image, or turn it over like a card, by using the Flip Horizontally or Flip Vertically commands. These commands work on the whole image. To flip a selection, use the Flip Tool. To flip a layer, use the functions of the Layer → Transform menu or the Flip Tool.


2 Answers

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); 

Altogether:

public static Bitmap createFlippedBitmap(Bitmap source, boolean xFlip, boolean yFlip) {     Matrix matrix = new Matrix();     matrix.postScale(xFlip ? -1 : 1, yFlip ? -1 : 1, source.getWidth() / 2f, source.getHeight() / 2f);     return Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), matrix, true); } 
like image 170
weston Avatar answered Oct 04 '22 16:10

weston


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) 
like image 45
Mahesh Babariya Avatar answered Oct 04 '22 14:10

Mahesh Babariya