0

I need to put a random image inside a screen with given resolution (640x480, 1280x720, etc). I finished it in Java. In Android do not support the BufferedImage and Graphics2D, I wonder if there is a way to replace this code from Java to Android. Here is my code from Java:

public BufferedImage resizeImage(BufferedImage originalImage, int type){
    BufferedImage resizedImage = new BufferedImage(screenWidth, screenHeight, type);
    Graphics2D g = resizedImage.createGraphics();

    int imgWidth = originalImage.getWidth();
    int imgHeight = originalImage.getHeight();
    int newImgWidth = 0;
    int newImgHeight = 0;
    int X = 0;
    int Y = 0;

    if (imgWidth > screenWidth){
        // scale width to fit
        newImgWidth = screenWidth;

        //scale height to maintain aspect ratio
        newImgHeight = (newImgWidth * imgHeight) / imgWidth;
    }

    if (newImgHeight > screenHeight) {
        //scale height to fit instead
        newImgHeight = screenHeight;
        //scale width to maintain aspect ratio
        newImgWidth = (newImgHeight * imgWidth) / imgHeight;
    }

    if (imgWidth < screenWidth && imgHeight < screenHeight) {
        X = screenWidth/2 - imgWidth/2;
        Y = screenHeight/2 - imgHeight/2;

        g.drawImage(originalImage, X, Y, imgWidth, imgHeight, null);
        g.dispose();

        return resizedImage;
    }

    X = screenWidth/2 - newImgWidth/2;
    Y = screenHeight/2 - newImgHeight/2;

    g.drawImage(originalImage, X, Y, newImgWidth, newImgHeight, null);
    g.dispose();

    return resizedImage;
}

Thank you in advance!

Luong Truong
  • 1,953
  • 2
  • 27
  • 46

0 Answers0