最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

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)文章

  • SpringBoot+Redis隊(duì)列實(shí)現(xiàn)Java版秒殺的示例代碼

    SpringBoot+Redis隊(duì)列實(shí)現(xiàn)Java版秒殺的示例代碼

    本文主要介紹了SpringBoot+Redis隊(duì)列實(shí)現(xiàn)Java版秒殺的示例代碼,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2023-06-06
  • Spring中@Autowired和@Resource注解的使用區(qū)別詳解

    Spring中@Autowired和@Resource注解的使用區(qū)別詳解

    這篇文章主要介紹了Spring中@Autowired和@Resource注解的使用區(qū)別詳解,@Autowired默認(rèn)根據(jù)type進(jìn)行注入,找到與指定類型兼容的?Bean?并進(jìn)行注入,如果無法通過type匹配到對(duì)應(yīng)的?Bean?的話,會(huì)根據(jù)name進(jìn)行匹配,如果都匹配不到則拋出異常,需要的朋友可以參考下
    2023-11-11
  • Spring實(shí)戰(zhàn)之使用靜態(tài)工廠方法創(chuàng)建Bean操作示例

    Spring實(shí)戰(zhàn)之使用靜態(tài)工廠方法創(chuàng)建Bean操作示例

    這篇文章主要介紹了Spring實(shí)戰(zhàn)之使用靜態(tài)工廠方法創(chuàng)建Bean操作,結(jié)合實(shí)例形式分析了靜態(tài)工廠方法創(chuàng)建Bean的相關(guān)實(shí)現(xiàn)步驟與操作注意事項(xiàng),需要的朋友可以參考下
    2019-11-11
  • Java排序算法之選擇排序代碼實(shí)例

    Java排序算法之選擇排序代碼實(shí)例

    這篇文章主要介紹了Java排序算法之選擇排序代碼實(shí)例,從數(shù)組的第一個(gè)元素開始,每次遍歷數(shù)組找出一個(gè)最小值放在最左側(cè),第二次從第二個(gè)元素開始,依次類推,直到起始元素為數(shù)組的倒數(shù)第二個(gè)元素時(shí),直接和最后一個(gè)元素比較,較小值放左邊,完成排序,需要的朋友可以參考下
    2023-11-11
  • 詳解5種Java中常見限流算法

    詳解5種Java中常見限流算法

    在高并發(fā)系統(tǒng)中,出于系統(tǒng)保護(hù)角度考慮,通常會(huì)對(duì)流量進(jìn)行限流;不但在工作中要頻繁使用,而且也是面試中的高頻考點(diǎn)。本文就為大家整理了5種Java中常見限流算法,需要的可以參考一下
    2023-04-04
  • Java應(yīng)用程序開發(fā)學(xué)習(xí)之static關(guān)鍵字應(yīng)用

    Java應(yīng)用程序開發(fā)學(xué)習(xí)之static關(guān)鍵字應(yīng)用

    今天小編就為大家分享一篇關(guān)于Java應(yīng)用程序開發(fā)學(xué)習(xí)之static關(guān)鍵字應(yīng)用,小編覺得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來看看吧
    2018-12-12
  • Spring Cloud Alibaba全面解析

    Spring Cloud Alibaba全面解析

    這篇文章詳細(xì)介紹了SpringCloudAlibaba的核心價(jià)值、誕生背景、核心優(yōu)勢(shì)以及與原生SpringCloud的區(qū)別,文章適合希望深入了解SpringCloudAlibaba的企業(yè)級(jí)微服務(wù)架構(gòu)師和開發(fā)人員,感興趣的朋友跟隨小編一起看看吧
    2026-03-03
  • Java微服務(wù)間接口調(diào)用 feign

    Java微服務(wù)間接口調(diào)用 feign

    這篇文章主要介紹了微服務(wù)間的接口調(diào)用feign,F(xiàn)eign是一種聲明式、模板化的HTTP客戶端。在spring cloud中使用Feign,可以做到類似于普通的接口的請(qǐng)求調(diào)用,感興趣的小伙伴可以參考閱讀
    2023-03-03
  • 在Spring中基于Java類進(jìn)行配置的完整步驟

    在Spring中基于Java類進(jìn)行配置的完整步驟

    基于Java配置選項(xiàng),可以編寫大多數(shù)的Spring不用配置XML,下面這篇文章主要給大家介紹了關(guān)于在Spring中基于Java類進(jìn)行配置的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2018-05-05
  • Java三種獲取redis的連接及redis_String類型演示(適合新手)

    Java三種獲取redis的連接及redis_String類型演示(適合新手)

    這篇文章主要介紹了Java三種獲取redis的連接及redis_String類型演示(適合新手),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-12-12

最新評(píng)論

临湘市| 宜兴市| 溧阳市| 兰溪市| 石门县| 琼中| 平泉县| 托克托县| 岑巩县| 苍溪县| 湖南省| 天门市| 讷河市| 寿阳县| 潮州市| 平阴县| 嘉荫县| 健康| 宜兰市| 沅陵县| 洪雅县| 余庆县| 鹿邑县| 宁河县| 黄大仙区| 石家庄市| 四川省| 西和县| 翁牛特旗| 行唐县| 大丰市| 天全县| 中西区| 台安县| 汝城县| 马山县| 隆德县| 通州区| 长治市| 阳曲县| 道真|