epubjs
Version:
Render ePub documents in the browser, across many devices
20 lines (19 loc) • 2.88 kB
HTML
<html xmlns="http://www.w3.org/1999/xhtml"><head><title>Saving Image Data</title><link rel="stylesheet" href="core.css" type="text/css"/><meta name="generator" content="DocBook XSL Stylesheets V1.74.0"/></head><body><div class="sect1" title="Saving Image Data"><div class="titlepage"><div><div><h1 class="title"><a id="learnjava3-CHP-21-SECT-4"/>Saving Image Data</h1></div></div></div><p><a id="idx11130" class="indexterm"/>We’ve spent a lot of time talking about loading images from
files and generating and transforming image data, but nothing about saving
it. First, let’s remember that saving an image to a file such as a JPG or
GIF really implies doing two things: encoding it (highly compressing the
data in a way optimized for the type of image) and then writing it to a
file, possibly with various metadata. As we mentioned earlier, the core
AWT does not provide tools for encoding image data, only decoding it. By
contrast, the ImageIO framework has the capability of writing images in
any format that it can read.</p><p>Writing a <code class="literal">BufferedImage</code> is simply
a matter of calling the static <code class="literal">ImageIO
write()</code> method:</p><a id="I_21_tt1203"/><pre class="programlisting"> <code class="n">File</code> <code class="n">outFile</code> <code class="o">=</code> <code class="k">new</code> <code class="n">File</code><code class="o">(</code><code class="s">"/tmp/myImage.png"</code><code class="o">);</code>
<code class="n">ImageIO</code><code class="o">.</code><code class="na">write</code><code class="o">(</code> <code class="n">bufferedImage</code> <code class="o">,</code> <code class="s">"png"</code><code class="o">,</code> <code class="n">outFile</code> <code class="o">);</code></pre><p>The second argument is a string identifier that names the image
type. You can get the list of supported formats by calling <a id="I_indexterm21_id819234" class="indexterm"/><code class="literal">ImageIO.getWriterFormatNames()</code>. We should note
that the actual type of the image argument is something called <code class="literal">RenderedImage</code>, but <code class="literal">BufferedImage</code> implements that interface.</p><p>You can get more control over the encoding (for example, JPG quality
settings) by getting an <code class="literal">ImageWriter</code> for
the output format and using <code class="literal">ImageWriteParam</code>s. The process is similar to that
in the reader progress listener snippet from the section <a class="xref" href="ch21s01.html#learnjava3-CHP-21-SECT-1.4" title="ImageIO">ImageIO</a>.<a id="I_indexterm21_id819276" class="indexterm"/></p></div></body></html>