欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Java文件與Base64之間的轉(zhuǎn)化方式

 更新時(shí)間:2025年02月11日 14:59:39   作者:Monly21  
這篇文章介紹了如何使用Java將文件(如圖片、視頻)轉(zhuǎn)換為Base64編碼,以及如何將Base64編碼轉(zhuǎn)換回文件,通過提供具體的工具類實(shí)現(xiàn),作者希望幫助讀者更好地理解和應(yīng)用這一過程

Java文件與Base64之間的轉(zhuǎn)化

1、文件轉(zhuǎn)Base64工具類

可以將圖片、視頻轉(zhuǎn)化為Base64格式

/**
 * 文件轉(zhuǎn)Base64
 * @param filePath
 * @return
 */
public static String convertFileToBase64(String filePath) {
    try {
        // 讀取文件為字節(jié)數(shù)組
        byte[] fileBytes = Files.readAllBytes(Paths.get(filePath));

        // 將字節(jié)數(shù)組轉(zhuǎn)換為Base64編碼的字符串
        String base64EncodedString = Base64.getEncoder().encodeToString(fileBytes);

        return base64EncodedString;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

2、Base64轉(zhuǎn)文件工具類

將Base64格式的圖片、視頻下載到本地

/**
 * Base64轉(zhuǎn)文件
 * @param base64String Base64字符串
 * @param filePath 輸出的文件路徑
 * @param mimeType
 *  MIME類型:
 *      視頻 video/mp4
 *      PNG: image/png
 *      JPEG: image/jpeg
 *      GIF: image/gif
 *      BMP: image/bmp
 *      WebP: image/webp
 * @return
 */
public static boolean convertBase64ToFile(String base64String, String filePath, String mimeType) {
    try {
        // 將Base64編碼的字符串轉(zhuǎn)換為字節(jié)數(shù)組
        byte[] fileBytes = Base64.getDecoder().decode(base64String);
        // 創(chuàng)建文件頭信息
        String header = "data:" + mimeType + ";base64,";
        byte[] headerBytes = header.getBytes();
        // 合并文件頭和文件內(nèi)容
        byte[] combinedBytes = new byte[headerBytes.length + fileBytes.length];
        System.arraycopy(headerBytes, 0, combinedBytes, 0, headerBytes.length);
        System.arraycopy(fileBytes, 0, combinedBytes, headerBytes.length, fileBytes.length);
        // 將字節(jié)數(shù)組寫入文件
        Files.write(Paths.get(filePath), fileBytes);
        return true;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

3、綜合案例

package org.ming;

import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;

public class FileToBase64Converter {
    /**
     * 文件轉(zhuǎn)Base64
     * @param filePath
     * @return
     */
    public static String convertFileToBase64(String filePath) {
        try {
            // 讀取文件為字節(jié)數(shù)組
            byte[] fileBytes = Files.readAllBytes(Paths.get(filePath));

            // 將字節(jié)數(shù)組轉(zhuǎn)換為Base64編碼的字符串
            String base64EncodedString = Base64.getEncoder().encodeToString(fileBytes);

            return base64EncodedString;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 文件轉(zhuǎn)Base64流程
     */
    public static List<Map<String, String>> fileToBase64() {
        List<Map<String, String>> dataList = new ArrayList<>();
        // 讀取的圖片路徑
        String filePath = "D:\\repo\\java_base_test\\static\\img\\GcJcSbJkBjVo.png";
        // 讀取的視頻路徑
        String videoPath = "D:\\repo\\java_base_test\\static\\video\\cs.mp4";

        String fileToBase64 = convertFileToBase64(filePath);
        String videoToBase64 = convertFileToBase64(videoPath);

        if (fileToBase64 != null) {
            System.out.println("圖片轉(zhuǎn)換成功");
            dataList.add(new HashMap<String, String>() {{
                put("outPath", String.format("D:\\repo\\java_base_test\\static\\img\\GcJcSbJkBjVo_%s.png", new Date().getTime()));
                put("base64Str", fileToBase64);
                put("mimeType", "image/png");
            }});
        } else {
            System.out.println("圖片轉(zhuǎn)換失敗");
        }

        if (videoToBase64 != null) {
            System.out.println("視頻轉(zhuǎn)換成功");
            dataList.add(new HashMap<String, String>() {{
                put("outPath", String.format("D:\\repo\\java_base_test\\static\\video\\cs_%s.mp4", new Date().getTime()));
                put("base64Str", videoToBase64);
                put("mimeType", "video/mp4");
            }});
        } else {
            System.out.println("視頻轉(zhuǎn)換失敗");
        }

        return dataList;
    }

    /**
     * Base64轉(zhuǎn)文件
     * @param base64String Base64字符串
     * @param filePath 輸出的文件路徑
     * @param mimeType
     *  MIME類型:
     *      視頻 video/mp4
     *      PNG: image/png
     *      JPEG: image/jpeg
     *      GIF: image/gif
     *      BMP: image/bmp
     *      WebP: image/webp
     * @return
     */
    public static boolean convertBase64ToFile(String base64String, String filePath, String mimeType) {
        try {
            // 將Base64編碼的字符串轉(zhuǎn)換為字節(jié)數(shù)組
            byte[] fileBytes = Base64.getDecoder().decode(base64String);
            // 創(chuàng)建文件頭信息
            String header = "data:" + mimeType + ";base64,";
            byte[] headerBytes = header.getBytes();
            // 合并文件頭和文件內(nèi)容
            byte[] combinedBytes = new byte[headerBytes.length + fileBytes.length];
            System.arraycopy(headerBytes, 0, combinedBytes, 0, headerBytes.length);
            System.arraycopy(fileBytes, 0, combinedBytes, headerBytes.length, fileBytes.length);
            // 將字節(jié)數(shù)組寫入文件
            Files.write(Paths.get(filePath), fileBytes);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * base64轉(zhuǎn)文件流程
     * @param base64String
     * @param filePath
     */
    public static void base64ToFile(List<Map<String, String>> dataList) {
        for (Map<String, String> resMap : dataList) {
            boolean flag = convertBase64ToFile(resMap.get("base64Str"), resMap.get("outPath"), resMap.get("mimeType"));
            if (flag) {
                System.out.println(resMap.get("outPath") + " 轉(zhuǎn)化成功");
            } else {
                System.out.println(resMap.get("outPath") + " 轉(zhuǎn)化失敗");
            }
        }
    }

    public static void main(String[] args) {
        // 文件轉(zhuǎn)Base64
        List<Map<String, String>> dataList = fileToBase64();
        // Base64轉(zhuǎn)文件
        base64ToFile(dataList);
    }
}

總結(jié)

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • 如何用Java Stream寫出既高雅又裝*的代碼

    如何用Java Stream寫出既高雅又裝*的代碼

    如何讓同事看不懂你寫的代碼,然后覺得你非常牛逼,這里用到了stream()與Lambda,需要有點(diǎn)基礎(chǔ),沒基礎(chǔ)你炫個(gè)&#128296;優(yōu)雅永不過時(shí)~ 看下面文章時(shí)記得穿燕尾服,拿高腳杯
    2021-08-08
  • java 使用memcached以及spring 配置memcached完整實(shí)例代碼

    java 使用memcached以及spring 配置memcached完整實(shí)例代碼

    本篇文章主要介紹了java 使用memcached以及spring 配置memcached完整實(shí)例代碼,具有一定的參考價(jià)值,有興趣的可以了解一下
    2017-07-07
  • SpringBoot使用Redis的zset統(tǒng)計(jì)在線用戶信息

    SpringBoot使用Redis的zset統(tǒng)計(jì)在線用戶信息

    這篇文章主要介紹了SpringBoot使用Redis的zset統(tǒng)計(jì)在線用戶信息,幫助大家更好的理解和學(xué)習(xí)使用SpringBoot框架,感興趣的朋友可以了解下
    2021-04-04
  • java el簡(jiǎn)介及用法

    java el簡(jiǎn)介及用法

    EL簡(jiǎn)介語(yǔ)法結(jié)構(gòu) 運(yùn)算符等資料代碼。
    2009-04-04
  • Spring啟動(dòng)后獲取所有擁有特定注解的Bean實(shí)例代碼

    Spring啟動(dòng)后獲取所有擁有特定注解的Bean實(shí)例代碼

    這篇文章主要介紹了Spring啟動(dòng)后獲取所有擁有特定注解的Bean實(shí)例代碼,分享了相關(guān)代碼示例,小編覺得還是挺不錯(cuò)的,具有一定借鑒價(jià)值,需要的朋友可以參考下
    2018-02-02
  • JAVA異常處理捕獲與拋出原理解析

    JAVA異常處理捕獲與拋出原理解析

    這篇文章主要介紹了JAVA異常處理捕獲與拋出原理解析,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-09-09
  • 詳解java定時(shí)任務(wù)

    詳解java定時(shí)任務(wù)

    這篇文章主要為大家詳細(xì)介紹了java定時(shí)任務(wù),使用JDK中的Timer定時(shí)任務(wù)來實(shí)現(xiàn),感興趣的小伙伴們可以參考一下
    2016-03-03
  • 創(chuàng)建Jersey REST 服務(wù),基于Maven的實(shí)現(xiàn)

    創(chuàng)建Jersey REST 服務(wù),基于Maven的實(shí)現(xiàn)

    下面小編就為大家?guī)硪黄獎(jiǎng)?chuàng)建Jersey REST 服務(wù),基于Maven的實(shí)現(xiàn)。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2017-06-06
  • spring boot加載資源路徑配置和classpath問題解決

    spring boot加載資源路徑配置和classpath問題解決

    這篇文章主要介紹了spring boot加載資源路徑配置和classpath問題解決,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2018-03-03
  • 詳解Java Streams 中的異常處理

    詳解Java Streams 中的異常處理

    這篇文章主要介紹了Java Streams 中的異常處理,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-03-03

最新評(píng)論