java图片局部透明

来源:互联网 发布:草图大师 mac 破解 编辑:程序博客网 时间:2024/04/30 00:03
/**     * 对图片中的 黑色或白色进行透明化处理     *      * @param sourcePath     *            原始图     * @param targetPath     *            目标图,为null时在原始图同级目录下生成目标图     * @param type     *            B:黑色 W:白色     * @return 结果图字节数据组     */    public static byte[] transferAlpha(String sourcePath, String targetPath,            String type) {        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();        try {            File iFile = new File(sourcePath);            if (!iFile.exists()) {                return byteArrayOutputStream.toByteArray();            }            ImageIcon imageIcon = new ImageIcon(ImageIO.read(iFile));            BufferedImage bufferedImage = new BufferedImage(imageIcon                    .getIconWidth(), imageIcon.getIconHeight(),                    BufferedImage.TYPE_4BYTE_ABGR);            Graphics2D g2D = (Graphics2D) bufferedImage.getGraphics();            g2D.drawImage(imageIcon.getImage(), 0, 0, imageIcon                    .getImageObserver());            int alpha = 0;            int offset = 20;            boolean isBlack = type.equals("B");            for (int j1 = bufferedImage.getMinY(); j1 < bufferedImage                    .getHeight(); j1++) {                for (int j2 = bufferedImage.getMinX(); j2 < bufferedImage                        .getWidth(); j2++) {                    int rgb = bufferedImage.getRGB(j2, j1);                    int r = (rgb & 0xff0000) >> 16;                    int g = (rgb & 0xff00) >> 8;                    int b = rgb & 0xff;                    boolean checkW = ((255 - r) < offset)                            && ((255 - g) < offset) && ((255 - b) < offset);                    boolean checkB = (r < offset) && (g < offset) && (b < offset);                    if (isBlack ? checkB : checkW) {                        rgb = ((alpha + 1) << 24) | (rgb & 0x00ffffff);                    }                    bufferedImage.setRGB(j2, j1, rgb);                }            }            g2D.drawImage(bufferedImage, 0, 0, imageIcon.getImageObserver());            File targetFile = null;            if (targetPath == null) {                targetFile = new File(sourcePath);            } else {                targetFile = new File(targetPath);                if (!targetFile.exists()) {                    File dir = new File(targetFile.getParent());                    if (!dir.exists()) {                        boolean result = dir.mkdirs();                        if (!result) {                            log.info("crate file failed.path:" + dir.getPath());                         }                    }                }            }            ImageIO.write(bufferedImage, "png", targetFile);        } catch (Exception e) {            e.printStackTrace();        }        return byteArrayOutputStream.toByteArray();    }