Java操作图片

功能描述

  • 图片裁剪
  • 图片尺寸放大
  • 图片尺寸缩小
  • 图片尺寸重置
  • 图片灰化
  • 添加文字水印
  • 添加图片水印
package com.qiangesoft.watermark.utils;

import org.springframework.util.Assert;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import java.awt.*;
import java.awt.color.ColorSpace;
import java.awt.image.BufferedImage;
import java.awt.image.ColorConvertOp;
import java.io.*;
import java.util.Iterator;

/**
 * 图片操作
 */
public class ImageOperateUtil {

    /**
     * 裁剪图片
     *
     * @param sourcePath
     * @param targetPath
     * @param width
     * @param height
     * @throws IOException
     */
    public static void cropImage(String sourcePath, String targetPath, int width, int height) throws IOException {
        cropImage(sourcePath, targetPath, 0, 0, width, height);
    }

    public static void cropImage(String sourcePath, String targetPath, int x, int y, int width, int height) throws IOException {
        String sourceType = sourcePath.substring(sourcePath.lastIndexOf(".") + 1);
        String targetType = targetPath.substring(targetPath.lastIndexOf(".") + 1);
        try (ImageInputStream iis = ImageIO.createImageInputStream(new File(sourcePath));
             FileOutputStream fos = new FileOutputStream(targetPath)) {
            cropImage(iis, fos, sourceType, targetType, x, y, width, height);
        }
    }

    /**
     * 裁剪图片
     *
     * @param file
     * @param outputStream
     * @param width
     * @param height
     * @throws IOException
     */
    public static void cropImage(MultipartFile file, OutputStream outputStream, int width, int height) throws IOException {
        cropImage(file, outputStream, 0, 0, width, height);
    }

    public static void cropImage(MultipartFile file, OutputStream outputStream, int x, int y, int width, int height) throws IOException {
        String originalFilename = file.getOriginalFilename();
        Assert.notNull(originalFilename, "文件非法");
        String sourceType = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        try (ImageInputStream iis = ImageIO.createImageInputStream(file.getInputStream())) {
            cropImage(iis, outputStream, sourceType, sourceType, x, y, width, height);
        }
    }

    private static void cropImage(ImageInputStream inputStream, OutputStream outputStream, String sourceType, String targetType, int x, int y, int width, int height) throws IOException {
        // 读取图片
        Iterator<ImageReader> readerIterator = ImageIO.getImageReadersByFormatName(sourceType);
        Assert.isTrue(readerIterator.hasNext(), "图片文件格式错误");
        ImageReader imageReader = readerIterator.next();
        imageReader.setInput(inputStream);

        // 裁剪图片
        ImageReadParam param = imageReader.getDefaultReadParam();
        // 从左上角开始裁剪
        param.setSourceRegion(new Rectangle(x, y, width, height));
        BufferedImage bufferedImage = imageReader.read(0, param);

        // 保存新图片
        ImageIO.write(bufferedImage, targetType, outputStream);
    }

    /**
     * 按倍率缩小图片
     *
     * @param sourcePath
     * @param targetPath
     * @param ratio
     * @throws IOException
     */
    public static void reduceImageByRatio(String sourcePath, String targetPath, int ratio) throws IOException {
        String fileType = targetPath.substring(targetPath.lastIndexOf(".") + 1);
        try (FileInputStream inputStream = new FileInputStream(sourcePath);
             FileOutputStream outputStream = new FileOutputStream(targetPath)) {
            reduceImageByRatio(inputStream, outputStream, ratio, fileType);
        }
    }

    /**
     * 按倍率缩小图片
     *
     * @param file
     * @param outputStream
     * @param ratio
     * @throws IOException
     */
    public static void reduceImageByRatio(MultipartFile file, OutputStream outputStream, int ratio) throws IOException {
        String originalFilename = file.getOriginalFilename();
        Assert.notNull(originalFilename, "文件非法");
        String fileType = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        try (InputStream inputStream = file.getInputStream()) {
            reduceImageByRatio(inputStream, outputStream, ratio, fileType);
        }
    }

    private static void reduceImageByRatio(InputStream inputStream, OutputStream outputStream, int ratio, String sourceType) throws IOException {
        // 构造Image对象
        BufferedImage sourceImage = ImageIO.read(inputStream);
        int width = sourceImage.getWidth() / ratio;
        int height = sourceImage.getHeight() / ratio;

        resizeImage(sourceImage, outputStream, width, height, sourceType);
    }

