1 package be
.nikiroo
.utils
;
3 import java
.io
.ByteArrayInputStream
;
4 import java
.io
.Closeable
;
6 import java
.io
.FileInputStream
;
7 import java
.io
.IOException
;
8 import java
.io
.InputStream
;
11 * This class represents an image data.
15 public class Image
implements Closeable
{
16 static private TempFiles tmpRepository
;
17 static private long count
= 0;
18 static private Object lock
= new Object();
23 * Do not use -- for serialisation purposes only.
25 @SuppressWarnings("unused")
30 * Create a new {@link Image} with the given data.
35 public Image(byte[] data
) {
36 ByteArrayInputStream in
= new ByteArrayInputStream(data
);
38 this.data
= getTemporaryFile();
39 IOUtils
.write(in
, this.data
);
40 } catch (IOException e
) {
41 throw new RuntimeException(e
);
45 } catch (IOException e
) {
46 throw new RuntimeException(e
);
52 * Create a new {@link Image} from its Base64 representation.
55 * the {@link Image} in Base64 format
58 * in case of I/O error
60 public Image(String base64
) throws IOException
{
61 this(Base64
.decode(base64
));
65 * Create a new {@link Image} from a stream.
71 * in case of I/O error
73 public Image(InputStream in
) throws IOException
{
74 data
= getTemporaryFile();
75 IOUtils
.write(in
, data
);
79 * <b>Read</b> the actual image data, as a byte array.
81 * @return the image data
83 public byte[] getData() {
85 FileInputStream in
= new FileInputStream(data
);
87 return IOUtils
.toByteArray(in
);
91 } catch (IOException e
) {
92 throw new RuntimeException(e
);
97 * Convert the given {@link Image} object into a Base64 representation of
98 * the same {@link Image} object.
100 * @return the Base64 representation
102 public String
toBase64() {
103 return Base64
.encodeBytes(getData());
107 * Closing the {@link Image} will delete the associated temporary file on
110 * Note that even if you don't, the program will still <b>try</b> to delete
111 * all the temporary files at JVM termination.
114 public void close() throws IOException
{
116 synchronized (lock
) {
120 tmpRepository
.close();
121 tmpRepository
= null;
127 protected void finalize() throws Throwable
{
136 * Return a newly created temporary file to work on.
140 * @throws IOException
141 * in case of I/O error
143 private File
getTemporaryFile() throws IOException
{
144 synchronized (lock
) {
145 if (tmpRepository
== null) {
146 tmpRepository
= new TempFiles("images");
152 return tmpRepository
.createTempFile("image");