如何获取 BMP 格式图像的 Base64 字符串

问题描述

我正在尝试将任何图像格式转换为 BMP 格式,然后返回转换后的 BMP 字节的 base64 字符串。 但是,当我返回 BMP 图像 base64 字符串时,它变为空白。我什至尝试在控制台上打印它,但仍然没有在控制台上打印字符串。在调试模式下,我可以看到图像被转换为​​ base64 字符串,但它没有被打印或传递给进一步的控制。 下面是代码片段:

base64encoded = true

但不知道为什么没有在响应中添加返回字符串并尝试在控制台中对其进行 pritintin,仍然没有输出 如果我对其进行调试,则会生成 base64 字符串,但它不会通过。 谁能指出我的错误或帮助我解决这个问题。

解决方法

问题已解决!能够将任何图像转换为bmp,然后转换为转换后的BMP格式图像的base64string。

private StringBuilder convertToBMP(byte[] content,String id,String filetype) throws IOException {

        String base64image = null;

        InputStream in = new ByteArrayInputStream(content);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        BufferedReader br = null;
        FileWriter writer = null;
        StringBuilder sb = null;
        try {

            BufferedImage image = ImageIO.read(in);

            if (filetype.equalsIgnoreCase("image/png")) {
                BufferedImage newBufferedImage = new BufferedImage(image.getWidth(),image.getHeight(),BufferedImage.TYPE_INT_RGB);

                newBufferedImage.createGraphics().drawImage(image,Color.WHITE,null);

                image = newBufferedImage;
            }

            if (!filetype.equalsIgnoreCase("image/bmp")) {
                boolean b = ImageIO.write(image,"bmp",out);
                byte[] bmpbyte = out.toByteArray();
                if (b && bmpbyte.length > 0) {
                    out.flush();
                    base64image = Base64.getEncoder().encodeToString(bmpbyte);
                    sb = new StringBuilder();
                    sb.append(base64image);
                }
            } else if (filetype.equalsIgnoreCase("image/bmp")) {
                base64image = Base64.getEncoder().encodeToString(content);
                sb = new StringBuilder();
                sb.append(base64image);
            }

        } catch (IOException | NullPointerException e) {
            // TODO Auto-generated catch block
            System.out.println("error while converting image" + e);
            e.printStackTrace();
        } finally {
            try {
                if (in != null)
                    in.close();
                if (out != null)
                    out.close();
                if (br != null)
                    br.close();
                if (writer != null)
                    writer.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return sb;

    }

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...