java 实现图片圆角处理、背景透明化

 更新时间:2021年11月15日 10:14:25   作者:孤独地搬砖  
这篇文章主要介绍了java 实现图片圆角处理、背景透明化,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

java 图片圆角处理、背景透明化

/**图片圆角处理,背景透明化
     * @param srcImageFile 原图片
     * @param result  处理后图片
     * @param type   图片格式
     * @param cornerRadius  720为圆角
     */
    public  void makeRoundedCorner(File srcImageFile, File result, String type, int cornerRadius) {        
        try {
            BufferedImage bi1 = ImageIO.read(srcImageFile);
            
            // 根据需要是否使用 BufferedImage.TYPE_INT_ARGB
            BufferedImage image = new BufferedImage(bi1.getWidth(), bi1.getHeight(),
                    BufferedImage.TYPE_INT_ARGB);
      
            Ellipse2D.Double shape = new Ellipse2D.Double(0, 0, bi1.getWidth(), bi1
                    .getHeight());
             
            Graphics2D g2 = image.createGraphics();
            image = g2.getDeviceConfiguration().createCompatibleImage(bi1.getWidth(), bi1.getHeight(), Transparency.TRANSLUCENT);
            g2 = image.createGraphics();
            g2.setComposite(AlphaComposite.Clear);
            g2.fill(new Rectangle(image.getWidth(), image.getHeight()));
            g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC, 1.0f));
            g2.setClip(shape);
            // 使用 setRenderingHint 设置抗锯齿
            g2 = image.createGraphics();
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g2.fillRoundRect(0, 0,bi1.getWidth(), bi1.getHeight(), cornerRadius, cornerRadius);
            g2.setComposite(AlphaComposite.SrcIn);
            g2.drawImage(bi1, 0, 0, bi1.getWidth(), bi1.getHeight(), null);
            g2.dispose();
            ImageIO.write(image, type, result);
        } catch (Exception e) {
            // TODO: handle exception
        }
    }

java 的图片处理解析

直接上效果图,现在有的需求就是把用户的头像,跟昵称嵌入到这个背景图中。

第一步,把头像切成圆角,背景透明的图片。

第二部,把第一步生成的图片,当成水印放到坐标的左边的红箭头的地方

第三部,创建文字水印,然后放入到右边的红箭头地方。

效果图如下:

由于需要thumbnailator组件支持

先导入maven

<dependency>
    <groupId>net.coobird</groupId>
    <artifactId>thumbnailator</artifactId>
    <version>0.4.8</version>
</dependency>

直接上代码:

package com.image;
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Point;
import java.awt.Transparency;
import java.awt.geom.Ellipse2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.geometry.Position;
public class ImageDo {
public static void main(String[] args) throws IOException {
//首先获取
makeRoundedCorner("C:/Users/luojie/Desktop/0.jpg", "C:/Users/luojie/Desktop/2.png", "png", 170);
//后续水印在背景图片的的x轴y轴的坐标
Position ab=  new Position() {
@Override
public Point calculate(int enclosingWidth, int enclosingHeight, int width, int height, int insetLeft,
int insetRight, int insetTop, int insetBottom) {
// TODO Auto-generated method stub
return new Point(89, 53);
}
};
//把生成的圆形图片变换成宽高142x142的图片
Thumbnails.of("C:/Users/luojie/Desktop/2.png").size(142, 142).toFile(
"C:/Users/luojie/Desktop/2_142x142.png");
//把生成的圆形图片,当水印贴到背景图中,ab为圆形图片应该到背景图的x轴y轴的坐标        
Thumbnails.of("C:/Users/luojie/Desktop/cmbg.png").size(1280, 1024).watermark(ab,
ImageIO.read(new File("C:/Users/luojie/Desktop/2_142x142.png")), 1f)
.outputQuality(0.8f).toFile("C:/Users/luojie/Desktop/image_watermark_bottom_right.jpg");
//给文字水印
pressText("C:/Users/luojie/Desktop/image_watermark_bottom_right.jpg", "WEIXINYONGHU", "Comic Sans MS", Font.BOLD, 30, Color.BLACK,275, 65, 1f);  
}
    /**  
     * 添加文字水印  
     * @param targetImg 目标图片路径,如:C://myPictrue//1.jpg  
     * @param pressText 水印文字, 如:中国证券网  
     * @param fontName 字体名称,    如:宋体  
     * @param fontStyle 字体样式,如:粗体和斜体(Font.BOLD|Font.ITALIC)  
     * @param fontSize 字体大小,单位为像素  
     * @param color 字体颜色  
     * @param x 水印文字距离目标图片左侧的偏移量,如果x<0, 则在正中间  
     * @param y 水印文字距离目标图片上侧的偏移量,如果y<0, 则在正中间  
     * @param alpha 透明度(0.0 -- 1.0, 0.0为完全透明,1.0为完全不透明)  
     */  
    public static void pressText(String targetImg,String pressText,String fontName,int fontStyle,int fontSize,Color color,int x,int y,float alpha){  
        try {  
            File file = new File(targetImg);  
            Image image = ImageIO.read(file);  
            int width = image.getWidth(null);  
            int height = image.getHeight(null);  
              
            BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);  
            Graphics2D g = bufferedImage.createGraphics();  
            g.drawImage(image,0,0, width, height, null);  
            g.setFont(new Font(fontName, fontStyle, fontSize));  
            g.setColor(color);  
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));  
              
            int width_wi = fontSize*getTextLength(pressText);  
            int height_wi = fontSize;                
            int widthDiff = width-width_wi;  
            int heightDiff = height-height_wi;  
            if(x<0){  
                x = widthDiff/2;  
            }else if(x>widthDiff){  
                x=widthDiff;  
            }  
              
            if(y<0){  
                y = heightDiff/2;  
            }else if(y>heightDiff){  
                y = heightDiff;  
            }  
            g.drawString(pressText, x, y+height_wi);//水印文件  
            g.dispose();  
            ImageIO.write(bufferedImage, "JPEG", file);  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
    }      
    
    /** 
     * 计算文字像素长度 
     * @param text 
     * @return 
     */  
    private static int getTextLength(String text){  
        int textLength = text.length();  
        int length = textLength;  
        for (int i = 0; i < textLength; i++) {  
            int wordLength = String.valueOf(text.charAt(i)).getBytes().length;  
            if(wordLength > 1){  
                length+=(wordLength-1);  
            }  
        }            
        return length%2==0 ? length/2:length/2+1;  
    }  
