实现两张图片的叠加

时间:2023-02-10 20:07:44

看了好多网上的图片叠加,说的最多的就是水印效果,但是我需要做的是两张图片完全重合的叠加,但是我的情况有点特殊,一张图片是从远程生成的,一张图片是本地生成的,所以在读图片的时候方法不一样,今天终于完成了,废话不多说,上代码:

首先是一个根据url网络网络url函数:

public static BufferedImage RequestImage(String imageurl) throws IOException{
   URL url = new URL(imageurl); 
try {
   InputStream inputStream=url.openStream();
BufferedImage  bufferedImage=ImageIO.read(inputStream);
return bufferedImage;
} catch (IOException e) {
e.printStackTrace();
return null;
}
 }

第二步是根据路径获取本地图片:

public BufferedImage getContourSurface(){
BufferedImage contourSurface = null;
String csImg =null;// obj.getString("imgUrl");
csImg = "//mapCache//1395916476971_0.png";
String csImgPath = getHttpRequest().getRealPath("/")+csImg;
try {
contourSurface = ImageIO.read(new FileInputStream(csImgPath));
} catch (IOException e) {
e.printStackTrace();
}
return contourSurface;
}


第三步是最关键的图片叠加

/**
 * 图片叠加
 * @param qualNum 图片质量 (0.25,0.5,0.75,1)最大值为1
 * @return 布尔类型
 */
@GET
@Path("/getBaseMap")
@Produces("image/png")
public String generateCompositeImage() {
String CompositeImage = getHttpRequest().getRealPath("/")
+ "contourSurface.jpg";
BufferedImage bimage = this.getBaseMap();
BufferedImage bimage2 = this.getContourSurface();
Graphics2D g = bimage.createGraphics();
g.drawImage((Image) bimage2, 0, 0, null);
g.dispose();
FileOutputStream out = null;
try {
out = new FileOutputStream(CompositeImage);
} catch (FileNotFoundException e) {
e.printStackTrace();
} // 先用一个特定的输出文件名
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bimage);

param.setQuality(1, true);

try {
encoder.encode(bimage, param);
} catch (ImageFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
OutputStream os = getHttpResponse().getOutputStream();
BufferedImage cs = ImageIO.read(new File(CompositeImage));
ImageIO.write(cs, "png", os);
os.flush();
os.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
}

//由于需要首先把图片生成本地图片才可以出图,如果不生成本地图片会报io异常:can't read input file,没办法,只能随后手动删除了
File file = new File(CompositeImage);
file.delete();
return null;

                效果图如下:(底图是ArcGIS服务的底图,上面是一张透明图片)
}实现两张图片的叠加

考虑到不想先生成本地图片,再删除,怕释放不了内存,所以又修改了一下代码,更精简了,主要是修改了叠加图片的函数,代码如下:

public String generateCompositeImage() {
BufferedImage baseMap = this.getBaseMap();
BufferedImage contourSurface = this.getContourSurface();
Graphics2D g = baseMap.createGraphics();
g.drawImage((Image) baseMap, 0, 0, null);
g.drawImage((Image) contourSurface, 0, 0, null);
g.dispose();
try {
OutputStream os = getHttpResponse().getOutputStream();
ImageIO.write(baseMap, "png", os);
ImageIO.write(contourSurface, "png", os);
os.flush();
os.close();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}