Java BufferedImage 转 PNG 格式 Base64 字符串

发布于 2024-12-01 00:04:44 字数 727 浏览 2 评论 0原文

我正在尝试将屏幕截图输出作为 Base64 编码字符串,但没有走得太远。到目前为止,我的代码使用 Base64 库( http://iharder.sourceforge.net/current/java/base64/ ):

    Robot robot = new Robot();
    Rectangle r = new Rectangle( Toolkit.getDefaultToolkit().getScreenSize() );
    BufferedImage bi = robot.createScreenCapture(r);
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    OutputStream b64 = new Base64.OutputStream(os);
    ImageIO.write(bi, "png", os);
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    out.writeTo(b64);
    String result = out.toString("UTF-8");

每次运行此命令时,“结果”始终是一个空字符串,但我不明白为什么。有什么想法吗?

注意:我不想将 png 写入磁盘上的文件。

I'm trying to get a screenshot output as a base64 encoded string but not getting very far. The code I have so far uses a Base64 library ( http://iharder.sourceforge.net/current/java/base64/ ):

    Robot robot = new Robot();
    Rectangle r = new Rectangle( Toolkit.getDefaultToolkit().getScreenSize() );
    BufferedImage bi = robot.createScreenCapture(r);
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    OutputStream b64 = new Base64.OutputStream(os);
    ImageIO.write(bi, "png", os);
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    out.writeTo(b64);
    String result = out.toString("UTF-8");

Each time I run this, "result" is always an empty string but I don't understand why. Any ideas?

Note: I don't want to have to write the png to a file on disk.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

绮筵 2024-12-08 00:04:44

我遵循了 xehpuk's 的答案,但在某些浏览器中通过数据渲染时,某些图像的最后几行像素丢失了问题url(Chrome 和 Firefox、Safari 似乎可以很好地渲染它们)。我怀疑这是因为浏览器正在尽最大努力解释数据,但最后几个字节的数据丢失了,所以它显示了它可以做什么。

输出流的包装似乎是此问题的原因。 Base64.wrap(OutputStream os) 的文档解释道:

建议在使用后立即关闭返回的输出流,在此期间它将把所有可能剩余的字节刷新到底层输出流。

因此,根据数据的长度,最后几个字节可能不会从流中刷新,因为没有调用 close() 。我的解决方案是不费心包装流,而直接对流进行编码:

public static String imgToBase64String(final RenderedImage img, final String formatName)
{
  final ByteArrayOutputStream os = new ByteArrayOutputStream();

  try
  {
    ImageIO.write(img, formatName, os);
    return Base64.getEncoder().encodeToString(os.toByteArray());
  }
  catch (final IOException ioe)
  {
    throw new UncheckedIOException(ioe);
  }
}

这解决了在浏览器中渲染时丢失像素行的问题。

I followed xehpuk's answer but had issues with certain images having the last few rows of pixels missing when rendered in certain browsers via a data url (Chrome and Firefox, Safari seemed to render them fine). I suspect this is because the browser is doing it's best to interpret the data but the last few bytes of data was missing so it shows what it can.

The wrapping of the output stream seems to be the cause of this problem. The documentation for Base64.wrap(OutputStream os) explains:

It is recommended to promptly close the returned output stream after use, during which it will flush all possible leftover bytes to the underlying output stream.

So depending on the length of the data, it's possible the last few bytes are not flushed from the stream because close() isn't called on it. My solution to this was to not bother wrapping the stream and just encode the stream directly:

public static String imgToBase64String(final RenderedImage img, final String formatName)
{
  final ByteArrayOutputStream os = new ByteArrayOutputStream();

  try
  {
    ImageIO.write(img, formatName, os);
    return Base64.getEncoder().encodeToString(os.toByteArray());
  }
  catch (final IOException ioe)
  {
    throw new UncheckedIOException(ioe);
  }
}

This resolved the issues with the missing rows of pixels when rendered in a browser.

烟柳画桥 2024-12-08 00:04:44

使用 Java 8 对图像进行 Base64 编码和解码:

public static String imgToBase64String(final RenderedImage img, final String formatName) {
    final ByteArrayOutputStream os = new ByteArrayOutputStream();
    try (final OutputStream b64os = Base64.getEncoder().wrap(os)) {
        ImageIO.write(img, formatName, b64os);
    } catch (final IOException ioe) {
        throw new UncheckedIOException(ioe);
    }
    return os.toString();
}

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);
    }
}

将其用于屏幕截图场景:

