Java图片处理 Java基础之简单的图片处理

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Java图片处理 Java基础之简单的图片处理

朝如青丝·暮成雪   2021-04-30 我要评论
想了解Java基础之简单的图片处理的相关内容吗,朝如青丝·暮成雪在本文为您仔细讲解Java图片处理的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:Java图片处理,java处理图片,下面大家一起来学习吧。

一、前言

先使用一个模板图片,在图片上添加图片或者文字都可以。

二、依赖

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.18</version>
    <optional>true</optional>
</dependency>

三、封装数据类

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.awt.*;

/**
 * 坐标数据
 * @author tyg
 * @date 2021-04-23 14:33
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class PositionPO {

    /** 显示的数据 */
    private Object data;
    /** X轴坐标 */
    private float x;
    /** Y轴坐标 */
    private float y;
    /** 宽度 */
    private float w;
    /** 高度 */
    private float h;
    /** 字体 */
    private Font font;

    public PositionPO(Object data, float x, float y, float w, float h) {
        this.data = data;
        this.x = x;
        this.y = y;
        this.w = w;
        this.h = h;
    }

    public PositionPO(Object data, float x, float y) {
        this.data = data;
        this.x = x;
        this.y = y;
    }

    public PositionPO(Object data, float x, float y, Font font) {
        this.data = data;
        this.x = x;
        this.y = y;
        this.font = font;
    }

    public PositionPO(float x, float y, float w, float h) {
        this.x = x;
        this.y = y;
        this.w = w;
        this.h = h;
    }
}
import com.yt.distributor.po.pdf.PositionPO;
import lombok.Data;

import java.util.List;

/**
 * 邀请海报
 * @author tyg
 * @date 2021-04-24 14:52
 */
@Data
public class ImageHandlePO {

    /** 文字 */
    private List<PositionPO> textList;
    /** 图片 */
    private List<PositionPO> imageList;

    public ImageHandlePO(List<PositionPO> textList, List<PositionPO> imageList) {
        this.textList = textList;
        this.imageList = imageList;
    }
}

四、常量类

package com.yt.distributor.constant;

import org.springframework.core.io.ClassPathResource;

import java.awt.*;
import java.io.File;
import java.io.IOException;

/**
 * 图片常量
 * @author tyg
 * @date 2021-04-24 16:59
 */
public class ImageConstant {

    /** 透明度 */
    public static final float PELLUCIDITY = 1.0F;
    /** 字体 */
    public static final Font FONT = new Font("微软雅黑", Font.BOLD, 18);
    /** 邀请海报模板图片源文件 */
    public static File POSTER_SOURCE_FILE;
    /** 图片默认格式 */
    public static final String FORMAT = "png";

