2 * Imagesqueeze - Image codec. Copyright ©2012-2019, Svjatoslav Agejenko, svjatoslav@svjatoslav.eu
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of version 3 of the GNU Lesser General Public License
6 * or later as published by the Free Software Foundation.
9 package eu.svjatoslav.imagesqueeze.codec;
11 import eu.svjatoslav.commons.data.BitInputStream;
12 import eu.svjatoslav.commons.data.BitOutputStream;
14 import java.awt.image.BufferedImage;
18 * Main class representing compressed image.
23 public ImageMetaData metaData;
25 public BufferedImage bufferedImage;
27 private ImageEncoder encoder;
33 * Initialize imagesqueeze image based on {@link BufferedImage}.
34 * {@link BufferedImage} must be of type BufferedImage.TYPE_3BYTE_BGR .
36 public Image(final BufferedImage image) {
38 bufferedImage = image;
39 metaData = new ImageMetaData();
42 metaData.width = image.getWidth();
43 metaData.height = image.getHeight();
47 * Initialize empty imagesqueeze image.
49 public Image(final int width, final int height) {
51 bufferedImage = new BufferedImage(width, height,
52 BufferedImage.TYPE_3BYTE_BGR);
53 metaData = new ImageMetaData();
56 metaData.width = width;
57 metaData.height = height;
61 * Load ImgSqz image from {@link File}.
63 public void loadImage(final File source) throws IOException {
65 final byte[] fileContent = new byte[(int) source.length()];
67 try (FileInputStream fileInputStream = new FileInputStream(source)) {
68 if (fileInputStream.read(fileContent) != fileContent.length)
69 throw new RuntimeException("Failed to read file content");
72 final ByteArrayInputStream inputStream = new ByteArrayInputStream(
75 loadImage(inputStream);
79 * Load ImgSqz image from {@link InputStream}.
81 public void loadImage(final InputStream source) throws IOException {
82 final BitInputStream bitInputStream = new BitInputStream(source);
84 metaData = new ImageMetaData();
85 metaData.load(bitInputStream);
87 bufferedImage = new BufferedImage(metaData.width, metaData.height,
88 BufferedImage.TYPE_3BYTE_BGR);
90 final ImageDecoder imageDecoder = new ImageDecoder(this, bitInputStream);
92 imageDecoder.decode();
96 * Save image into ImgSqz file format.
98 public void saveImage(final File file) throws IOException {
99 final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
100 saveImage(outputStream);
102 final byte[] buffer = outputStream.toByteArray();
103 try (FileOutputStream fileOutputStream = new FileOutputStream(file)) {
104 fileOutputStream.write(buffer);
109 * Save image into ImgSqz file format.
111 private void saveImage(final OutputStream outputStream) throws IOException {
113 final BitOutputStream bitOutputStream = new BitOutputStream(
116 metaData.save(bitOutputStream);
118 if (encoder == null) {
119 encoder = new ImageEncoder(this);
122 encoder.encode(bitOutputStream);
124 bitOutputStream.finishByte();