final Robot robot = new Robot();
final Rectangle r = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
final BufferedImage bi = robot.createScreenCapture(r);
final String base64String = imgToBase64String(bi, "png");

Base64 encoding and decoding of images using Java 8:

public static String imgToBase64String(final RenderedImage img, final String formatName) {
    final ByteArrayOutputStream os = new ByteArrayOutputStream();
    try (final OutputStream b64os = Base64.getEncoder().wrap(os)) {
        ImageIO.write(img, formatName, b64os);
    } catch (final IOException ioe) {
        throw new UncheckedIOException(ioe);
    }
    return os.toString();
}

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);
    }
}

Use it like this for your screenshot scenario:

final Robot robot = new Robot();
final Rectangle r = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
final BufferedImage bi = robot.createScreenCapture(r);
final String base64String = imgToBase64String(bi, "png");
别在捏我脸啦 2024-12-08 00:04:44

以下语句的工作方向是错误的:

out.writeTo(b64);

它用 out 的空字节数组覆盖 Base 64 数据。

out 的目的到底是什么?我认为你不需要它。

更新:

并且您将图像直接写入os,而不是通过 Base 64 编码器写入。

以下代码应该可以工作:

...
ByteArrayOutputStream os = new ByteArrayOutputStream();
OutputStream b64 = new Base64.OutputStream(os);
ImageIO.write(bi, "png", b64);
String result = os.toString("UTF-8");

The following statement works in the wrong direction:

out.writeTo(b64);

It overwrites the Base 64 data with the empty byte array of out.

What's the purpose of out anyway? I don't think you need it.

Update:

And you write the image directly to os instead of writing through the Base 64 encoder.

The following code should work:

...
ByteArrayOutputStream os = new ByteArrayOutputStream();
OutputStream b64 = new Base64.OutputStream(os);
ImageIO.write(bi, "png", b64);
String result = os.toString("UTF-8");
只有一腔孤勇 2024-12-08 00:04:44

这对我有用:

将图像编码为 Base64 字符串

public static String encodeToString(BufferedImage image, String type) {
    String imageString = null;
    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    try {
        ImageIO.write(image, type, bos);
        byte[] imageBytes = bos.toByteArray();

        Base64.Encoder encoder = Base64.getEncoder();
        imageString = encoder.encodeToString(imageBytes);

        bos.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return imageString;
}

将 Base64 字符串解码为图像

public static BufferedImage decodeToImage(String imageString) {
    BufferedImage image = null;
    byte[] imageByte;
    try {
        Base64.Decoder decoder = Base64.getDecoder();
        imageByte = decoder.decode(imageString);
        ByteArrayInputStream bis = new ByteArrayInputStream(imageByte);
        image = ImageIO.read(bis);
        bis.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return image;
}

This works for me:

Encode Image to Base64 String

public static String encodeToString(BufferedImage image, String type) {
    String imageString = null;
    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    try {
        ImageIO.write(image, type, bos);
        byte[] imageBytes = bos.toByteArray();

        Base64.Encoder encoder = Base64.getEncoder();
        imageString = encoder.encodeToString(imageBytes);

        bos.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return imageString;
}

Decode Base64 String to Image

public static BufferedImage decodeToImage(String imageString) {
    BufferedImage image = null;
    byte[] imageByte;
    try {
        Base64.Decoder decoder = Base64.getDecoder();
        imageByte = decoder.decode(imageString);
        ByteArrayInputStream bis = new ByteArrayInputStream(imageByte);
        image = ImageIO.read(bis);
        bis.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return image;
}
つ低調成傷 2024-12-08 00:04:44

事实上,两种不同解决方案的结合对我来说很有效。我的用例是从 zip 文件中读取图像。这是对我有用的代码:

BufferedImage bgTileSprite = ImageIO.read(inputStream);
ByteArrayOutputStream os = new ByteArrayOutputStream();
ImageIO.write(bgTileSprite, "png", os);
String result = Base64.getEncoder().encodeToString(os.toByteArray());
LOGGER.info(result);

我通过将结果转换为实际图像来确认结果。效果奇妙。

Actually, the combination of two different solutions worked for me. My use case is to read images from a zip file. Here is the code that worked for me :

BufferedImage bgTileSprite = ImageIO.read(inputStream);
ByteArrayOutputStream os = new ByteArrayOutputStream();
ImageIO.write(bgTileSprite, "png", os);
String result = Base64.getEncoder().encodeToString(os.toByteArray());
LOGGER.info(result);

I Confirmed the result by converting the result to actual image. It works wonder.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文