Java图片格式转换案例怎么开发

wen java案例 30

本文目录导读:

Java图片格式转换案例怎么开发

  1. 使用Java Image I/O API(标准库)
  2. 批量转换工具
  3. 使用Thumbnailator库(推荐)
  4. 完整的GUI转换工具
  5. 使用建议

我将为你详细介绍Java图片格式转换的开发案例,包含多种实现方式。

使用Java Image I/O API(标准库)

这是最基础的方式,无需额外依赖:

import javax.imageio.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Iterator;
public class ImageConverter {
    /**
     * 转换图片格式
     * @param sourceFile 源文件
     * @param targetFormat 目标格式 (jpg, png, gif, bmp, wbmp)
     * @param quality 图片质量 (0.0-1.0, 仅对jpg有效)
     */
    public static void convert(File sourceFile, String targetFormat, float quality) 
            throws IOException {
        // 读取源图片
        BufferedImage image = ImageIO.read(sourceFile);
        if (image == null) {
            throw new IOException("无法读取图片: " + sourceFile.getAbsolutePath());
        }
        // 生成目标文件名
        String fileName = sourceFile.getName();
        String baseName = fileName.substring(0, fileName.lastIndexOf('.'));
        File targetFile = new File(sourceFile.getParent(), 
                                   baseName + "." + targetFormat.toLowerCase());
        // 设置压缩质量(仅对JPEG有效)
        if (targetFormat.equalsIgnoreCase("jpg") || 
            targetFormat.equalsIgnoreCase("jpeg")) {
            ImageWriter writer = ImageIO.getImageWritersByFormatName("jpeg").next();
            ImageWriteParam param = writer.getDefaultWriteParam();
            param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
            param.setCompressionQuality(quality);
            try (FileOutputStream fos = new FileOutputStream(targetFile);
                 ImageOutputStream ios = ImageIO.createImageOutputStream(fos)) {
                writer.setOutput(ios);
                writer.write(null, new IIOImage(image, null, null), param);
                writer.dispose();
            }
        } else {
            // PNG、GIF等其他格式直接写入
            ImageIO.write(image, targetFormat, targetFile);
        }
        System.out.println("转换成功: " + targetFile.getAbsolutePath());
    }
    // 使用示例
    public static void main(String[] args) {
        try {
            // 将PNG转换为JPG,质量0.9
            convert(new File("input.png"), "jpg", 0.9f);
            // 将JPG转换为PNG
            convert(new File("input.jpg"), "png", 1.0f);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

批量转换工具

import javax.imageio.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.*;
public class BatchImageConverter {
    private static final Set<String> SUPPORTED_FORMATS = 
        new HashSet<>(Arrays.asList("jpg", "jpeg", "png", "gif", "bmp", "wbmp"));
    /**
     * 批量转换图片格式
     */
    public static void batchConvert(File sourceDir, File targetDir, 
                                  String targetFormat, float quality) 
            throws IOException {
        if (!sourceDir.isDirectory()) {
            throw new IllegalArgumentException("源路径必须是目录");
        }
        if (!targetDir.exists()) {
            targetDir.mkdirs();
        }
        File[] files = sourceDir.listFiles((dir, name) -> {
            String ext = name.substring(name.lastIndexOf('.') + 1).toLowerCase();
            return SUPPORTED_FORMATS.contains(ext);
        });
        if (files == null || files.length == 0) {
            System.out.println("没有找到支持的图片文件");
            return;
        }
        int successCount = 0;
        for (File file : files) {
            try {
                convertSingle(file, targetDir, targetFormat, quality);
                successCount++;
                System.out.println("✓ 转换成功: " + file.getName());
            } catch (Exception e) {
                System.err.println("✗ 转换失败: " + file.getName() + " - " + e.getMessage());
            }
        }
        System.out.println("\n转换完成: 成功 " + successCount + "/" + files.length + " 个文件");
    }
    private static void convertSingle(File sourceFile, File targetDir, 
                                    String targetFormat, float quality) 
            throws IOException {
        BufferedImage image = ImageIO.read(sourceFile);
        if (image == null) {
            throw new IOException("无法读取图片");
        }
        String baseName = sourceFile.getName()
            .substring(0, sourceFile.getName().lastIndexOf('.'));
        File targetFile = new File(targetDir, baseName + "." + targetFormat.toLowerCase());
        if (targetFormat.equalsIgnoreCase("jpg") || 
            targetFormat.equalsIgnoreCase("jpeg")) {
            ImageWriter writer = ImageIO.getImageWritersByFormatName("jpeg").next();
            ImageWriteParam param = writer.getDefaultWriteParam();
            param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
            param.setCompressionQuality(quality);
            try (FileOutputStream fos = new FileOutputStream(targetFile);
                 ImageOutputStream ios = ImageIO.createImageOutputStream(fos)) {
                writer.setOutput(ios);
                writer.write(null, new IIOImage(image, null, null), param);
                writer.dispose();
            }
        } else {
            ImageIO.write(image, targetFormat, targetFile);
        }
    }
    // 使用示例
    public static void main(String[] args) {
        try {
            batchConvert(
                new File("input/images"),  // 源目录
                new File("output/images"), // 目标目录
                "jpg",                     // 目标格式
                0.85f                      // 质量参数
            );
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

使用Thumbnailator库(推荐)

添加Maven依赖:

<dependency>
    <groupId>net.coobird</groupId>
    <artifactId>thumbnailator</artifactId>
    <version>0.4.20</version>
</dependency>
import net.coobird.thumbnailator.Thumbnails;
import java.io.*;
public class ThumbnailatorConverter {
    /**
     * 使用Thumbnailator转换图片格式
     */
    public static void convertWithThumbnailator(File source, String targetFormat, 
                                              float quality) throws IOException {
        String fileName = source.getName();
        String baseName = fileName.substring(0, fileName.lastIndexOf('.'));
        File target = new File(source.getParent(), 
                              baseName + "." + targetFormat.toLowerCase());
        Thumbnails.of(source)
            .scale(1.0)  // 保持原始尺寸
            .outputFormat(targetFormat)
            .outputQuality(quality)
            .toFile(target);
        System.out.println("转换成功: " + target.getAbsolutePath());
    }
    /**
     * 使用Thumbnailator进行批量转换并压缩
     */
    public static void batchConvertWithThumbnailator(File sourceDir, File targetDir,
                                                   String targetFormat, float quality,
                                                   int width, int height) throws IOException {
        if (!targetDir.exists()) {
            targetDir.mkdirs();
        }
        File[] files = sourceDir.listFiles((dir, name) -> {
            name = name.toLowerCase();
            return name.endsWith(".jpg") || name.endsWith(".jpeg") || 
                   name.endsWith(".png") || name.endsWith(".gif") || 
                   name.endsWith(".bmp");
        });
        if (files != null) {
            for (File file : files) {
                String baseName = file.getName()
                    .substring(0, file.getName().lastIndexOf('.'));
                File outputFile = new File(targetDir, 
                    baseName + "." + targetFormat.toLowerCase());
                Thumbnails.of(file)
                    .size(width, height)  // 调整尺寸
                    .outputFormat(targetFormat)
                    .outputQuality(quality)
                    .toFile(outputFile);
                System.out.println("已转换: " + outputFile.getName());
            }
        }
    }
    // 使用示例
    public static void main(String[] args) throws IOException {
        // 简单转换
        convertWithThumbnailator(new File("input.png"), "jpg", 0.9f);
        // 批量转换并调整尺寸
        batchConvertWithThumbnailator(
            new File("input"), 
            new File("output"),
            "jpg", 0.8f, 800, 600
        );
    }
}

完整的GUI转换工具

import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class ImageConverterGUI extends JFrame {
    private JLabel statusLabel;
    private JComboBox<String> formatCombo;
    private JSlider qualitySlider;
    private JTextField qualityValue;
    private File selectedFile;
    public ImageConverterGUI() {
        setTitle("图片格式转换工具");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(500, 300);
        setLocationRelativeTo(null);
        initComponents();
    }
    private void initComponents() {
        JPanel mainPanel = new JPanel(new BorderLayout(10, 10));
        mainPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
        // 文件选择
        JPanel filePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        JButton selectButton = new JButton("选择图片");
        JLabel fileLabel = new JLabel("未选择文件");
        fileLabel.setPreferredSize(new Dimension(300, 30));
        selectButton.addActionListener(e -> {
            JFileChooser chooser = new JFileChooser();
            FileNameExtensionFilter filter = new FileNameExtensionFilter(
                "图片文件 (jpg, png, gif, bmp)", "jpg", "jpeg", "png", "gif", "bmp");
            chooser.setFileFilter(filter);
            if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
                selectedFile = chooser.getSelectedFile();
                fileLabel.setText("已选择: " + selectedFile.getName());
            }
        });
        filePanel.add(selectButton);
        filePanel.add(fileLabel);
        // 格式选择
        JPanel formatPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        formatPanel.add(new JLabel("目标格式:"));
        formatCombo = new JComboBox<>(new String[]{"jpg", "png", "gif", "bmp"});
        formatPanel.add(formatCombo);
        // 质量设置
        JPanel qualityPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        qualityPanel.add(new JLabel("图片质量:"));
        qualitySlider = new JSlider(0, 100, 90);
        qualitySlider.setPreferredSize(new Dimension(200, 30));
        qualityValue = new JTextField("0.9", 5);
        qualityValue.setEditable(false);
        qualitySlider.addChangeListener(e -> {
            qualityValue.setText(String.format("%.1f", qualitySlider.getValue() / 100.0));
        });
        qualityPanel.add(qualitySlider);
        qualityPanel.add(qualityValue);
        // 转换按钮
        JButton convertButton = new JButton("开始转换");
        convertButton.addActionListener(e -> convertImage());
        // 状态标签
        statusLabel = new JLabel("就绪");
        statusLabel.setHorizontalAlignment(SwingConstants.CENTER);
        // 组合所有面板
        JPanel centerPanel = new JPanel();
        centerPanel.setLayout(new BoxLayout(centerPanel, BoxLayout.Y_AXIS));
        centerPanel.add(filePanel);
        centerPanel.add(formatPanel);
        centerPanel.add(qualityPanel);
        centerPanel.add(Box.createVerticalStrut(20));
        centerPanel.add(convertButton);
        mainPanel.add(centerPanel, BorderLayout.CENTER);
        mainPanel.add(statusLabel, BorderLayout.SOUTH);
        add(mainPanel);
    }
    private void convertImage() {
        if (selectedFile == null) {
            statusLabel.setText("请先选择图片文件");
            return;
        }
        try {
            String targetFormat = (String) formatCombo.getSelectedItem();
            float quality = qualitySlider.getValue() / 100.0f;
            // 使用前面定义的方法进行转换
            ImageConverter.convert(selectedFile, targetFormat, quality);
            statusLabel.setText("✓ 转换成功!");
            JOptionPane.showMessageDialog(this, 
                "图片转换成功!", "成功", JOptionPane.INFORMATION_MESSAGE);
        } catch (Exception ex) {
            statusLabel.setText("✗ 转换失败: " + ex.getMessage());
            JOptionPane.showMessageDialog(this, 
                "转换失败: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            new ImageConverterGUI().setVisible(true);
        });
    }
}

使用建议

  1. 轻量需求 - 使用标准Java Image I/O API
  2. 需要压缩和调整尺寸 - 使用Thumbnailator库
  3. 批量处理 - 使用批量转换工具
  4. 用户交互 - 使用GUI版本

选择哪种方式取决于你的具体需求场景。

抱歉,评论功能暂时关闭!