Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
94 views
in Technique[技术] by (71.8m points)

java - Save ReadableByteChannel as PNG

I have a ReadableByteChannel which contains an image (either obtained from an URL or a file). I write the Channel finally into a File with a code like

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

Since it is unclear if the image is a png or a jpeg or ... I want to make sure and save it as png. I know I can use the ImageIO.write(buffImg, outImageName, "png");

But somehow this requires that the buffImg is a RenderedImage which raises the question how to obtain it?

Is there a simpler solution than reading the file from the file system with ImageIO and than write it as png? Can I convert it directly within the memory?

Plus an additional question: Is there a way to tell ImageIO to get rid of the AlphaChannel (=transparent)?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you can, I suggest getting the InputStream or the underlying File or URL objects instead of a ReadableByteChannel, as ImageIO.read(..) supports all those types as input directly.

If not possible, you can use Channels.newInputStream(..) to get an InputStream from the byte channel, to pass on to ImageIO.read(...). There's no need to write to a file first.

Code:

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

To get rid of any unwanted transparency, you could do:

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

You can now write the image in PNG format, either to a file or stream:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...