Java 生成透明图片

/ 默认分类 / 没有评论 / 1101浏览

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;
import javax.swing.*;
import java.awt.*;
import java.awt.font.FontRenderContext;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

/**
 * 图片处理工具类
 *
 * @author maruifu
 */
public class ImageUtils {
    private static final Logger log = LoggerFactory.getLogger(ImageUtils.class);

    public static void main(String[] args) {
        String text = "我是小马哥";
        String filePath = "/Users/maruifu/Desktop/1.png"; //生成指定文字透明图片
        createImage(text, filePath, "宋体", 45); //设置指定图片透明 //setColorInRange(path,path);
    }

    /**
     * 动态获取文字宽高
     *
     * @param text 文字
     * @param font 字体
     * @return
     */
    private static int[] getWidthAndHeight(String text, Font font) {
        Rectangle2D r = font.getStringBounds(text, new FontRenderContext(AffineTransform.getScaleInstance(1, 1), false, false));
        int unitHeight = (int) Math.floor(r.getHeight()); // 获取整个str用了font样式的宽度这里用四舍五入后+1保证宽度绝对能容纳这个字符串作为图片的宽度 
        int width = (int) Math.round(r.getWidth()) + 1; // 把单个字符的高度+3保证高度绝对能容纳字符串作为图片的高度 
        int height = unitHeight + 3;
        return new int[]{width, height};
    }

    /**
     * 生成指定文字透明图片
     *
     * @param text     文字内容 "我是小马哥"
     * @param filePath 生成地址 "/Users/maruifu/Desktop/123.png"
     * @param fontName 字体名称 "宋体"
     * @param fontSize 字体大小 45
     */
    public static void createImage(String text, String filePath, String fontName, int fontSize) {
        ImageOutputStream imageOutputStream = null;
        try {
            Font font = new Font(fontName, Font.BOLD, fontSize); // 获取font的样式应用在输出内容上整个的宽高 
            int[] arr = getWidthAndHeight(text, font); // 设置背景宽高 
            int width = arr[0];
            int height = arr[1];
            BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR); // 获取图形上下文对象 
            Graphics2D graphics = (Graphics2D) image.getGraphics();
            graphics.clearRect(0, 0, width, height); // 填充 
            graphics.fillRect(0, 0, width, height); // 设定字体大小及样式 
            graphics.setFont(font); // 字体颜色 
            graphics.setColor(Color.BLACK); // 描绘字符串 
            graphics.drawString(text, 0, font.getSize()); // 图片透明度 
            setTransparency(image, graphics);
            File jpgFile = new File(filePath);
            if (!jpgFile.exists()) {
                jpgFile.createNewFile();
            }
            // 创建图片输出流对象,基于文件对象 
            imageOutputStream = ImageIO.createImageOutputStream(jpgFile); // 写入 
            ImageIO.write(image, FilenameUtils.getExtension(filePath), imageOutputStream);
        } catch (IOException e) {
            log.error("生成图片失败{}", e);
        } finally { // 关闭流 
            IOUtils.closeQuietly(imageOutputStream);
        }

    }

    private static void setTransparency(BufferedImage image, Graphics2D graphics) {
        int alpha = 0; // 外层遍历是Y轴的像素 
        for (int y = image.getMinY(); y < image.getHeight(); y++) { // 内层遍历是X轴的像素 
            for (int x = image.getMinX(); x < image.getWidth(); x++) {
                int rgb = image.getRGB(x, y); // 对当前颜色判断是否在指定区间内 
                if (colorInRange(rgb)) {
                    alpha = 0;
                } else {
                    // 设置为不透明 
                    alpha = 255;
                } // #AARRGGBB 最前两位为透明度 
                rgb = (alpha << 24) | (rgb & 0x00ffffff);
                image.setRGB(x, y, rgb);
            }
        }
        // 绘制设置了RGB的新图片 
        graphics.drawImage(image, 0, 0, null);
        // 释放画笔 
        graphics.dispose();
    }

    /**
     * 设置指定图片透明
     *
     * @param sourcePath 源文件地址
     * @param targetPath 新文件地址
     */
    public static void setColorInRange(String sourcePath, String
            targetPath) {
        try {
            BufferedImage image = ImageIO.read(new File(sourcePath)); // 高度和宽度 
            int height = image.getHeight();
            int width = image.getWidth();
            // 生产背景透明和内容透明的图片
            ImageIcon imageIcon = new ImageIcon(image);
            BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR);
            // 获取画笔
            Graphics2D g2D = (Graphics2D) bufferedImage.getGraphics();
            // 绘制Image的图片
            g2D.drawImage(imageIcon.getImage(), 0, 0, null);
            // 图片透明
            setTransparency(bufferedImage, g2D);
            // 生成图片为PNG
            ImageIO.write(bufferedImage, FilenameUtils.getExtension(sourcePath), new File(targetPath));

        } catch (IOException e) {
            log.error("设置图片透明失败{}", e);
        }


    }

    /**
     * 判断是背景还是内容
     *
     * @param color
     * @return
     */
    public static boolean colorInRange(int color) {
        // 色差范围0~255 
        int colorRange = 210;
        // 获取color(RGB)中R位
        int red = (color & 0xff0000) >> 16;
        // 获取color(RGB)中G位 
        int green = (color & 0x00ff00) >> 8;
        // 获取color(RGB)中B位
        int blue = (color & 0x0000ff);
        // 通过RGB三分量来判断当前颜色是否在指定的颜色区间内 
        if (red >= colorRange && green >= colorRange && blue >= colorRange) {
            return true;
        }
        return false;
    }
}