    /**
     * 按倍率放大图片
     *
     * @param sourcePath
     * @param targetPath
     * @param ratio
     * @throws IOException
     */
    public static void enlargeImageByRatio(String sourcePath, String targetPath, int ratio) throws IOException {
        String fileType = targetPath.substring(targetPath.lastIndexOf(".") + 1);
        try (FileInputStream inputStream = new FileInputStream(sourcePath);
             FileOutputStream outputStream = new FileOutputStream(targetPath)) {
            enlargeImageByRatio(inputStream, outputStream, ratio, fileType);
        }
    }

    /**
     * 按倍率放大图片
     *
     * @param file
     * @param outputStream
     * @param ratio
     * @throws IOException
     */
    public static void enlargeImageByRatio(MultipartFile file, OutputStream outputStream, int ratio) throws IOException {
        String originalFilename = file.getOriginalFilename();
        Assert.notNull(originalFilename, "文件非法");
        String fileType = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        try (InputStream inputStream = file.getInputStream()) {
            enlargeImageByRatio(inputStream, outputStream, ratio, fileType);
        }
    }

    private static void enlargeImageByRatio(InputStream inputStream, OutputStream outputStream, int ratio, String fileType) throws IOException {
        // 构造Image对象
        BufferedImage sourceImage = ImageIO.read(inputStream);
        int width = sourceImage.getWidth() * ratio;
        int height = sourceImage.getHeight() * ratio;

        resizeImage(sourceImage, outputStream, width, height, fileType);
    }

    /**
     * 按倍率放大图片
     *
     * @param sourcePath
     * @param targetPath
     * @param width
     * @param height
     * @throws IOException
     */
    public static void resizeImage(String sourcePath, String targetPath, int width, int height) throws IOException {
        String fileType = targetPath.substring(targetPath.lastIndexOf(".") + 1);
        try (FileInputStream inputStream = new FileInputStream(sourcePath);
             FileOutputStream outputStream = new FileOutputStream(targetPath)) {
            // 构造Image对象
            BufferedImage sourceImage = ImageIO.read(inputStream);
            resizeImage(sourceImage, outputStream, width, height, fileType);
        }
    }

    /**
     * 按倍率放大图片
     *
     * @param file
     * @param outputStream
     * @param width
     * @param height
     * @throws IOException
     */
    public static void resizeImage(MultipartFile file, OutputStream outputStream, int width, int height) throws IOException {
        String originalFilename = file.getOriginalFilename();
        Assert.notNull(originalFilename, "文件非法");
        String fileType = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        try (InputStream inputStream = file.getInputStream()) {
            // 构造Image对象
            BufferedImage sourceImage = ImageIO.read(inputStream);
            resizeImage(sourceImage, outputStream, width, height, fileType);
        }
    }

    private static void resizeImage(BufferedImage sourceImage, OutputStream outputStream, int width, int height, String fileType) throws IOException {
        // 设置宽高
        BufferedImage targetImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        targetImage.getGraphics().drawImage(sourceImage, 0, 0, null);

        // 保存新图片
        ImageIO.write(targetImage, fileType, outputStream);
    }

    /**
     * 图片灰化
     *
     * @param sourcePath
     * @param targetPath
     * @throws IOException
     */
    public static void grayImage(String sourcePath, String targetPath) throws IOException {
        String fileType = targetPath.substring(targetPath.lastIndexOf(".") + 1);
        try (FileInputStream inputStream = new FileInputStream(sourcePath);
             FileOutputStream outputStream = new FileOutputStream(targetPath)) {
            grayImage(inputStream, outputStream, fileType);
        }
    }

    /**
     * 图片灰化
     *
     * @param file
     * @param outputStream
     * @throws IOException
     */
    public static void grayImage(MultipartFile file, OutputStream outputStream) throws IOException {
        String originalFilename = file.getOriginalFilename();
        Assert.notNull(originalFilename, "文件非法");
        String fileType = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        try (InputStream inputStream = file.getInputStream()) {
            grayImage(inputStream, outputStream, fileType);
        }
    }

    private static void grayImage(InputStream inputStream, OutputStream outputStream, String fileType) throws IOException {
        // 读取图片
        BufferedImage bufferedImage = ImageIO.read(inputStream);

        // 灰化
        ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_GRAY);
        ColorConvertOp op = new ColorConvertOp(cs, null);
        BufferedImage newBufferedImage = op.filter(bufferedImage, null);