/*
* 圆角处理
* @param BufferedImage
* @param cornerRadius
* */
public static String makeRoundedCorner(String srcImageFile, String result, String type, int cornerRadius) {
   try {
       BufferedImage image = ImageIO.read(new File(srcImageFile));
//        int w = image.getWidth();
//        int h = image.getHeight();
       int w = image.getWidth();
       int h = image.getHeight();
       BufferedImage output = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
       Graphics2D g2 = output.createGraphics();
       
       output = g2.getDeviceConfiguration().createCompatibleImage(w, h, Transparency.TRANSLUCENT);
       g2.dispose();
       g2 = output.createGraphics();
       //这里绘画圆角矩形
//        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
//        g2.fillRoundRect(0, 0,w, h, cornerRadius, cornerRadius);
//        g2.setComposite(AlphaComposite.SrcIn);
       
       //这里绘画原型图
       Ellipse2D.Double shape = new Ellipse2D.Double(0, 0,w, h); 
       g2.setClip(shape);  
       
       g2.drawImage(image, 0, 0, w, h, null);
       g2.dispose();
       ImageIO.write(output, type, new File(result));
       return result;
   } catch (IOException e) {
       e.printStackTrace();
   }
   return null;
}
}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • RocketMQ中的消息发送与消费详解

    RocketMQ中的消息发送与消费详解

    这篇文章主要介绍了RocketMQ中的消息发送与消费详解,RocketMQ是一款高性能、高可靠性的分布式消息中间件,消费者是RocketMQ中的重要组成部分,消费者负责从消息队列中获取消息并进行处理,需要的朋友可以参考下
    2023-10-10
  • springboot使用swagger-ui 2.10.5 有关版本更新带来的问题小结

    springboot使用swagger-ui 2.10.5 有关版本更新带来的问题小结

    这篇文章主要介绍了springboot使用swagger-ui 2.10.5 有关版本更新带来的问题小结,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-12-12
  • SpringBoot初始教程之Servlet、Filter、Listener配置详解

    SpringBoot初始教程之Servlet、Filter、Listener配置详解

    本篇文章主要介绍了SpringBoot初始教程之Servlet、Filter、Listener配置详解,具有一定的参考价值,有兴趣的可以了解一下
    2017-09-09
  • springboot+mybatis-plus+oracle实现逻辑删除

    springboot+mybatis-plus+oracle实现逻辑删除

    最近在做一个前后端分离的小项目,需要删除用户表的用户,本文主要实现了springboot+mybatis-plus+oracle逻辑删除,具有一定的参考价值,感兴趣的可以了解一下
    2021-08-08
  • Java中的ThreadLocal功能演示示例

    Java中的ThreadLocal功能演示示例

    这篇文章主要介绍了Java中的ThreadLocal功能演示示例,帮助大家更好的理解和使用Java,感兴趣的朋友可以了解下
    2021-02-02
  • Java8新特性之lambda(动力节点Java学院整理)

    Java8新特性之lambda(动力节点Java学院整理)

    这篇文章主要介绍了Java8新特性之lambda(动力节点Java学院整理)表达式的相关知识,包括lambda语法方面的知识,非常不错,具有参考借鉴价值,需要的朋友参考下吧
    2017-06-06
  • springboot响应json null值过滤方式

    springboot响应json null值过滤方式

    这篇文章主要介绍了springboot响应json null值过滤方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-11-11
  • java数据结构基础:绪论

    java数据结构基础:绪论

    这篇文章主要介绍了Java的数据解构基础,希望对广大的程序爱好者有所帮助,同时祝大家有一个好成绩,需要的朋友可以参考下,希望能给你带来帮助
    2021-07-07
  • 详解用maven将dubbo工程打成jar包运行

    详解用maven将dubbo工程打成jar包运行

    这篇文章主要介绍了详解用maven将dubbo工程打成jar包运行,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-04-04
  • Java中list.contains()的用法及拓展

    Java中list.contains()的用法及拓展

    List集合相信大家在开发过程中几乎都会用到,有时候难免会遇到集合里的数据是重复的,需要进行去除,下面这篇文章主要给大家介绍了关于Java中list.contains()的用法及拓展的相关资料,需要的朋友可以参考下
    2023-03-03

最新评论