Как обрезать изображение в Java? - PullRequest
0 голосов
/ 28 мая 2018

Я использую Java для обрезки изображения при загрузке файла, я устанавливаю значение и пытаюсь обрезать, но не получаю правильный размер изображения, как я ожидал

Это мой код: ( updated )

private BufferedImage cropImageSquare(byte[] image) throws IOException {        
    InputStream in = new ByteArrayInputStream(image);
    BufferedImage originalImage = ImageIO.read(in);

    System.out.println("Original Image Dimension: "+originalImage.getWidth()+"x"+originalImage.getHeight());            

    BufferedImage croppedImage = originalImage.getSubimage(300, 150, 500, 500);
    System.out.println("Cropped Image Dimension: "+croppedImage.getWidth()+"x"+croppedImage.getHeight());


     return croppedImage;
}

мое фото:

enter image description here

Я хочу обрезать изображение, как указано выше (красная линия), но моеКод кажется неправильным.

Как обрезать изображение, как ожидается?

Ответы [ 2 ]

0 голосов
/ 28 мая 2018

Я хочу обрезать изображение, как показано выше (красная линия), но мой код кажется неправильным.

Итак, ваше входное изображение 1024x811, а ваше "целевое" изображение928x690, что примерно равно 0.906x0.8509 уменьшению / разнице, поэтому реальный вопрос ... какой из них является правильным значением?

В результате моего тестирования, основанного на этом изображении, 0.8509 производитлучший результат

FromTo

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

public class Test {

    public static void main(String[] args) throws IOException {
        BufferedImage crop = new Test().crop(0.8509);
        System.out.println(crop.getWidth() + "x" + crop.getHeight());
        ImageIO.write(crop, "jpg", new File("Square.jpg"));
    }

    public BufferedImage crop(double amount) throws IOException {
        BufferedImage originalImage = ImageIO.read(Test.class.getResource("Cat.jpg"));
        int height = originalImage.getHeight();
        int width = originalImage.getWidth();

        int targetWidth = (int)(width * amount);
        int targetHeight = (int)(height * amount);
        // Coordinates of the image's middle
        int xc = (width - targetWidth) / 2;
        int yc = (height - targetHeight) / 2;

        // Crop
        BufferedImage croppedImage = originalImage.getSubimage(
                        xc, 
                        yc,
                        targetWidth, // widht
                        targetHeight // height
        );
        return croppedImage;
    }

}

Теперь это не делает никаких проверок (xc + targetWidth > imageWidth), но я уверен, что вы можете заполнить это

0 голосов
/ 28 мая 2018

Код работает нормально для меня.

public class Test {

    public static void main( String[] args ) throws IllegalAccessException, InstantiationException {

        try{
              BufferedImage image = ImageIO.read(new File("C:\\Users\\guptab\\Pictures\\American.png"));
              ByteArrayOutputStream baos = new ByteArrayOutputStream();
              ImageIO.write(image, "png", baos);
             byte[] res=baos.toByteArray();
             image = new Test().cropImageSquare(res);

        } 
        catch(Exception e) {
             e.printStackTrace();
        System.out.println("Error");
        }
        }



    private BufferedImage cropImageSquare(byte[] image) throws IOException {        
        InputStream in = new ByteArrayInputStream(image);
        BufferedImage originalImage = ImageIO.read(in);

        System.out.println("Original Image Dimension: "+originalImage.getWidth()+"x"+originalImage.getHeight());            

        BufferedImage croppedImage = originalImage.getSubimage(300, 150, 300, 600);
        System.out.println("Cropped Image Dimension: "+croppedImage.getWidth()+"x"+croppedImage.getHeight());


         return croppedImage;
    }
}

Вывод:

Original Image Dimension: 1279x1023
Cropped Image Dimension: 300x600

Определение метода getSubImage:

BufferedImage java.awt.image.BufferedImage.getSubimage(int x, int y, int w, int h)


Returns a subimage defined by a specified rectangular region. The returned BufferedImage shares the same data array as the original image.
Parameters:x the X coordinate of the upper-left corner of the specified rectangular regiony the Y coordinate of the upper-left corner of the specified rectangular regionw the width of the specified rectangular regionh the height of the specified rectangular regionReturns:a BufferedImage that is the subimage of this BufferedImage.

Итак, int x и inty (Первые два параметра - это координаты изображения, а не размеры), только int w, int h (последние два параметра) - это размеры изображения, которое работает нормально.

...