Home > Java > javaTutorial > How to convert bmp and jpeg image formats to each other in Java

How to convert bmp and jpeg image formats to each other in Java

WBOY
Release: 2023-04-28 23:10:05
forward
1337 people have browsed it

Bmp to Jpeg

public static String bmp2Jpeg(String filePath, String outPath) {
    try {
        long start = System.currentTimeMillis();
        // 加载bmp图片
        File file = new File(filePath);
        Image img = ImageIO.read(file);
        BufferedImage tag = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_RGB);
        tag.getGraphics().drawImage(img.getScaledInstance(img.getWidth(null), img.getHeight(null), Image.SCALE_SMOOTH), 0, 0, null);

        // 输出为Jpeg
        FileOutputStream out = new FileOutputStream(outPath);
        // JPEGImageEncoder可适用于其他图片类型的转换
        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
        encoder.encode(tag);
        out.close();
        
        log.info("bmp 转 JPEG,共耗时:  " + (System.currentTimeMillis() - start) + " 毫秒");
        return outPath;
    } catch (IOException e) {
        e.printStackTrace();
    }
        return outPath;
    }
Copy after login

Jpeg to Bmp

public static void jpeg2Bmp(String inputPath, String outputPath) {
    try {
        long start = System.currentTimeMillis();
    
        // 加载Jpeg图片资源
        FileImageInputStream fiis = new FileImageInputStream(new File(inputPath));
        FileImageOutputStream fios = new FileImageOutputStream(new File(outputPath));
        ImageReader jpegReader = null;
        Iterator<ImageReader> it1 = ImageIO.getImageReadersByFormatName("jpeg");
        if (it1.hasNext()) {
            jpegReader = it1.next();
        }
        jpegReader.setInput(fiis);
        
        ImageWriter bmpWriter = null;
        Iterator<ImageWriter> it2 = ImageIO.getImageWritersByFormatName("bmp");
        if (it2.hasNext()) {
            bmpWriter = it2.next();
        }
        bmpWriter.setOutput(fios);
        BufferedImage br = jpegReader.read(0);
        bmpWriter.write(br);
        fiis.close();
        fios.close();
        
        log.info("jpeg 转 bmp,共耗时:" + (System.currentTimeMillis() - start) + " 毫秒");
    } catch (IOException e) {
        e.printStackTrace();
    }
}
Copy after login

The above is the detailed content of How to convert bmp and jpeg image formats to each other in Java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template