Java图片处理 - 复制
Java处理图片的时候,可以用原生接口,可以直接以第三方接口方式复制图片
以文件复制
public static void copyByStream(File source,File target) throws Exception {
int length = 1024;
FileInputStream in = new FileInputStream(source);
FileOutputStream out = new FileOutputStream(target);
byte[] buffer = new byte[length];
while (true) {
int ins = in.read(buffer);
if (ins == -1) {
in.close();
out.flush();
out.close();
} else {
out.write(buffer, 0, ins);
}
}
}
以图片流复制
public static void copyByImageIO(String sourcePath,String targetPath) throws Exception {
try {
File input = new File(sourcePath);
BufferedImage bim = ImageIO.read(input);
File output = new File(targetPath);
ImageIO.write(bim, "jpg", output);
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
使用第三方库复制
这里使用的第三方库是ImageMagick,GraphicsMagick中的convert命令,所以需安装ImageMagick或者GraphicsMagick,如何安装请移步Java图片处理 - 安装ImageMagick库使用convert命令
而且项目中还需要导入maven配置
<dependency>
<groupId>org.im4java</groupId>
<artifactId>im4java</artifactId>
<version>1.4.0</version>
</dependency>
/**
* 拷贝图片 - 同步
* @param source
* @param target
* @return
* @throws Exception
*/
public static boolean copyImage(String source, String target) throws Exception {
createDirectory(target);
IMOperation op = new IMOperation();
op.addImage(source);
op.addImage(target);
ConvertCmd cmd = (ConvertCmd) getImageCommand("convert");
cmd.setAsyncMode(false);
cmd.run(op);
return true;
}
/**
* 拷贝图片 - 异步
* @param source
* @param target
* @return
* @throws Exception
*/
public static void copyImageAsyncMode(String source, String target) throws Exception {
createDirectory(target);
IMOperation op = new IMOperation();
op.addImage(source);
op.addImage(target);
ConvertCmd cmd = (ConvertCmd) getImageCommand("convert");
cmd.setAsyncMode(true);
cmd.run(op);
}
/**
* 创建目录
* @param path
*/
private static void createDirectory(String path) {
File file = new File(path);
if (file.exists()){
return;
}
file.getParentFile().mkdirs();
}
大家还可以参考我专栏中的其他文章:
(1)Java图片处理 - 安装ImageMagick库使用convert命令
(2)Java图片处理 - 创建工具类
(3)Java图片处理 - 复制
(4)Java图片处理 - 缩放图片
(5)Java图片处理 - gif图获取一帧图片