Java 实现不改变图片尺寸,增大图片大小(kb)

需求描述:

碰到一个需求,要求图片必须达到一定的大小,但是图片的尺寸还不能变化,这可咋整,想了好久没找到解决办法,然后根据windows的copy命令启发想到了这个方法,原理和windows的copy命令的原理一样,都是拼接图片内容,从而让图片达到指定大小。

# windows 图片复制命令(cmd操作)
copy /b a.jpg+a.jpg b.jpg

解决:

代码如下,就是将a图片的内容拼接到b图片上,b图片就是我们需要的图片,对于a图片来说没有任何要求,就是相当于给b图片做内容填充。之所以有这个效果是因为图片都具有特定的开头和结尾标识,我们这么操作不会影响原图片的信息。下面我进行了多次拼接,其实完全可以找一张需要的大小图片做原始图片将其直接拼接到我们需要的图片上就行了。


import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * @Author: pcc
 * @Description: 一句话描述该类
 */
public class Test {

    public static void main(String[] args) {

        String sourceFile = "D:\\新建文件夹\\a.jpg";
        String destinationFile = "D:\\新建文件夹\\b.jpg";

        try {
            // 检查源文件是否存在
            if (!Files.exists(Paths.get(sourceFile))) {
                throw new IOException("Source file does not exist: " + sourceFile);
            }

            appendFiles(sourceFile, destinationFile);
            System.out.println("Files have been appended successfully.");
        } catch (IOException e) {
            System.err.println("An error occurred: " + e.getMessage());
            e.printStackTrace(); 
        }
    }

    private static void appendFiles(String sourceFile, String destinationFile) throws IOException {
            byte[] buffer = new byte[1024];
            int bytesRead;
            for (int i = 0; i < 5; i++) {
                try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(sourceFile));
                     BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destinationFile, true))) {
                    while ((bytesRead = bis.read(buffer)) != -1) {
                        bos.write(buffer, 0, bytesRead);
                    }
                }
            }


    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

归去来 兮

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值