如何将多个头像合成类似QQ的群头像?
如上图所示,如何用java将单一的图片合成如上群头像。
在一个正方形外框中,要将多个图片合成上述图片。首先要做的是,依据圆相交的程度,计算圆心坐标与图片间空白区域大小。然后设计不同位置的切割模具,最后再将切割好的单一图片,在最终承载的图片上的指定位置绘制出来,即可完成整个合并过程。
参考代码如下:
private String exe5(List<String> urls) throws IOException {
int size = 220, wihteSize = 15;
int x = 130, y = 0;
BufferedImage imageNew = new BufferedImage(480, 480, BufferedImage.TYPE_INT_ARGB);
Graphics2D graphics2DNew = imageNew.createGraphics();
imageNew = graphics2DNew.getDeviceConfiguration().createCompatibleImage(480, 480, Transparency.TRANSLUCENT);
graphics2DNew.dispose();
graphics2DNew = imageNew.createGraphics();
graphics2DNew.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
for(int i = 0; i < urls.size(); i++) {
String fileName = urls.get(i);
Area tempArea = new Area();
Ellipse2D.Double circle0 = new Ellipse2D.Double(wihteSize, wihteSize, size - 2 * wihteSize, size - 2 * wihteSize);
if (i == 0) {
Ellipse2D.Double circle1 = new Ellipse2D.Double(-130, 112, size, size);
tempArea.add(new Area(circle0));
tempArea.subtract(new Area(circle1));
} else if (i == 1) {
Ellipse2D.Double circle1 = new Ellipse2D.Double(53, 148, size, size);
tempArea.add(new Area(circle0));
tempArea.subtract(new Area(circle1));
} else if(i == 2) {
Ellipse2D.Double circle1 = new Ellipse2D.Double(153, 0, size, size);
tempArea.add(new Area(circle0));
tempArea.subtract(new Area(circle1));
} else if(i == 3) {
Ellipse2D.Double circle1 = new Ellipse2D.Double(53, -148, size, size);
tempArea.add(new Area(circle0));
tempArea.subtract(new Area(circle1));
} else {
Ellipse2D.Double circle1 = new Ellipse2D.Double(-130, -112, size, size);
tempArea.add(new Area(circle0));
tempArea.subtract(new Area(circle1));
}
graphics2DNew.drawImage(drawImage(fileName, size, tempArea), x, y, null);
if(i == 0) {
x = 0;
y = 112;
} else if (i == 1) {
x = 54;
y = 260;
} else if (i == 2) {
x = 207;
y = 260;
} else if (i == 3) {
x = 260;
y = 112;
} else {
x = 260;
y = 112;
}
}
graphics2DNew.dispose();
……
}
/**
* 往模具中填充图片
* @param fileName
* @param size
* @return
* @throws IOException
*/
private BufferedImage drawImage(String fileName, int size, Area area) throws IOException {
BufferedImage bufferedImage = zipImage(fileName, size);
BufferedImage tempBufferImage = new BufferedImage(size, size, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = tempBufferImage.createGraphics();
tempBufferImage = g2d.getDeviceConfiguration().createCompatibleImage(size, size, Transparency.TRANSLUCENT);
g2d.dispose();
g2d = tempBufferImage.createGraphics();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setClip(area);
g2d.fill(area);
g2d.drawImage(bufferedImage, 0, 0, null);
g2d.dispose();
return tempBufferImage;
}
合成之后的图片会有一定的毛刺,但是缩小看之后,就无法分辨出来。因此,在客户端进行展示的时候,取缩略图就可以满足需求。