java.awt.image.RasterFormatException: (y + height) is outside of Raster
Я хочу обрезать изображение и получить квадратное изображение. Пример:
Исходное изображение: 1000x667
Хочу получить: 667х667
Из такого изображения
Получить такой
Чтобы изображение обрезалось по центру
Мой код:
public static void main(String[] args) throws IOException {
try {
BufferedImage image = ImageIO.read(new File("/home/someone/test/1.jpeg"));
int type = image.getType() == 0? BufferedImage.TYPE_INT_ARGB : image.getType();
int x = 0,y=0,w=0,h=0;
int width = image.getWidth();
int height = image.getHeight();
int delta = (width - height)/2;
if (delta != 0){
if(delta > 0){
x = delta;
y = height;
w = height;
h = height;
}
if(delta < 0){
x = 0;
y = height + delta;
w = width;
h = width;
}
image = image.getSubimage(x,y,w,h);
ImageIO.write(image,"jpg",new File( "/home/someone/test/1a.jpeg"));
}
} catch (RasterFormatException e){
System.out.println(e);
}
}
Получаю такую ошибку:
java.awt.image.RasterFormatException: (y + height) is outside of Raster
Знаю что ошибка возникает в этой строке
image = image.getSubimage(x,y,w,h);
Ответы (1 шт):
Автор решения: hunter
→ Ссылка
Моя ошибка была в том что за начальной точкой координат (x=0 u y=0) брал левую-нижнюю угол. А надо было левую-верхнюю взять
Исправленный код:
public static void main(String[] args) throws IOException {
try {
BufferedImage image = ImageIO.read(new File("/home/rahimov/test/4.jpeg"));
int type = image.getType() == 0? BufferedImage.TYPE_INT_ARGB : image.getType();
int x = 0, y=166,w=667,h=667;
BufferedImage image2 = image.getSubimage(x,y,w,h);
ImageIO.write(image2,"jpg",new File( "/home/rahimov/test/4b.jpeg"));
} catch (RasterFormatException e){
System.out.println(e);
}
}