        // 保存新图片
        ImageIO.write(newBufferedImage, fileType, outputStream);
    }

    /**
     * 图片添加文字水印
     *
     * @param sourcePath
     * @param targetPath
     * @param font
     * @param color
     * @param x
     * @param y
     * @param watermarkText
     * @throws IOException
     */
    public static void watermarkText(String sourcePath, String targetPath, Font font, Color color, int x, int y, String watermarkText) throws IOException {
        String fileType = targetPath.substring(targetPath.lastIndexOf(".") + 1);
        try (FileInputStream inputStream = new FileInputStream(sourcePath);
             FileOutputStream outputStream = new FileOutputStream(targetPath)) {
            watermarkText(inputStream, outputStream, font, color, x, y, watermarkText, fileType);
        }
    }

    /**
     * 图片添加文字水印
     *
     * @param file
     * @param outputStream
     * @param font
     * @param color
     * @param x
     * @param y
     * @param watermarkText
     * @throws IOException
     */
    public static void watermarkText(MultipartFile file, OutputStream outputStream, Font font, Color color, int x, int y, String watermarkText) throws IOException {
        String originalFilename = file.getOriginalFilename();
        Assert.notNull(originalFilename, "文件非法");
        String fileType = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        try (InputStream inputStream = file.getInputStream()) {
            watermarkText(inputStream, outputStream, font, color, x, y, watermarkText, fileType);
        }
    }

    private static void watermarkText(InputStream inputStream, OutputStream outputStream, Font font, Color color, int x, int y, String watermarkText, String fileType) throws IOException {
        // 读取图片
        BufferedImage image = ImageIO.read(inputStream);
        Graphics2D g2d = image.createGraphics();

        // 设置文字字体、样式
        g2d.setFont(font);
        g2d.setColor(color);
        g2d.drawString(watermarkText, x, y);
        g2d.dispose();

        // 保存新图片
        ImageIO.write(image, fileType, outputStream);
    }

    /**
     * 图片添加图片水印
     *
     * @param sourcePath
     * @param appendSourcePath
     * @param targetPath
     * @param x
     * @param y
     * @param width
     * @param height
     * @throws IOException
     */
    public static void watermarkImage(String sourcePath, String appendSourcePath, String targetPath, int x, int y, int width, int height) throws IOException {
        String fileType = targetPath.substring(targetPath.lastIndexOf(".") + 1);
        try (FileInputStream inputStream = new FileInputStream(sourcePath);
             FileInputStream appendInputStream = new FileInputStream(appendSourcePath);
             FileOutputStream outputStream = new FileOutputStream(targetPath)) {
            watermarkImage(inputStream, appendInputStream, outputStream, x, y, width, height, fileType);
        }
    }

    /**
     * 图片添加图片水印
     *
     * @param file
     * @param appendFile
     * @param outputStream
     * @param x
     * @param y
     * @param width
     * @param height
     * @throws IOException
     */
    public static void watermarkImage(MultipartFile file, MultipartFile appendFile, OutputStream outputStream, int x, int y, int width, int height) throws IOException {
        String originalFilename = file.getOriginalFilename();
        Assert.notNull(originalFilename, "文件非法");
        String fileType = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        try (InputStream inputStream = file.getInputStream();
             InputStream appendInputStream = appendFile.getInputStream()) {
            watermarkImage(inputStream, appendInputStream, outputStream, x, y, width, height, fileType);
        }
    }

    private static void watermarkImage(InputStream inputStream, InputStream appendInputStream, OutputStream outputStream, int x, int y, int width, int height, String fileType) throws IOException {
        // 读取图片
        BufferedImage image = ImageIO.read(inputStream);
        Graphics2D g2d = image.createGraphics();

        // 设置水印图片的起始x/y坐标、宽度、高度
        BufferedImage appendImage = ImageIO.read(appendInputStream);
        g2d.drawImage(appendImage, x, y, width, height, null, null);
        g2d.dispose();

        // 保存新图片
        ImageIO.write(image, fileType, outputStream);
    }


    public static void main(String[] args) throws Exception {
        ImageOperateUtil.cropImage("C:/Users/16/Desktop/image/mianju.jpg", "C:/Users/16/Desktop/image/mianju1.jpg", 2000, 1000);
        ImageOperateUtil.cropImage("C:/Users/16/Desktop/image/mianju.jpg", "C:/Users/16/Desktop/image/mianju2.jpg", 500, 500, 2000, 1000);
        ImageOperateUtil.reduceImageByRatio("C:/Users/16/Desktop/image/mianju.jpg", "C:/Users/16/Desktop/image/mianju3.jpg", 2);
        ImageOperateUtil.enlargeImageByRatio("C:/Users/16/Desktop/image/mianju.jpg", "C:/Users/16/Desktop/image/mianju4.jpg", 2);
        ImageOperateUtil.resizeImage("C:/Users/16/Desktop/image/mianju.jpg", "C:/Users/16/Desktop/image/mianju5.jpg", 3000, 2000);
        ImageOperateUtil.grayImage("C:/Users/16/Desktop/image/mianju.jpg", "C:/Users/16/Desktop/image/mianju6.jpg");
        ImageOperateUtil.watermarkText("C:/Users/16/Desktop/image/mianju.jpg", "C:/Users/16/Desktop/image/mianju7.jpg",
                new Font("宋体", Font.BOLD, 150), new Color(255, 255, 255, 255), 300, 500, "哈哈哈哈");
        ImageOperateUtil.watermarkImage("C:/Users/16/Desktop/image/mianju.jpg", "C:/Users/16/Desktop/image/demo.jpeg",
                "C:/Users/16/Desktop/image/mianju8.jpg", 0, 0, 300, 200);
    }

}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/577190.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

