溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Java如何實現(xiàn)bmp和jpeg圖片格式互轉(zhuǎn)

發(fā)布時間:2023-04-14 09:41:17 來源:億速云 閱讀:109 作者:iii 欄目:編程語言

這篇“Java如何實現(xiàn)bmp和jpeg圖片格式互轉(zhuǎn)”文章的知識點大部分人都不太理解,所以小編給大家總結(jié)了以下內(nèi)容,內(nèi)容詳細,步驟清晰,具有一定的借鑒價值,希望大家閱讀完這篇文章能有所收獲,下面我們一起來看看這篇“Java如何實現(xiàn)bmp和jpeg圖片格式互轉(zhuǎn)”文章吧。

Bmp轉(zhuǎn)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可適用于其他圖片類型的轉(zhuǎn)換
        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
        encoder.encode(tag);
        out.close();
        
        log.info("bmp 轉(zhuǎn) JPEG,共耗時:  " + (System.currentTimeMillis() - start) + " 毫秒");
        return outPath;
    } catch (IOException e) {
        e.printStackTrace();
    }
        return outPath;
    }

Jpeg轉(zhuǎn)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 轉(zhuǎn) bmp,共耗時:" + (System.currentTimeMillis() - start) + " 毫秒");
    } catch (IOException e) {
        e.printStackTrace();
    }
}

以上就是關于“Java如何實現(xiàn)bmp和jpeg圖片格式互轉(zhuǎn)”這篇文章的內(nèi)容,相信大家都有了一定的了解,希望小編分享的內(nèi)容對大家有幫助,若想了解更多相關的知識內(nèi)容,請關注億速云行業(yè)資訊頻道。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。

AI