    static{
        try {
            ClassPathResource resource = new ClassPathResource("conf/poster.jpg");
            POSTER_SOURCE_FILE = resource.getFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

五、图像处理类

import com.yt.distributor.constant.ImageConstant;
import com.yt.distributor.po.img.ImageHandlePO;
import com.yt.distributor.po.pdf.PositionPO;
import lombok.extern.log4j.Log4j2;
import net.dreamlu.mica.core.utils.$;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * 图像合成处理
  * 注:图像处理的原点坐标在:左上角,距离为像素
 * @author tyg
 * @date 2021-04-24 17:45
 */
@Log4j2
public class PictureSynthesis {

    /** 原模板图片文件 */
    public static final Object FLAG = true;
    /** 原模板图片文件 */
    public static File sourceFile;


    public static void main(String[] args) throws IOException {
        // 生成二维码
        BufferedImage image = QrCodeGenerator.generateQrCode("http://www.baiud.com/index.html?id=13", 192, 192);
        // 图片
        List<PositionPO> imageList = new ArrayList<>();
        imageList.add(new PositionPO(ImageIO.read(new URL("https://thirdwx.qlogo.cn/mmopen/vi_32/AtTHbmrMict69vB7ocDMbstibgvwxpK51bOoNkQiaemrImnicUK2L9OoF1JibHiceLwY53ibiaicJQibuEwLNFicJiaYcQHRiaw/132")), 120F, 1688F, 192F, 192F));
        imageList.add(new PositionPO(image, 785F, 1632F, 192F , 192F));

        // 文字
        Font font = new Font("微软雅黑", Font.PLAIN, 30);
        List<PositionPO> textList = new ArrayList<>();
        textList.add(new PositionPO("颜魔子辰", 120F, 1660F, font));
        textList.add(new PositionPO("颜魔子辰邀请您", 336F, 1758F, font));
        textList.add(new PositionPO("加入某某小店。", 336F, 1796F, font));
        textList.add(new PositionPO("长按可识别二维码", 760F, 1880F, font));

        String sourcePath = "C:\\Users\\Administrator\\Desktop\\poster.jpg";
        String savePath = "C:\\Users\\Administrator\\Desktop\\poster-handle.jpg";
        // 输出水印图片
        handleImage(new ImageHandlePO(textList, imageList), new File(sourcePath), savePath);
    }

    /**
     * 图片处理(返回输入流)
     * @param po            处理的数据
     * @author tyg
     * @date 2021-04-14 15:45
     * @return InputStream
     */
    public static InputStream handleImage(ImageHandlePO po, File sourceFile) throws IOException {
        synchronized (FLAG) {
            PictureSynthesis.sourceFile = sourceFile;
            //图片处理,导出数据
            BufferedImage image = watermark(po);
            return getInputStream(image);
        }
    }

    /**
     * 图片处理(输出到文件中)
     * @param po            处理的数据
     * @param saveFilePath  保存的路径
     * @author tyg
     * @date   2017年9月6日下午12:53:11
     */
    public static void handleImage(ImageHandlePO po, File sourceFile, String saveFilePath) throws IOException {
        synchronized (FLAG) {
            PictureSynthesis.sourceFile = sourceFile;
            // 构建叠加层
            BufferedImage buffImg = watermark(po);
            // 输出水印图片
            generateWaterFile(buffImg, saveFilePath);
        }
    }

    /**
     * 构建叠加层
     * 图像处理的原点坐标在:左上角
     * @param po 处理的数据
     * @throws IOException io异常
     * @return BufferedImage 生成水印并返回java.awt.image.BufferedImage
     */
    private static BufferedImage watermark(ImageHandlePO po) throws IOException {
        // 获取底图
        BufferedImage buffImg = ImageIO.read(sourceFile);
        // 创建Graphics2D对象,用在底图对象上绘图
        Graphics2D g2d = buffImg.createGraphics();

        // 处理文字
        if ($.isNotEmpty(po.getTextList())){
            for (PositionPO pp : po.getTextList()){
                g2d.setColor(Color.black);
                g2d.setFont( pp.getFont() == null ? ImageConstant.FONT : pp.getFont());
                g2d.drawString(pp.getData().toString(), pp.getX(), pp.getY());
            }
        }
        // 处理图片
        if ($.isNotEmpty(po.getImageList())){
            for (PositionPO pp : po.getImageList()){
                BufferedImage image = (BufferedImage) pp.getData();
                // 获取层图的宽度
                int width = pp.getW() <= 0 ? image.getWidth() : (int) pp.getW();
                // 获取层图的高度
                int height = pp.getH() <= 0 ? image.getHeight() : (int) pp.getH();
                // 在图形和图像中实现混合和透明效果
                g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, ImageConstant.PELLUCIDITY));
                // 绘制
                g2d.drawImage(image, (int)pp.getX(), (int)pp.getY(), width, height, null);
            }
        }
        // 释放图形上下文使用的系统资源
        g2d.dispose();
        return buffImg;
    }

    /**
     * 输出水印图片
     * @param buffImg  图像加水印之后的BufferedImage对象
     * @param savePath 图像加水印之后的保存路径
     * @author tyg
     * @date 2021-04-24 16:19
     */
    private static void generateWaterFile(BufferedImage buffImg, String savePath) {
        int temp = savePath.lastIndexOf(".") + 1;
        try {
            ImageIO.write(buffImg, savePath.substring(temp), new File(savePath));
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }

    /**
     * 获取系统所支持的字体
     * @author tyg
     * @date 2021-04-24 16:19
     */
    private static void getFonts(){
        String[] fontNames=GraphicsEnvironment.getLocalGraphicsEnvironment().
                getAvailableFontFamilyNames();
        for(String fontName:fontNames){
            System.out.println(fontName);
        }
    }

    /**
     * 获取图片输入流
     * @param image	图片
     * @author tyg
     * @date 2021-04-14 17:14
     * @return java.io.InputStream
     */
    public static InputStream getInputStream(BufferedImage image){
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            ImageIO.write(image, ImageConstant.FORMAT, os);
            return new ByteArrayInputStream(os.toByteArray());
        } catch (IOException e) {
            log.error("提示:",e);
        }
        return null;
    }

}

六、效果图

以上的数据都是按图片的1080*1920像素来设定的,下面红框部分是动态生成的。

在这里插入图片描述

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们