实现SpringMVC底层机制(一)

文章目录 1.环境配置1.创建maven项目2.创建文件目录3.导入jar包 2.开发核心控制器文件目录1.流程图2.编写核心控制器SunDispatcherServlet.java3.类路径下编写spring配置文件sunspringmvc.xml4.配置中央控制器web.xml5.配置tomcat&#xff0c;完成测试1.配置发布方式2.配置热加…

创建Spring Boot项目

选择Maven Archetype,之后再Archetype选择webapp 两个都打勾 这是当前的打勾 这个是以后都默认勾上 打开对应的路径&#xff0c;用vscode打开settings.xml 加入国内源 阿里云 若没有此文件可上网查找 若jar包出现问题&#xff0c;可在repostitory文件内全删除 之后在Maven刷…

巴特沃斯滤波原理及代码实现(matlab详细过程版)

目录 一、算法原理1、原理概述2、参考文献 二、代码实现三、结果展示 本文由CSDN点云侠原创&#xff0c;原文链接。如果你不是在点云侠的博客中看到该文章&#xff0c;那么此处便是不要脸的爬虫与GPT。 一、算法原理 1、原理概述 巴特沃斯滤波器&#xff08;Butterworth filt…

主成分分析(PCA)在 Java 中的简单应用

在数据科学的众多工具中&#xff0c;主成分分析&#xff08;PCA&#xff09;是一种非常重要的统计技术&#xff0c;用于数据降维和模式识别。它通过提取数据中的关键特征来简化数据结构&#xff0c;从而帮助我们更好地理解数据集的主要变化因素。本文将介绍如何在 Java 编程环境…

CARLA (I)--Ubuntu20.04 服务器安装 CARLA_0.9.13服务端和客户端详细步骤

目录 0. 说明0.1 应用场景&#xff1a;0.2 本文动机&#xff1a; 1. 准备工作2. 安装 CARLA 服务端软件【远程服务器】3. 安装 CARLA 客户端【远程服务器】3.1 .egg 文件安装&#xff1a;3.2 .whl 文件安装&#xff1a;3.3 从Pypi下载Python package 4. 运行服务端程序5. 运行客…

arcgis js 4.x加载SceneLayer并实现基于属性查询定位及高亮

一、代码 <!DOCTYPE html> <html> <head><meta charset"utf-8" /><meta name"viewport" content"widthdevice-width, initial-scale1,maximum-scale1,user-scalableno"><title></title><link rel…

北京车展创新纷呈,移远通信网联赋能

时隔四年&#xff0c;备受瞩目的2024&#xff08;第十八届&#xff09;北京国际汽车展览会于4月25日盛大开幕。在这场汽车行业盛会上&#xff0c;各大主流车企竞相炫技&#xff0c;众多全球首发车、概念车、新能源车在这里汇聚&#xff0c;深刻揭示了汽车产业的最新成果和发展潮…

神经网络的激活函数

目录 神经网络 激活函数 sigmoid 激活函数 tanh 激活函数 backward方法 relu 激活函数 softmax 激活函数 神经网络 人工神经网络&#xff08; Artificial Neural Network&#xff0c; 简写为ANN&#xff09;也简称为神经网络&#xff08;NN&#xff09;&#xff0c…

杰发科技AC7840——CAN通信简介(7)_波形分析

参考&#xff1a; CAN总线协议_stm32_mustfeng-GitCode 开源社区 0. 简介 隐形和显性波形 整帧数据表示 1. 字节描述 CAN数据帧标准格式域段域段名位宽&#xff1a;bit描述帧起始SOF(Start Of Frame)1数据帧起始标志&#xff0c;固定为1bit显性(b0)仲裁段dentify(ID)11本数…

