有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java将ReadableByteChannel另存为PNG

我有一个ReadableByteChannel,其中包含一个图像(从URL或文件获取)。我最终将通道写入一个文件,代码如下

final FileOutputStream fileOutputStream = new FileOutputStream(outImageName);
fileOutputStream.getChannel().transferFrom(imageByteChannel, 0, Long.MAX_VALUE);
fileOutputStream.close();

因为不清楚图像是png还是jpeg或。。。我想确定并将其保存为png。我知道我可以用ImageIO.write(buffImg, outImageName, "png");

但不知何故,这要求buffImg是一个RenderedImage,这就提出了如何获得它的问题

有没有比使用ImageIO从文件系统读取文件并将其作为png写入更简单的解决方案?我可以直接在内存中转换它吗

另外还有一个问题:有没有办法告诉ImageIO摆脱AlphaChannel(=透明)


共 (1) 个答案

  1. # 1 楼答案

    如果可以,我建议获取InputStream或底层FileURL对象而不是ReadableByteChannel,因为ImageIO.read(..)直接支持所有这些类型作为输入

    如果不可能,您可以使用Channels.newInputStream(..)从字节通道获取InputStream,以传递到ImageIO.read(...)。不需要先写入文件

    代码:

    ReadableByteChannel channel = ...; // You already have this
    BufferedImage image = ImageIO.read(Channels.newInputStream(channel))
    

    要消除任何不必要的透明度,可以执行以下操作:

    BufferedImage opaque = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_3BYTE_BGR);
    Graphics2D g = opaque.createGraphics();
    try {
        g.setColor(Color.WHITE); // Or any other bg color you like
        g.fillRect(0, 0, image.getWidth(), image.getHeight());
    
        g.drawImage(image, 0, 0, null);
    }
    finally {
        g.dispose();
    }
    

    现在,您可以将PNG格式的图像写入文件或流:

    if (!ImageIO.write(opaque, "PNG", new File(outputFile)) {
        // TODO: Handle odd case where the image could not be written
    }