Java图片处理 - 复制

本文介绍使用Java进行图片复制的不同方式,包括直接通过文件流复制、利用ImageIO工具类复制图片流,以及借助第三方库ImageMagick实现图片的同步与异步复制。文中还提供了具体的代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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图获取一帧图片

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值