c++图论基础(2)

目录 图的存储方式&#xff1a; 邻接矩阵&#xff1a; 代码实现&#xff1a; 邻接表&#xff1a; 代码实现&#xff1a; 邻接矩阵邻接表对比&#xff1a; 带权图&#xff1a; 邻接矩阵存储&#xff1a; 邻接表存储(代码实现)&#xff1a; 图的存储方式&#xff1a; 邻…

Unreal Engine添加UGameInstanceSubsystem子类

点击C类文件夹&#xff0c;在右边的区域点击鼠标右键&#xff0c;在弹出的菜单中选择“新建C类”在弹出的菜单中选中“显示所有类”&#xff0c;选择GameInstanceSubsystem作为父类, 点击“下一步”按钮输入子类名称“UVRVIUOnlineGameSubsystem”&#xff0c;选择插件作为新类…

Qt 创建控件的两种方式

目录 Qt 创建控件的两种方式 通过ui界面创建控件 通过代码方式创建控件 Qt 创建控件的两种方式 通过ui界面创建控件 这里当然我们是需要先有一个项目的&#xff0c;按照我们之前创建项目的步骤&#xff0c;我们可以先创建一个 Widget 的项目&#xff0c;但是 MainWindow 也…

EasyRecovery数据恢复软件2025激活码及下载使用步骤教程

EasyRecovery数据恢复软件是一款功能强大且用户友好的数据恢复工具&#xff0c;专为帮助用户找回因各种原因丢失的数据而设计。该软件由全球知名的数据恢复技术公司开发&#xff0c;经过多年的技术积累和更新迭代&#xff0c;已经成为行业内备受推崇的数据恢复解决方案。 EasyR…

Spring MVC系列之九大核心组件

概述 Spring MVC是面试必问知识点其一&#xff0c;Spring MVC知识体系庞杂&#xff0c;有以下九大核心组件&#xff1a; HandlerMappingHandlerAdapterHandlerExceptionResolverViewResolverRequestToViewNameTranslatorLocaleResolverThemeResolverMultipartResolverFlashMa…

Andorid复习

组件 TextView 阴影 android:shadowColor"color/red" 阴影颜色android:shadowRadius"3.0" 阴影模糊度&#xff08;大小&#xff09;android:shadowDx"10.0" 横向偏移android:shadowDy"10.0" 跑马灯 这里用自定义控件 public cla…

【Java】HOT100 回溯

目录 理论基础 一、组合问题 LeetCode77&#xff1a;组合 LeetCode17&#xff1a;电话号码的字母组合 LeetCode39&#xff1a;组合总和 LeetCode216&#xff1a;组合总和ii LeetCode216&#xff1a;组合总和iii 二、分割问题 LeetCode131&#xff1a;分割回文串 Leet…

MFC实现ini配置文件的读取

MFC实现 ini 配置文件的读取1 实现的功能&#xff1a;点击导入配置文件按钮可以在旁边编辑框中显示配置文件的路径&#xff0c;以及在下面的编辑框中显示配置文件的内容。 1. 显示配置文件内容的编辑框设置 对于显示配置文件内容的 Edit Contorl 编辑框的属性设置如下&#x…

vue3中所有页面需要手动刷新一下才能显示,控制台没有报错

1.问题 登录进来是进入首页&#xff0c;然后切换任何页面都是空白&#xff0c;但是控制台没有报错。在其他页面刷新后却能显示&#xff0c;然而切换到首页刷新后再切换到其他页面又是空白。 2.解决问题 原因&#xff1a;在于首页给了两个根标签&#xff0c;我把其中一个根标签…

视频输入c++ 调用 libtorch推理

1、支持GPU情况 libtorch 支持GPU情况比较奇怪&#xff0c;目前2.3 版本需要在链接器里面加上以下命令&#xff0c;否则不会支持gpu -INCLUDE:?ignore_this_library_placeholderYAHXZ 2 探测是否支持 加一个函数看你是否支持torch&#xff0c;不然不清楚&#xff0c;看到…

axios——503响应超时重复多次请求——技能提升

今天在写后台管理系统时&#xff0c;遇到一个问题&#xff0c;就是每天早上一启动项目&#xff0c;接口会提示503超时&#xff0c;因此项目运行必须重新刷新请求成功后才可以正常使用。 后端同事说请求超时了&#xff0c;需要前端处理一下&#xff0c;如果是503的状态码&#…
最新文章