java实现将图片转Base64字符,Base64转图片

ops/2024/9/23 20:02:37/

图片转base64

java">import java.io.*;
import java.util.Base64;public class ImageToBase64Converter {public static void main(String[] args) {String imagePath = "path/to/your/image.png"; // 替换为你的图片路径String outputFilePath = "out.txt";try {File imageFile = new File(imagePath);FileInputStream fis = new FileInputStream(imageFile);ByteArrayOutputStream bos = new ByteArrayOutputStream();byte[] buffer = new byte[1024];int bytesRead;while ((bytesRead = fis.read(buffer)) != -1) {bos.write(buffer, 0, bytesRead);}byte[] imageBytes = bos.toByteArray();String base64Image = Base64.getEncoder().encodeToString(imageBytes);BufferedWriter writer = new BufferedWriter(new FileWriter(outputFilePath));writer.write(base64Image);writer.close();System.out.println("Base64 representation of the image has been written to out.txt.");fis.close();bos.close();} catch (IOException e) {e.printStackTrace();}}
}

base64转图片

java">import java.io.*;
import java.util.Base64;public class Base64ToImageConverter {public static void main(String[] args) {String inputFilePath = "out.txt";String outputImagePath = "output.png";try {BufferedReader reader = new BufferedReader(new FileReader(inputFilePath));StringBuilder base64Image = new StringBuilder();String line;while ((line = reader.readLine()) != null) {base64Image.append(line);}byte[] imageBytes = Base64.getDecoder().decode(base64Image.toString());FileOutputStream fos = new FileOutputStream(outputImagePath);fos.write(imageBytes);fos.close();System.out.println("Image has been successfully written to output.png.");} catch (IOException e) {e.printStackTrace();}}
}

扩展需求:批量操作

批量操作。将 E:\资料\gw-资料 路径下的所有png格式图片,转成base64 ,输出到E:\资料\gw-资料\out.txt 。保留原文件名称的情况下,再将out.txt里面的base64 还原成多个png图片

java">import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Base64;public class BatchImageToBase64Converter {public static void main(String[] args) {String inputFolderPath = "E:\\资料\\gw-资料";String outputFilePath = "E:\\资料\\gw-资料\\out.txt";try {BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outputFilePath), "UTF-8"));Files.walk(Paths.get(inputFolderPath)).filter(Files::isRegularFile).filter(path -> path.toString().toLowerCase().endsWith(".png")).forEach(path -> {try {byte[] imageBytes = Files.readAllBytes(path);String base64Image = Base64.getEncoder().encodeToString(imageBytes);writer.write("File: " + path.getFileName() + "\n");writer.write(base64Image + "\n");writer.write("----------\n");} catch (IOException e) {e.printStackTrace();}});writer.close();System.out.println("Base64 representations of images have been written to out.txt.");} catch (IOException e) {e.printStackTrace();}}
}

还原:

java">import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Base64;public class BatchBase64ToImageConverter {public static void main(String[] args) {String inputFilePath = "E:\\资料\\gw-资料\\out.txt";String outputFolderPath = "E:\\资料\\gw-资料\\restored_images";try {BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(inputFilePath), "UTF-8"));String line;while ((line = reader.readLine()) != null) {if (line.startsWith("File: ")) {String fileName = line.substring("File: ".length());String base64Data = reader.readLine().trim();byte[] imageBytes = Base64.getDecoder().decode(base64Data);Path outputPath = Paths.get(outputFolderPath, fileName);Files.createDirectories(outputPath.getParent());Files.write(outputPath, imageBytes);System.out.println("Image \"" + fileName + "\" restored.");}}reader.close();System.out.println("All images have been restored.");} catch (IOException e) {e.printStackTrace();}}
}


http://www.ppmy.cn/ops/8551.html

相关文章

Phpstorm环境配置与应用

PhpStorm是一款功能强大的PHP集成开发环境,配置与应用涉及以下步骤: 下载与安装: 访问 PhpStorm 官网下载地址,选择合适的版本进行下载。双击下载的安装包文件进行安装,过程类似于其他IntelliJ IDEA产品。 个性化设…

自定义Centos的终端的命令提示符

背景 当我们使用终端登陆Centos时,就自动打开了ssh终端。这个终端的命令提示符一般是这样的: 这个以#号结束的一行字,就是我们说的命令提示符了。 这个是腾讯云的服务器的提示符,可以看到主机名是VM-4-7-centos。 但是这个看起…

如何防止服务器被攻击

如何防止服务器被攻击 第1步:切断网络; 服务器的攻击来源都必须通过互联网,一旦切断网络,它们就失去了攻击的入口,你可以通过切断网络的方式,以最快的速度切断攻击源,保护服务器所在网络的其他主机服务器。…

Android集成Sentry实践

需求:之前使用的是tencent的bugly做为崩溃和异常监控,好像是要开始收费了,计划使用开源免费的sentry进行替换。 步骤: 1.修改工程文件 app/build.gradle apply plugin: io.sentry.android.gradle sentry {// 禁用或启用ProGua…

盘点50条Redis相关热门话题(一)

Redis在云计算中的应用实践,关键词:云计算,分布式缓存Redis在高并发场景下的性能优化技巧,关键词:高并发,性能优化Redis在微服务架构中的角色与应用,关键词:微服务,分布式…

力扣HOT100 - 24. 两两交换链表中的节点

解题思路: 递归 class Solution {public ListNode swapPairs(ListNode head) {if (head null || head.next null) {return head;}ListNode newHead head.next;head.next swapPairs(newHead.next);newHead.next head;return newHead;} }

【每日刷题】Day20

【每日刷题】Day20 🥕个人主页:开敲🍉 🔥所属专栏:每日刷题🍍 🌼文章目录🌼 1. 面试题 17.04. 消失的数字 - 力扣(LeetCode) 2. 189. 轮转数组 - 力扣&#…

k8s实践总结

一、pod常用操作: 1、如何重启pod? 1.1 删除并重新创建Pod 这是最直接的方法。你可以通过kubectl命令行工具删除Pod,然后Kubernetes将基于其对应的Deployment、ReplicaSet或其他控制器自动重新创建它。 不建议并行删除全部pod&#xff0c…