JAVA入坑之高级文件处理

news2024/10/1 3:36:49

一、图片文件简介及解析

1.1图形图像基础概念

1.2JAVA图形图像关键类

1.3图形的基本操作 

package org.example;


import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.util.Iterator;

public class ImageTest {
    public static void main(String[] args) throws Exception {
        readAndWrite(); // 读取并写入图片
        readComparison(); // 图片读取速度对比
        cropImage("D://桌面//1.png", "D://桌面//4.png", 750, 250, 700, 300, "png", "png");
        combineImagesHorizontally("D://桌面//1.png", "D://桌面//1.png", "jpg", "D://桌面//4.png");
        combineImagesVertically("D://桌面//1.png","D://桌面//1.png","jpg", "D://桌面//5.png");
    }
    public static void readAndWrite() throws Exception {
        // 读取和写入 PNG 图片
        BufferedImage image = ImageIO.read(new File("D://桌面//1.png"));
        System.out.println("高度: " + image.getHeight()); // 图片高度(像素)
        System.out.println("宽度: " + image.getWidth()); // 图片宽度(像素)
        ImageIO.write(image, "png", new File("D://桌面//3.png"));
    }
    public static void readComparison() throws Exception {
        System.out.println("===========加载速度测试==============");
        // 使用 ImageIO 读取 PNG 图片
        long startTime = System.nanoTime();
        BufferedImage image = ImageIO.read(new File("D://桌面//1.png"));
        System.out.println("高度: " + image.getHeight()); // 图片高度(像素)
        System.out.println("宽度: " + image.getWidth()); // 图片宽度(像素)
        long endTime = System.nanoTime();
        System.out.println("使用 ImageIO 读取时间: " + (endTime - startTime) / 1000000.0 + "毫秒");
        // 使用 PNG ImageReader 读取 PNG 图片
        startTime = System.nanoTime();
        Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName("png");
        ImageReader reader = readers.next(); // 使用正确的格式读取器
        System.out.println(reader.getClass().getName());
        ImageInputStream iis = ImageIO.createImageInputStream(new File("D://桌面//1.png"));
        reader.setInput(iis, true);
        System.out.println("使用 ImageReader 获得的高度:" + reader.getHeight(0)); // 从 ImageReader 获取图片高度
        System.out.println("使用 ImageReader 获得的宽度:" + reader.getWidth(0)); // 从 ImageReader 获取图片宽度
        endTime = System.nanoTime();
        System.out.println("使用 ImageReader 读取时间: " + (endTime - startTime) / 1000000.0 + "毫秒");
    }
    public static void cropImage(String fromPath, String toPath, int x, int y, int width, int height, String readImageFormat, String writeImageFormat) throws Exception {
        FileInputStream fis = null;
        ImageInputStream iis = null;
        try {
            // 读取原始图片文件
            fis = new FileInputStream(fromPath);
            Iterator<ImageReader> it = ImageIO.getImageReadersByFormatName(readImageFormat);
            ImageReader reader = it.next();
            iis = ImageIO.createImageInputStream(fis);
            reader.setInput(iis, true);
            // 定义一个矩形 并放入切割参数中
            ImageReadParam param = reader.getDefaultReadParam();
            Rectangle rect = new Rectangle(x, y, width, height);
            param.setSourceRegion(rect);
            // 从源文件读取一个矩形大小的图像
            BufferedImage bi = reader.read(0, param);
            // 写入到目标文件
            ImageIO.write(bi, writeImageFormat, new File(toPath));
        } finally {
            fis.close();
            iis.close();
        }
    }
    public static void combineImagesHorizontally(String firstPath, String secondPath, String imageFormat, String toPath) {
        try {
            File first = new File(firstPath);
            BufferedImage imageOne = ImageIO.read(first);
            int width1 = imageOne.getWidth();
            int height1 = imageOne.getHeight();
            int[] firstRGB = imageOne.getRGB(0, 0, width1, height1, null, 0, width1);
            File second = new File(secondPath);
            BufferedImage imageTwo = ImageIO.read(second);
            int width2 = imageTwo.getWidth();
            int height2 = imageTwo.getHeight();
            int[] secondRGB = imageTwo.getRGB(0, 0, width2, height2, null, 0, width2);
            // 生成新图片
            int height3 = Math.max(height1, height2);
            int width3 = width1 + width2;
            BufferedImage imageNew = new BufferedImage(width3, height3, BufferedImage.TYPE_INT_RGB);
            // 设置左半部分的RGB从 (0, 0) 开始
            imageNew.setRGB(0, 0, width1, height1, firstRGB, 0, width1);
            // 设置右半部分的RGB从 (width1, 0) 开始
            imageNew.setRGB(width1, 0, width2, height2, secondRGB, 0, width2);
            // 保存图片
            ImageIO.write(imageNew, imageFormat, new File(toPath));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static void combineImagesVertically(String firstPath, String secondPath,String imageFormat, String toPath){
        try{
//读取第一张图片
            File  first  =  new  File(firstPath);
            BufferedImage  imageOne = ImageIO.read(first);
            int  width1  =  imageOne.getWidth();//图片宽度
            int  height1  =  imageOne.getHeight();//图片高度
//从图片中读取RGB
            int[]  firstRGB  =  new  int[width1*height1];
            firstRGB  =  imageOne.getRGB(0,0,width1,height1,firstRGB,0,width1);
//对第二张图片做相同的处理
            File  second  =  new  File(secondPath);
            BufferedImage  imageTwo  =  ImageIO.read(second);
            int width2 = imageTwo.getWidth();
            int height2 = imageTwo.getHeight();
            int[]   secondRGB  =  new  int[width2*height2];
            secondRGB  =  imageTwo.getRGB(0,0,width2,height2,secondRGB,0,width2);
//生成新图片
            int width3 = (width1>width2)?width1:width2; //挑选宽度大的,作为目标文件的宽度
            int height3 = height1+height2; //高度,两张图片相加
            BufferedImage  imageNew  =  new  BufferedImage(width3,height3,BufferedImage.TYPE_INT_RGB);
//设置上半部分的RGB 从 开始
            imageNew.setRGB(0,0,width1,height1,firstRGB,0,width1);
//设置下半部分的RGB 从(0, height1) 开始
            imageNew.setRGB(0,height1,width2,height2,secondRGB,0,width2);
//保存图片
            ImageIO.write(imageNew, imageFormat, new File(toPath));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

1.4验证码的生成

package org.example;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Random;
import javax.imageio.ImageIO;

public class ValidateCodeTest {
    static char[] codeSequence = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'M', 'N', 'P', 'Q', 'R', 'S', 'T',
            'U', 'V', 'W', 'X', 'Y', 'Z', '2', '3', '4', '5', '6', '7', '8', '9' };
    static int charNum = codeSequence.length;

    public static void main(String[] a) throws IOException {
        generateCode("D://桌面//6.png");
    }

    public static void generateCode(String filePath) throws IOException {
        // 首先定义验证码图片框
        int width = 800; // 验证码图片的宽度
        int height = 200; // 验证码图片的高度

        BufferedImage buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        // 定义图片上的图形和干扰线
        Graphics2D gd = buffImg.createGraphics();
        gd.setColor(Color.LIGHT_GRAY); // 将图像填充为浅灰色
        gd.fillRect(0, 0, width, height);
        gd.setColor(Color.BLACK); // 画边框。
        gd.drawRect(0, 0, width - 1, height - 1);

        // 随机产生16条灰色干扰线,使图像中的认证码不易识别
        gd.setColor(Color.GRAY);
        Random random = new Random();
        for (int i = 0; i < 16; i++) {
            int x = random.nextInt(width);
            int y = random.nextInt(height);
            int x1 = random.nextInt(12);
            int y1 = random.nextInt(12);
            gd.drawLine(x, y, x + x1, y + y1);
        }

        // 计算字的位置坐标
        int codeCount = 4; // 字符个数
        int fontHeight = height - 10; // 字体高度
        int codeX = (width - 4) / (codeCount + 1); // 第一个字符的x坐标
        int codeY = height - 7;

        // 创建字体
        Font font = new Font("Fixedsys", Font.PLAIN, fontHeight);
        gd.setFont(font);

        // 随机产生codeCount个数字的验证码
        for (int i = 0; i < codeCount; i++) {
            String strRand = String.valueOf(codeSequence[random.nextInt(charNum)]);
            int red = random.nextInt(255);
            int green = random.nextInt(255);
            int blue = random.nextInt(255);
            gd.setColor(new Color(red, green, blue));
            gd.drawString(strRand, (i + 1) * codeX, codeY);
        }

        // 保存图片
        ImageIO.write(buffImg, "jpg", new File(filePath));
    }
}

二、条形码和二维码简介及解析

2.1条形码

2.2二维码

2.3相关包

package org.example;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.MatrixToImageWriter; // 引入 MatrixToImageWriter 类
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Map;

public class BarCodeTest {

    /**
     * 根据 code 生成相应的一维码
     *
     * @param file   一维码目标文件
     * @param code   一维码内容
     * @param width  图片宽度
     * @param height 图片高度
     */
    public static void generateCode(File file, String code, int width, int height) {
        // 定义位图矩阵 BitMatrix
        BitMatrix matrix = null;
        try {
            // 使用 CODE_128 格式进行编码生成一维码
            MultiFormatWriter writer = new MultiFormatWriter();
            matrix = writer.encode(code, BarcodeFormat.CODE_128, width, height, null);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 将位图矩阵 BitMatrix 保存为图片
        try (FileOutputStream outStream = new FileOutputStream(file)) {
            ImageIO.write(MatrixToImageWriter.toBufferedImage(matrix), "png", outStream);
            outStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void readCode(File file) {
        try {
            BufferedImage image = ImageIO.read(file);
            if (image == null) {
                return;
            }
            LuminanceSource source = new BufferedImageLuminanceSource(image);
            BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
            Map<DecodeHintType, Object> hints = new HashMap<>();
            hints.put(DecodeHintType.CHARACTER_SET, "GBK");
            hints.put(DecodeHintType.PURE_BARCODE, Boolean.TRUE);
            hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
            Result result = new MultiFormatReader().decode(bitmap, hints);
            System.out.println("条形码内容:" + result.getText());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws Exception {
        // generateCode(new File("1dcode.png"), "123456789012", 500, 250);
        readCode(new File("1dcode.png"));
    }
}

 三、Docx简介及解析

3.1Docx简介

 3.2POI库

 四、表格文件简介及解析

●xls/xlsx 文件(Microsoft Excel) 
●CSV文件(Comma Seperated Values文件)

4.1xls/xlsx 文件

 4.2相关包

 4.3CSV文件

五、 PDF简介及解析

5.1  PDF简介

5.2第三方包

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

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

foobar2000使用笔记

foobar2000使用笔记 现在大多数在线音乐不开通VIP会员&#xff0c;很多歌曲只能听很短几句就听不了了。即使是歌曲免费&#xff0c;想听的歌在不同的APP平台&#xff0c;也较为不便。没办法&#xff0c;听歌又回归到了很多年前下载到本地播放的方式。电脑上的离线音乐一直用网上…

C语言——通讯录详解(文件版)

文件版通讯录 前言&#xff1a;一、保存通讯录二、读取通讯录2.1 通讯录初始化2.2 将文件的信息加载到通讯录 三、代码展示3.1通讯录的声明和定义(contct.h)3.2通讯录函数的实现&#xff08;contact.c&#xff09;3.2 通讯录的测试(test.c) 前言&#xff1a; 我们已经掌握了通…

2023国赛数学建模D题思路模型代码 高教社杯

本次比赛我们将会全程更新思路模型及代码&#xff0c;大家查看文末名片获取 之前国赛相关的资料和助攻可以查看 2022数学建模国赛C题思路分析_2022国赛c题matlab_UST数模社_的博客-CSDN博客 2022国赛数学建模A题B题C题D题资料思路汇总 高教社杯_2022国赛c题matlab_UST数模社…

【工具】python代码编辑器--PyCharm下载安装和介绍

PyCharm是一种Python IDE(集成开发环境),由JetBrains打造。它带有一整套可以帮助用户在使用Python语言开发时提高其效率的工具,比如调试、语法高亮、项目管理、代码跳转、智能提示、自动完成、单元测试、版本控制等。此外,PyCharm还提供了一些高级功能,以用于支持Django框…

Python学习笔记_实战篇(二)_django多条件筛选搜索

多条件搜索在很多网站上都有用到&#xff0c;比如京东&#xff0c;淘宝&#xff0c;51cto&#xff0c;等等好多购物教育网站上都有&#xff0c;当然网上也有很多开源的比楼主写的好的多了去了&#xff0c;仅供参考&#xff0c;哈哈 先来一张效果图吧&#xff0c;不然幻想不出来…

Python学习笔记_实战篇(一)_模拟登陆之下载

中间涉及到的技术点有&#xff1a; 模拟登陆模拟下载解析exal文件数据流读取exal文件&#xff0c;拿出订单号还有最后一点请求接口 下面就给大家挨个说一下,刚拿到需求其实还是很模糊的&#xff0c;因为一个都没做过&#xff0c;等静下心来去理解的时候&#xff0c;发现并没有…

Linux中shell脚本——for、while循环及脚本练习

目录 一.for循环 1.1.基本格式 1.2.类C语言格式 二.while循环 2.1.基本格式 2.2.死循环语句 三.跳出循环 3.1.continue跳出循环 3.2.break跳出循环 四.常用循环 4.1.循环打印九九乘法表 4.2.循环ping测试某个网段网络连通性 4.3.while死循环实现猜数字游戏 4.4.数…

springboot之多数据源配置

文章目录 一、多数据源的典型使用场景1 业务复杂&#xff08;数据量大&#xff09;2 读写分离 二、如何实现多数据源通过AbstractRoutingDataSource动态指定数据源多数据源切换方式AOPMyBatis插件 三、spring集成多个Mybatis框架 实现多数据源控制四、dynamic-datasource 多数据…

YOLO目标检测算法训练过程学习记录

先前已经完成过YOLO系列目标检测算法的调试过程&#xff0c;今天主要是将所有的调试加以总结 这里的conda环境就不再赘述了&#xff0c;直接使用requirement.txt文件的即可&#xff0c;也可以参考YOLOX的配置过程5 数据集处理 YOLOv5有自己的数据集格式&#xff0c;博主的数据…

70 # 协商缓存的配置:通过修改时间

对比&#xff08;协商&#xff09;缓存 比较一下再去决定是用缓存还是重新获取数据&#xff0c;这样会减少网络请求&#xff0c;提高性能。 对比缓存的工作原理 客户端第一次请求服务器的时候&#xff0c;服务器会把数据进行缓存&#xff0c;同时会生成一个缓存标识符&#…

iOS_Crash报告的组成结构

崩溃报告结构如下&#xff0c;每个部分都包含可帮助定位崩溃位置的信息&#xff1a; 1. Header 描述崩溃发生的环境&#xff0c;包含设备、系统、时间、版本等信息。如&#xff1a; Incident Identifier: 6156848E-344E-4D9E-84E0-87AFD0D0AE7B CrashReporter Key: 76f2fb…

【C++STL基础入门】深入浅出string类insert和appand

文章目录 前言一、插入1.中间插入2.尾巴插入拼接appand 总结 前言 本系列STL是使用vs2022C20版本特性来写的。 在C标准模板库&#xff08;STL&#xff09;的众多容器中&#xff0c;string类是处理字符串的重要工具。它提供了丰富的函数和操作符&#xff0c;使得字符串的操作…

真机二阶段之堆叠技术

堆叠技术 --- 可以将多台真实的物理设备逻辑上抽象成一台 思科 -- VPC 华为 -- iStack和CSS 华三 -- IRF 锐捷 -- VSU iStack和CSS的区别&#xff1a; CSS --- 集群 --- 它仅支持将两台支持集群的交换机逻辑上整合成一台设备。 iStack --- 堆叠 --- 可以将多台支持堆叠的交换…

Agile Iteration Velocity

【agile iteration velocity】敏捷速度指的平均速度 第四次迭代结束速度&#xff1a; 76 / 4 19 第五次迭代结束速度&#xff1a; &#xff08;76 24 &#xff09; / 5 100 / 5 20

【地理专题】2023年最新全国A级景区数

数据来源&#xff1a;中国文化和旅游部时间跨度&#xff1a;2023年区域范围&#xff1a;全国范围数据字段&#xff1a; 景区名称&#xff1b;地址&#xff1b;等级&#xff1b;城市&#xff1b;经度&#xff1b;纬度 该图基于自然资源部地图技术审查中心标准地图服务网站下载…

The internal rate of return (IRR)

内部收益率 NPV(Net Present Value)_spencer_tseng的博客-CSDN博客

华为网络篇 OSPF的Silent-Interface-33

难度1复杂度1 目录 一、实验拓扑 二、实验步骤 三、实验过程 总结 一、实验拓扑 二、实验步骤 1.搭建如图所示的网络拓扑&#xff1b; 2.初始化各设备&#xff0c;配置相应的IP地址&#xff0c;测试直连网络的连通性&#xff1b; 3.整个网络配置OSPF协议&#xff0c;查看…

使用预制体画刷在游戏场景中快速布置预制体、粒子特效等

有时候在使用tilemap的时候&#xff0c;会希望在场景中添加更复杂的对象。 在2d-extras中&#xff0c;加入了预制件笔刷&#xff08;Prefab Brush&#xff09;&#xff0c;可以将游戏物体预制体作为瓦片&#xff0c;来方便的在游戏场景中快速的绘制。可以自动适应游戏物体的位置…

Docker容器:docker镜像的创建及dockerfile

Docker容器&#xff1a;docker镜像的创建及dockerfile案例 一.docker镜像的三种创建方法 创建镜像有三种方法&#xff1a;基于现有镜像创建、基于本地模板创建及基于dockerfile创建 1.基于现有镜像创建 1.1 启动镜像 #首先启动一个镜像&#xff0c;在容器里做修改 docker …

Linux笔试题(1)

1、以长格式列目录时&#xff0c;若文件test的权限描述为&#xff1a;drwxrw-r–&#xff0c;则文件test的类型及文件主的权限是__A____。 A.目录文件、读写执行 B.目录文件、读写 C.普通文件、读写 D.普通文件、读 在这个问题中&#xff0c;我们需要解析文件权限的描述&…