微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决如何获取 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;

    }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。