需求描述:
碰到一个需求,要求图片必须达到一定的大小,但是图片的尺寸还不能变化,这可咋整,想了好久没找到解决办法,然后根据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);
}
}
}
}
}