本文主要是介绍签名图片去除背景,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
实现图片的背景虚化
/*** 去除图片背景色,图片透明化* @param image 原始图片* @param isCompress 是否压缩* @param imageWidth 压缩后的图片宽度: isCompress为true时不能为null* @param imageHeight 他所后的图片高度: isCompress为true时不能为null*/public static BufferedImage clearImageBackground(BufferedImage image, boolean isCompress, Integer imageWidth, Integer imageHeight) throws IOException {BufferedImage bufferedImage = new BufferedImage(IMG_WIDTH, IMG_HEIGHT, BufferedImage.TYPE_INT_ARGB);try {image = transImageBackgroundColor(image, Color.BLACK, Color.WHITE);if(isCompress){image = resizeImage(image, imageWidth, imageHeight);}bufferedImage = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB);int width = image.getWidth();int height = image.getHeight();for (int x = 0; x < width; x++) {for (int y = 0; y < height; y++) {int rgba = image.getRGB(x, y);if (isWhite(rgba)) {bufferedImage.setRGB(x, y, 0x00ffff);} else {bufferedImage.setRGB(x, y, rgba);}}}}catch (Exception e){e.printStackTrace();}return bufferedImage;}public static boolean isWhite(int rgba) {int r = (rgba >> 16) & 0xFF;int g = (rgba >> 8) & 0xFF;int b = rgba & 0xFF;return r > 250 && g > 250 && b > 250;}
修改图片背景
/*** 压缩图片* @param image 原始图片* @param filterColor 过滤的颜色(如:文字黑色不替换,则filterColor为BLACK)* @param color 新的背景颜色*/public static BufferedImage transImageBackgroundColor(BufferedImage image, Color filterColor, Color color) {for (int x = image.getMinX(); x < image.getWidth(); x++) {for (int y = image.getMinY(); y < image.getHeight(); y++) {int rgb = image.getRGB(x, y);Color src = new Color(rgb);if(filterColor.equals(src)){image.setRGB(x, y, src.getRGB());continue;}image.setRGB(x, y, color.getRGB());}}return image;}
图片压缩
/*** 压缩图片* @param image 原始图片* @param newWidth 压缩宽度* @param newHeight 压缩高度*/public static BufferedImage resizeImage(BufferedImage image, int newWidth, int newHeight) {Image imageSrc = image.getScaledInstance(newWidth, newHeight, Image.SCALE_AREA_AVERAGING);BufferedImage resizeImage = new BufferedImage(newWidth, newHeight, image.getType());Graphics2D g2d = resizeImage.createGraphics();g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);g2d.drawImage(imageSrc, 0, 0,newWidth, newHeight, null);g2d.dispose();return resizeImage;}
这篇关于签名图片去除背景的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!