Last active
September 20, 2020 16:16
-
-
Save omkar-tenkale/3da22fd414737e6f1f55024367004fbc to your computer and use it in GitHub Desktop.
Java port of https://stackoverflow.com/questions/16702966/rotate-image-and-crop-out-black-borders/16778797#16778797
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Given width and height of a rectangle which is rotated from center by angle in radians, | |
//returns width and height of rectangle to crop from center of original image to eliminate the black borders | |
// https://i.stack.imgur.com/KWoeo.jpg | |
//Similar to this image above,input params are input's width and height,rotation in radians | |
//Output is pair.first = width of cropped image in B, pair.second = height of cropped image in B | |
//You can use the scaleCenterCrop function to crop the image bitmap on android | |
// Usage: | |
// Pair<Integer, Integer> pair = rotatedRectWithMaxArea(originalImageWidth, originalImageHeight, Math.toRadians(rotation)); | |
public Pair<Integer,Integer> rotatedRectWithMaxArea(int w, int h, double angle){ | |
double height=0; | |
double width=0; | |
if(w<=0 || h<=0){ | |
return new Pair<>((int) width, (int) height); | |
} | |
int quadrant = (int) (Math.floor(angle / (Math.PI / 2))) & 3; | |
double sign_alpha = ((quadrant & 1) == 0) ? angle : (Math.PI - angle); | |
double alpha = (sign_alpha % Math.PI + Math.PI) % Math.PI; | |
double bb_w = w * Math.cos(alpha) + h * Math.sin(alpha); | |
double bb_h = w * Math.sin(alpha) + h * Math.cos(alpha); | |
double gamma = (w < h) ? (Math.atan2(bb_w, bb_w)) : (Math.atan2(bb_w, bb_w)); | |
double delta = Math.PI - alpha - gamma; | |
int length = (w < h) ? h : w; | |
double d = length * Math.cos(alpha); | |
double a = d * Math.sin(alpha) / Math.sin(delta); | |
double y = a * Math.cos(gamma); | |
double x = y * Math.tan(gamma); | |
return new Pair<>((int)(bb_w - 2 * x),(int)(bb_h - 2 * y)); | |
} | |
static public Bitmap scaleCenterCrop(Bitmap source,int newWidth, int newHeight) { | |
float centerX = (newWidth - source.getWidth()) * 0.5f; | |
float centerY = (newHeight- source.getHeight()) * 0.5f; | |
Bitmap dest = Bitmap.createBitmap(newWidth, newHeight,Bitmap.Config.ARGB_8888); | |
Canvas canvas = new Canvas(dest); | |
canvas.drawBitmap(source, centerX,centerY,new Paint()); | |
return dest; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment