标签:new draw server try exce write phi wim file
import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.File; import javax.imageio.ImageIO; import javax.swing.ImageIcon; public class ImageUtil { /** * 图片去白色的背景,并裁切 * * @param image 图片 * @param range 范围 1-255 越大 容错越高 去掉的背景越多 * @return 图片 * @throws Exception 异常 */ public static BufferedImage transferAlpha(BufferedImage bufferedImage, int range) throws Exception { BufferedImage sub = null; try { ImageIcon imageIcon = new ImageIcon(bufferedImage); Graphics2D g2D = (Graphics2D) bufferedImage.getGraphics(); g2D.drawImage(imageIcon.getImage(), 0, 0, imageIcon .getImageObserver()); int alpha = 0; int minX = bufferedImage.getWidth(); int minY = bufferedImage.getHeight(); int maxX = 0; int maxY = 0; 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); if (((255 - R) < range) && ((255 - G) < range) && ((255 - B) < range)) { //去除白色背景; rgb = ((alpha + 1) << 24) | (rgb & 0x00ffffff); } else { minX = minX <= j2 ? minX : j2; minY = minY <= j1 ? minY : j1; maxX = maxX >= j2 ? maxX : j2; maxY = maxY >= j1 ? maxY : j1; } bufferedImage.setRGB(j2, j1, rgb); } } int width = maxX - minX; int height = maxY - minY; sub = bufferedImage.getSubimage(minX, minY, width, height); ImageIO.write(sub, "png", new File("D:/new.png")); } catch (Exception e) { e.printStackTrace(); throw e; } return sub; } }
去掉白色背景,并剪切成透明背景。
标签:new draw server try exce write phi wim file
原文地址:http://www.cnblogs.com/tietazhan/p/6110550.html