Java 8中如何对图像进行Base64编码和解码呢?
下文笔者讲述使用java代码对图片进行Base64编码和解码的方法分享,如下所示
Base64编码和解码的实现思路
借助ImageIO对象中的方法即可实现将图片转换为Base64 和Base64转换图片例:Base64编码和解码的示例
public static String imgToBase64String(final RenderedImage img, final String formatName) { final ByteArrayOutputStream os = new ByteArrayOutputStream(); try { ImageIO.write(img, formatName, Base64.getEncoder().wrap(os)); return os.toString(StandardCharsets.ISO_8859_1.name()); } catch (final IOException ioe) { throw new UncheckedIOException(ioe); } } public static BufferedImage base64StringToImg(final String base64String) { try { return ImageIO.read(new ByteArrayInputStream(Base64.getDecoder().decode(base64String))); } catch (final IOException ioe) { throw new UncheckedIOException(ioe); } }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。