前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Java 生成透明图片

Java 生成透明图片

作者头像
IT小马哥
修改2023-02-06 09:09:26
1K0
修改2023-02-06 09:09:26
举报
文章被收录于专栏:Java TaleJava Tale

设置图片透明

代码语言:txt
复制
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 ImageUtils1 {





    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;

    }
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2022-12-30,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
图片处理
图片处理(Image Processing,IP)是由腾讯云数据万象提供的丰富的图片处理服务,广泛应用于腾讯内部各产品。支持对腾讯云对象存储 COS 或第三方源的图片进行处理,提供基础处理能力(图片裁剪、转格式、缩放、打水印等)、图片瘦身能力(Guetzli 压缩、AVIF 转码压缩)、盲水印版权保护能力,同时支持先进的图像 AI 功能(图像增强、图像标签、图像评分、图像修复、商品抠图等),满足多种业务场景下的图片处理需求。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档