'Crop youtube type image in Java

I have a difficulty cropping the image in Java. I have image that has black lines up and down. The image looks like this : Image

I want to remove the black frame from the image and the width to remain the same. Please send me some solution to my problem. I tried something like this, but it crops only the bottom of the image.

 BufferedImage originalImg = ImageIO.read(
                    new File(imageLocation));

            // Fetching and printing alongside the
            // dimensions of original image using getWidth()
            // and getHeight() methods
            System.out.println("Original Image Dimension: "
                    + originalImg.getWidth()
                    + "x"
                    + originalImg.getHeight());

            // Creating a subimage of given dimensions
            BufferedImage SubImg
                    = originalImg.getSubimage(0,0,originalImg.getWidth(), 217);


            // Printing Dimensions of new image created
            System.out.println("Cropped Image Dimension: "
                    + SubImg.getWidth() + "x"
                    + SubImg.getHeight());

            // Creating new file for cropped image by
            // creating an object of File class
            File outputfile
                    = new File(defaultPath+"crop_Image.jpg");

//            // Writing image in new file created
            ImageIO.write(SubImg, "jpg", outputfile);

            // Display message on console representing
//            // proper execution of program
            System.out.println(
                    "Cropped Image created successfully");
        }


Solution 1:[1]

You can use getRGB and setRGB to copy image area to the new image.

import java.awt.image.BufferedImage;

public class ImageUtil {
    
    public static BufferedImage crop(BufferedImage image, int top, int right, int bottom, int left) {
        int newWidth = image.getWidth() - left - right;
        int newHeight = image.getHeight() - top - bottom;
        
        int[] rgb = image.getRGB(left, top, newWidth, newHeight, null, 0, newWidth);
        
        BufferedImage newImage = new BufferedImage(newHeight, newHeight, BufferedImage.TYPE_INT_ARGB);
        
        newImage.setRGB(0, 0, newWidth, newHeight, rgb, 0, newWidth);
        
        return newImage;
    }
    
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mikhail Yevchenko