/** * 保持PNG背景的透明属性(背景不变黑) * @param response * @param byteArray * @throws Exception */ public static void convertTransparent(HttpServletResponse response,byte[] byteArray) throws Exception { response.setContentType("image/png"); //浏览器不要缓存 response.setDateHeader("expries", -1); response.setHeader("Cache-Control", "no-cache"); response.setHeader("Pragma", "no-cache"); ByteArrayInputStream inputStream = new ByteArrayInputStream(byteArray); BufferedImage image = null; image = ImageIO.read(inputStream); int w = image.getWidth(); int h = image.getHeight(); int minx = image.getMinTileX(); int miny = image.getMinTileY(); for (int i = minx; i < w; i++) { for (int j = miny; j < h; j++) { int rgb = image.getRGB(i, j); //以黑色为例 int RGB = Color.BLACK.getRGB(); int r = (rgb & 0xff0000) >> 16; int g = (rgb & 0xff00) >> 8; int b = (rgb & 0xff); int R = (RGB & 0xff0000) >> 16; int G = (RGB & 0xff00) >> 8; int B = (RGB & 0xff); if (Math.abs(R - r) < 75 && Math.abs(G - g) < 75 && Math.abs(B - b) < 75) { //0xff0000是红色的十六进制代码 image.setRGB(i, j, 0xff0000); } } ImageIO.write(image, "png", response.getOutputStream()); } }