图片文件和 Base64 字符串互转(Java 实现)

这篇具有很好参考价值的文章主要介绍了图片文件和 Base64 字符串互转(Java 实现)。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

  项目中,有些场景下,客户端需要将本地图片传输到服务方存储,此时客户端可以将图片文件转为 Base64 字符串传输到服务方,服务方收到后再将 Base64 字符串还原为图片。以下是一些图片文件和 Base64 字符串互转的工具类,以及校验图片大小的工具。文章来源地址https://www.toymoban.com/news/detail-766809.html

一、依赖包
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <optional>true</optional>
</dependency>
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.6</version>
</dependency>
<dependency>
    <groupId>commons-lang</groupId>
    <artifactId>commons-lang</artifactId>
    <version>2.5</version>
</dependency>
<dependency>
    <groupId>commons-codec</groupId>
    <artifactId>commons-codec</artifactId>
    <version>1.11</version>
</dependency>
二、工具类 Java 代码
package com.example.testdemo.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Objects;

@Slf4j
public class ImageUtil {

    /**
     * 把文件转为 base64
     *
     * @param imagePath 文件全路径名
     * @return base64 字符串
     */
    public static String imageToBase64(String imagePath) {

        try {
            File file = new File(imagePath);
            FileInputStream fis = new FileInputStream(file);
            byte[] imageBytes = new byte[fis.available()];
            fis.read(imageBytes);
            fis.close();
            return Base64.encodeBase64String(imageBytes);
        } catch (IOException e) {
            log.error("图片转 base64 出现异常", e);
            return null;
        }
    }

    /**
     * 把文件转为 base64
     *
     * @param path 文件全路径名
     * @return base64 字符串
     * @throws Exception 抛出异常
     */
    public static String convertBase64(String path) throws Exception {
        if (StringUtils.isBlank(path)) {
            throw new Exception("path is null");
        } else {
            return convertBase64(new File(path));
        }
    }

    /**
     * 文件转为 Base64
     *
     * @param file 文件
     * @return Base64 字符串
     * @throws Exception 抛出异常
     */
    public static String convertBase64(File file) throws Exception {
        if (Objects.isNull(file)) {
            throw new Exception("file is null");
        } else if (!file.exists()) {
            throw new Exception("file does not exist");
        } else {
            byte[] data = FileUtils.readFileToByteArray(file);
            return Base64.encodeBase64String(data);
        }
    }

    /**
     * base64 字符串转图片文件 File
     *
     * @param code base64 字符串
     * @param path 生成图片的全名
     * @return 生成的文件
     * @throws IOException 抛出异常
     */
    public static File base64ToFile(String code, String path) throws IOException {
        File file = new File(path);
        byte[] data = Base64.decodeBase64(code);
        FileUtils.writeByteArrayToFile(file, data);
        return file;
    }

    /**
     * 校验图片的宽度和高度是否符合要求(具体可按实际要求修改判断逻辑)
     *
     * @param path 图片全路径
     * @return 符合要求:true;否则:false
     */
    public static boolean checkImageWidthAndHeight(String path) {
        try {
            File imageFile = new File(path);
            BufferedImage bufferedImage = ImageIO.read(imageFile);

            int width = bufferedImage.getWidth();
            int height = bufferedImage.getHeight();
            log.info("图片:[{}], 宽度:[{}] 像素, 高度:[{}] 像素", path, width, height);

            // 假如图片要求是正方形,且不低于 300 * 300,不高于 800 * 800
            if (width != height) {
                log.warn("图片不是正方形");
                return false;
            }
            if (width < 300) {
                log.warn("图片低于 300 * 300,不符合要求");
                return false;
            }
            if (width > 800) {
                log.warn("图片高于 800 * 800,不符合要求");
                return false;
            }

            return true;
        } catch (IOException e) {
            log.error("校验图片规格出现异常", e);
            return false;
        }
    }

    public static void main(String[] args) throws Exception {

        try {
            // 校验图片是否符合规范
            String basePath = "D:\\";
            String fileName = "test.jpeg";
            String fullPath = basePath + File.separator + fileName;
            boolean res = checkImageWidthAndHeight(fullPath);
            if (!res) {
                log.warn("图片不符合规范");
            }

            // 图片转 base64
            String base64Str = convertBase64(fullPath);
            log.info("base64 字符串:[{}]", base64Str);

            // base64 字符串转图片文件 File
            // 生成的图片
            String convertPath = basePath + File.separator + "convert.jpg";
            base64ToFile(base64Str, convertPath);

            // 图片转 base64
            log.info("base64 字符串:[{}]", imageToBase64(fullPath));
        } catch (IOException e) {
            log.error("图片转化测试异常", e);
        }
    }
}

