1.将透明图主体居中
/**
* 将透明图主体居中
* @param file2
*/
private void imageInit(File file2) {
try {
BufferedImage bufferedImage = ImageIO.read(file2);
int xMin = bufferedImage.getWidth();
int xMax = 0;
int yMin = bufferedImage.getHeight();
int yMax = 0;
List<Coord> coordList = new ArrayList<>();
for (int i = 0; i < xMin; i++) {
for (int j = 0; j < yMin; j++) {
//透明底判断
if (bufferedImage.getRGB(i, j) >> 24 != 0) {
Coord coord = new Coord(i, j);
coordList.add(coord);
}
}
}
//取出最大和最小的xy(差值就是新图片的宽高)
for (Coord coord : coordList) {
int x = coord.x;
int y = coord.y;
if (x < xMin)
xMin = x;
if (x > xMax)
xMax = x;
if (y < yMin)
yMin = y;
if (y > yMax)
yMax = y;
}
//设置透明底
selectedImage = new BufferedImage(xMax - xMin, yMax - yMin, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics = selectedImage.createGraphics();
selectedImage = graphics.getDeviceConfiguration().createCompatibleImage(xMax - xMin, yMax - yMin, Transparency.TRANSLUCENT);
graphics.dispose();
//从原图中将像素点拿出来
for (int i = 0; i < xMax - xMin; i++) {
for (int j = 0; j < yMax - yMin; j++) {
selectedImage.setRGB(i,j,bufferedImage.getRGB(i+xMin,j+yMin));
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
处理前:
处理后: