| 1 | package be.nikiroo.utils; |
| 2 | |
| 3 | import java.io.IOException; |
| 4 | import java.io.InputStream; |
| 5 | |
| 6 | /** |
| 7 | * This class represents an image data. |
| 8 | * |
| 9 | * @author niki |
| 10 | */ |
| 11 | public class Image { |
| 12 | private byte[] data; |
| 13 | |
| 14 | /** |
| 15 | * Do not use -- for serialisation purposes only. |
| 16 | */ |
| 17 | @SuppressWarnings("unused") |
| 18 | private Image() { |
| 19 | } |
| 20 | |
| 21 | /** |
| 22 | * Create a new {@link Image} with the given data. |
| 23 | * |
| 24 | * @param data |
| 25 | * the data |
| 26 | */ |
| 27 | public Image(byte[] data) { |
| 28 | this.data = data; |
| 29 | } |
| 30 | |
| 31 | /** |
| 32 | * Create a new {@link Image} from its Base64 representation. |
| 33 | * |
| 34 | * @param base64 |
| 35 | * the {@link Image} in Base64 format |
| 36 | * |
| 37 | * @throws IOException |
| 38 | * in case of I/O error |
| 39 | */ |
| 40 | public Image(String base64) throws IOException { |
| 41 | this(Base64.decode(base64)); |
| 42 | } |
| 43 | |
| 44 | /** |
| 45 | * Create a new {@link Image} from a stream. |
| 46 | * |
| 47 | * @param in |
| 48 | * the stream |
| 49 | * |
| 50 | * @throws IOException |
| 51 | * in case of I/O error |
| 52 | */ |
| 53 | public Image(InputStream in) throws IOException { |
| 54 | this.data = IOUtils.toByteArray(in); |
| 55 | } |
| 56 | |
| 57 | /** |
| 58 | * The actual image data. |
| 59 | * <p> |
| 60 | * This is the actual data, not a copy, so any change made here will be |
| 61 | * reflected into the {@link Image} and vice-versa. |
| 62 | * |
| 63 | * @return the image data |
| 64 | */ |
| 65 | public byte[] getData() { |
| 66 | return data; |
| 67 | } |
| 68 | |
| 69 | /** |
| 70 | * Convert the given {@link Image} object into a Base64 representation of |
| 71 | * the same {@link Image} object. |
| 72 | * |
| 73 | * @return the Base64 representation |
| 74 | */ |
| 75 | public String toBase64() { |
| 76 | return new String(Base64.encodeBytes(getData())); |
| 77 | } |
| 78 | } |