到了这里,关于图片文件和 Base64 字符串互转(Java 实现)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • postman获取验证码图片(base64字符串格式)

    在 Tests 里编写脚本 然后,在响应体的 Visualize 里查看

    2024年02月12日
    浏览(38)
  • 将html字符串中的base64图片转换成file并上传

    目的 解决富文本编辑器中复制粘贴的图片 base64 字符串过长导致无法存储到数据库的问题 思路 通过正则 获取html字符串中里面的所有图片 base64 数组 然后每个图片base64 转成file 使用上传文件的函数 上传到服务器上. 将上传后获取到的图片访问url 替换成 数据里面的 img 的 src

    2024年01月23日
    浏览(42)
  • [虚幻引擎] UE DTBase64 插件说明 使用蓝图对字符串或文件进行Base64加密解密

    本插件可以在虚幻引擎中使用蓝图对字符串,字节数组,文件进行Base64的加密和解密。 目录 1. 节点说明 String To Base64 Base64 To String Binary To Base64 Base64 To Binary File To Base64 Base64 To File 2. 案例演示 3. 插件下载 String To Base64 对字符串进行Base64加密,字符串会自动转换成UTF8的格式,这

    2024年02月13日
    浏览(54)
  • PDF处理控件Aspose.PDF功能演示:使用Java将Base64字符串转换为PDF/JPG/PNG图像

    Aspose.PDF  是一款高级PDF处理API,可以在跨平台应用程序中轻松生成,修改,转换,呈现,保护和打印文档。无需使用Adobe Acrobat。此外,API提供压缩选项,表创建和处理,图形和图像功能,广泛的超链接功能,图章和水印任务,扩展的安全控件和自定义字体处理。 Aspose API支持

    2024年02月04日
    浏览(59)
  • base64 字符串转换为 Blob 对象

    在 JavaScript 中,可以使用以下代码将 base64 字符串转换为 Blob 对象: 其中, base64 是待转换的 base64 字符串, type 是 Blob 对象的 MIME 类型,默认值为 \\\'application/octet-stream\\\' 。该函数返回一个 Blob 对象。 可以像下面这样使用该函数: 其中, base64Str 是待转换的 base64 字符串, ima

    2024年02月15日
    浏览(30)
  • 将 base64 字符串转换为 Blob 对象

    在 JavaScript 中,可以使用以下代码将 base64 字符串转换为 Blob 对象: 其中, base64 是待转换的 base64 字符串, type 是 Blob 对象的 MIME 类型,默认值为 \\\'application/octet-stream\\\' 。该函数返回一个 Blob 对象。 可以像下面这样使用该函数: 其中, base64Str 是待转换的 base64 字符串, ima

    2024年02月16日
    浏览(49)
  • 解决因base64字符串过长,报500的问题

    提示:后端用nodejs的express,前端是vue 当上传的图片小(base64字符串长度小)时,上传成功 当上传的图片大(base64字符串长度过长)时,上传失败,接口报500,服务器也报了一大堆的错误。 如果直接把base64字符串复制到数据库发现报错,提示数据太长,很明显是因为base64字符

    2024年02月11日
    浏览(36)
  • [译]JavaScript中Base64编码字符串的细节

    本文作者为 360 奇舞团前端开发工程师 本文为翻译 原文标题:The nuances of base64 encoding strings in JavaScript 原文作者:Matt Joseph 原文链接:https://web.dev/articles/base64-encoding   Base64编码和解码是一种常见的将二进制内容转换为适合Web的文本的形式。它通常用于data URLs,比如内嵌图片

    2024年02月05日
    浏览(38)
  • 在HTTP请求中安全传输base64编码的字符串

    base64 是一种常见的的编码格式,它可以把二进制数据编码成一个由大小写英文字母( a-zA-Z )、阿拉伯数字( 0-9 ),以及三个特殊字符 + 、 / 、 = 组成的字符串。 但是在URL传输中, + 、 / 、 = 这三个特殊字符是保留字符(或者叫不安全字符),如果将编码后的base64字符串直

    2024年02月06日
    浏览(32)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包