#532 Write TGA with RLE compression.

This commit is contained in:
Harald Kuhr
2021-04-08 19:29:26 +02:00
parent 913a03608c
commit fac9f1a927
13 changed files with 1265 additions and 67 deletions
@@ -63,7 +63,8 @@ final class RLEDecoder implements Decoder {
buffer.put((byte) data);
}
} else {
}
else {
for (int b = 0; b < pixel.length; b++) {
int data = stream.read();
if (data < 0) {
@@ -0,0 +1,117 @@
/*
* Copyright (c) 2021, Harald Kuhr
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.twelvemonkeys.imageio.plugins.tga;
import com.twelvemonkeys.io.enc.Encoder;
import com.twelvemonkeys.lang.Validate;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;
final class RLEEncoder implements Encoder {
private final int pixelSize;
RLEEncoder(final int pixelDepth) {
Validate.isTrue(pixelDepth % Byte.SIZE == 0, "Depth must be a multiple of bytes (8 bits)");
pixelSize = pixelDepth / Byte.SIZE;
}
public void encode(final OutputStream stream, final ByteBuffer buffer) throws IOException {
encode(stream, buffer.array(), buffer.arrayOffset() + buffer.position(), buffer.remaining());
buffer.position(buffer.remaining());
}
private void encode(final OutputStream stream, final byte[] buffer, final int pOffset, final int length) throws IOException {
// NOTE: It's best to encode a 2 byte repeat
// run as a replicate run except when preceded and followed by a
// literal run, in which case it's best to merge the three into one
// literal run. Always encode 3 byte repeats as replicate runs.
// Worst case: output = input + (input + 127) / 128
int offset = pOffset;
final int max = pOffset + length - pixelSize;
final int maxMinus1 = max - pixelSize;
while (offset <= max) {
// Compressed run
int run = 1;
while (run < 127 && offset < max && equalPixel(buffer, offset, offset + pixelSize)) {
offset += pixelSize;
run++;
}
if (run > 1) {
stream.write(0x80 | (run - 1));
stream.write(buffer, offset, pixelSize);
offset += pixelSize;
}
// Literal run
int runStart = offset;
run = 0;
while ((run < 127 && ((offset < max && !(equalPixel(buffer, offset, offset + pixelSize)))
|| (offset < maxMinus1 && !(equalPixel(buffer, offset, offset + 2 * pixelSize)))))) {
offset += pixelSize;
run++;
}
// If last pixel, include it in literal run, if space
if (offset == max && run > 0 && run < 127) {
offset += pixelSize;
run++;
}
if (run > 0) {
stream.write(run - 1);
stream.write(buffer, runStart, run * pixelSize);
}
// If last pixel, and not space, start new literal run
if (offset == max && (run <= 0 || run >= 127)) {
stream.write(0);
stream.write(buffer, offset, pixelSize);
offset += pixelSize;
}
}
}
private boolean equalPixel(final byte[] buffer, final int offset, int compareOffset) {
for (int i = 0; i < pixelSize; i++) {
if (buffer[offset + i] != buffer[compareOffset + i]) {
return false;
}
}
return true;
}
}
@@ -47,26 +47,26 @@ import static com.twelvemonkeys.imageio.plugins.tga.TGA.EXT_AREA_SIZE;
*/
final class TGAExtensions {
private String authorName;
private String authorComments;
String authorName;
String authorComments;
private Calendar creationDate;
private String jobId;
Calendar creationDate;
String jobId;
private String softwareId;
private String softwareVersion;
String softwareId;
String softwareVersion;
private int backgroundColor;
private double pixelAspectRatio;
private double gamma;
int backgroundColor;
double pixelAspectRatio;
double gamma;
private long colorCorrectionOffset;
private long postageStampOffset;
private long scanLineOffset;
long colorCorrectionOffset;
long postageStampOffset;
long scanLineOffset;
private int attributeType;
int attributeType;
private TGAExtensions() {
TGAExtensions() {
}
static TGAExtensions read(final ImageInputStream stream) throws IOException {
@@ -142,6 +142,7 @@ final class TGAExtensions {
return null;
}
//noinspection MagicConstant
calendar.set(year, month - 1, date, hourOfDay, minute, second);
return calendar;
@@ -176,6 +177,7 @@ final class TGAExtensions {
}
}
@SuppressWarnings("SwitchStatementWithTooFewBranches")
public boolean isAlphaPremultiplied() {
switch (attributeType) {
case 4:
@@ -31,7 +31,6 @@
package com.twelvemonkeys.imageio.plugins.tga;
import javax.imageio.IIOException;
import javax.imageio.ImageWriteParam;
import javax.imageio.stream.ImageInputStream;
import java.awt.image.ColorModel;
import java.awt.image.IndexColorModel;
@@ -58,9 +57,9 @@ final class TGAHeader {
private int height;
private int pixelDepth;
private int attributeBits;
private int origin;
int origin;
private int interleave;
private String identification;
String identification;
private IndexColorModel colorMap;
int getImageType() {
@@ -119,7 +118,7 @@ final class TGAHeader {
'}';
}
static TGAHeader from(final RenderedImage image, final ImageWriteParam param) {
static TGAHeader from(final RenderedImage image, final boolean compressed) {
notNull(image, "image");
ColorModel colorModel = image.getColorModel();
@@ -128,7 +127,7 @@ final class TGAHeader {
TGAHeader header = new TGAHeader();
header.colorMapType = colorMap != null ? 1 : 0;
header.imageType = getImageType(colorModel, param);
header.imageType = getImageType(colorModel, compressed);
header.colorMapStart = 0;
header.colorMapSize = colorMap != null ? colorMap.getMapSize() : 0;
header.colorMapDepth = colorMap != null ? (colorMap.hasAlpha() ? 32 : 24) : 0;
@@ -149,7 +148,7 @@ final class TGAHeader {
return header;
}
private static int getImageType(final ColorModel colorModel, final ImageWriteParam param) {
private static int getImageType(final ColorModel colorModel, final boolean compressed) {
int uncompressedType;
if (colorModel instanceof IndexColorModel) {
@@ -169,7 +168,7 @@ final class TGAHeader {
}
}
return uncompressedType | (TGAImageWriteParam.isRLE(param) ? 8 : 0);
return uncompressedType | (compressed ? 8 : 0);
}
void write(final DataOutput stream) throws IOException {
@@ -30,7 +30,13 @@
package com.twelvemonkeys.imageio.plugins.tga;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.imageio.ImageWriteParam;
import javax.imageio.metadata.IIOMetadata;
import javax.imageio.metadata.IIOMetadataFormatImpl;
import javax.imageio.metadata.IIOMetadataNode;
import java.util.Locale;
/**
@@ -42,14 +48,29 @@ public final class TGAImageWriteParam extends ImageWriteParam {
this(null);
}
@SuppressWarnings("WeakerAccess")
public TGAImageWriteParam(final Locale locale) {
super(locale);
canWriteCompressed = true;
compressionTypes = new String[]{"None", "RLE"};
}
static boolean isRLE(final ImageWriteParam param) {
return param != null && param.getCompressionMode() == MODE_EXPLICIT && "RLE".equals(param.getCompressionType());
static boolean isRLE(final ImageWriteParam param, final IIOMetadata metadata) {
return (param == null || param.canWriteCompressed() && param.getCompressionMode() == MODE_COPY_FROM_METADATA) && "RLE".equals(compressionTypeFromMetadata(metadata))
|| param != null && param.canWriteCompressed() && param.getCompressionMode() == MODE_EXPLICIT && "RLE".equals(param.getCompressionType());
}
private static String compressionTypeFromMetadata(final IIOMetadata metadata) {
if (metadata != null) {
IIOMetadataNode root = (IIOMetadataNode) metadata.getAsTree(IIOMetadataFormatImpl.standardMetadataFormatName);
NodeList compressionTypeName = root.getElementsByTagName("CompressionTypeName");
if (compressionTypeName.getLength() > 0) {
Node value = compressionTypeName.item(0).getAttributes().getNamedItem("value");
return value != null ? value.getNodeValue() : null;
}
}
return null;
}
}
@@ -31,18 +31,26 @@
package com.twelvemonkeys.imageio.plugins.tga;
import com.twelvemonkeys.imageio.ImageWriterBase;
import com.twelvemonkeys.imageio.util.IIOUtil;
import com.twelvemonkeys.imageio.util.ImageTypeSpecifiers;
import com.twelvemonkeys.io.LittleEndianDataOutputStream;
import com.twelvemonkeys.io.enc.EncoderStream;
import com.twelvemonkeys.lang.Validate;
import javax.imageio.*;
import javax.imageio.metadata.IIOMetadata;
import javax.imageio.spi.ImageWriterSpi;
import javax.imageio.stream.ImageOutputStream;
import java.awt.*;
import java.awt.color.ColorSpace;
import java.awt.image.*;
import java.io.DataOutput;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import static com.twelvemonkeys.imageio.plugins.tga.TGAImageWriteParam.isRLE;
import static com.twelvemonkeys.lang.Validate.notNull;
/**
@@ -55,13 +63,23 @@ final class TGAImageWriter extends ImageWriterBase {
@Override
public IIOMetadata getDefaultImageMetadata(final ImageTypeSpecifier imageType, final ImageWriteParam param) {
TGAHeader header = TGAHeader.from(imageType.createBufferedImage(1, 1), param);
Validate.notNull(imageType, "imageType");
TGAHeader header = TGAHeader.from(imageType.createBufferedImage(1, 1), isRLE(param, null));
return new TGAMetadata(header, null);
}
@Override
public IIOMetadata convertImageMetadata(final IIOMetadata inData, final ImageTypeSpecifier imageType, final ImageWriteParam param) {
return null;
Validate.notNull(inData, "inData");
Validate.notNull(imageType, "imageType");
if (inData instanceof TGAMetadata) {
return inData;
}
// TODO: Make metadata mutable, and do actual merge
return getDefaultImageMetadata(imageType, param);
}
@Override
@@ -73,16 +91,23 @@ final class TGAImageWriter extends ImageWriterBase {
}
}
@Override
public ImageWriteParam getDefaultWriteParam() {
return new TGAImageWriteParam(getLocale());
}
@Override
public void write(final IIOMetadata streamMetadata, final IIOImage image, final ImageWriteParam param) throws IOException {
assertOutput();
Validate.notNull(image, "image");
if (image.hasRaster()) {
throw new UnsupportedOperationException("Raster not supported");
}
final boolean compressed = isRLE(param, image.getMetadata());
RenderedImage renderedImage = image.getRenderedImage();
TGAHeader header = TGAHeader.from(renderedImage, param);
TGAHeader header = TGAHeader.from(renderedImage, compressed);
header.write(imageOutput);
@@ -94,7 +119,7 @@ final class TGAImageWriter extends ImageWriterBase {
? ImageTypeSpecifiers.createInterleaved(ColorSpace.getInstance(ColorSpace.CS_sRGB), new int[] {2, 1, 0}, DataBuffer.TYPE_BYTE, false, false).createBufferedImage(renderedImage.getWidth(), 1).getRaster()
: ImageTypeSpecifier.createFromRenderedImage(renderedImage).createBufferedImage(renderedImage.getWidth(), 1).getRaster();
DataBuffer buffer = rowRaster.getDataBuffer();
final DataBuffer buffer = rowRaster.getDataBuffer();
for (int tileY = 0; tileY < renderedImage.getNumYTiles(); tileY++) {
for (int tileX = 0; tileX < renderedImage.getNumXTiles(); tileX++) {
@@ -110,6 +135,8 @@ final class TGAImageWriter extends ImageWriterBase {
break;
}
DataOutput imageOutput = compressed ? createRLEStream(header, this.imageOutput) : this.imageOutput;
switch (buffer.getDataType()) {
case DataBuffer.TYPE_BYTE:
rowRaster.setDataElements(0, 0, raster.createChild(0, y, raster.getWidth(), 1, 0, 0, null));
@@ -118,22 +145,37 @@ final class TGAImageWriter extends ImageWriterBase {
case DataBuffer.TYPE_USHORT:
rowRaster.setDataElements(0, 0, raster.createChild(0, y, raster.getWidth(), 1, 0, 0, null));
short[] shorts = ((DataBufferUShort) buffer).getData();
imageOutput.writeShorts(shorts, 0, shorts.length);
// TODO: Get rid of this, due to stupid design in EncoderStream...
ByteBuffer bb = ByteBuffer.allocate(shorts.length * 2);
bb.order(ByteOrder.LITTLE_ENDIAN);
bb.asShortBuffer().put(shorts);
imageOutput.write(bb.array());
// TODO: The below should work just as good
// for (short value : shorts) {
// imageOutput.writeShort(value);
// }
break;
default:
throw new IIOException("Unsupported data");
throw new IIOException("Unsupported data type");
}
processImageProgress(tileY * 100f / renderedImage.getNumYTiles());
if (compressed) {
((LittleEndianDataOutputStream) imageOutput).close();
}
}
processImageProgress(tileY * 100f / renderedImage.getNumYTiles());
}
}
// TODO: If we have thumbnails, we need to write extension too.
processImageComplete();
}
private static LittleEndianDataOutputStream createRLEStream(final TGAHeader header, final ImageOutputStream stream) {
return new LittleEndianDataOutputStream(new EncoderStream(IIOUtil.createStreamAdapter(stream), new RLEEncoder(header.getPixelDepth())));
}
// TODO: Refactor to common util
@@ -78,7 +78,12 @@ final class TGAMetadata extends AbstractMetadata {
chroma.appendChild(numChannels);
switch (header.getPixelDepth()) {
case 8:
numChannels.setAttribute("value", Integer.toString(1));
if (header.getImageType() == TGA.IMAGETYPE_MONOCHROME || header.getImageType() == TGA.IMAGETYPE_MONOCHROME_RLE) {
numChannels.setAttribute("value", Integer.toString(1));
}
else {
numChannels.setAttribute("value", Integer.toString(3));
}
break;
case 16:
if (header.getAttributeBits() > 0 && extensions != null && extensions.hasAlpha()) {
@@ -146,7 +151,7 @@ final class TGAMetadata extends AbstractMetadata {
IIOMetadataNode compressionTypeName = new IIOMetadataNode("CompressionTypeName");
node.appendChild(compressionTypeName);
String value = header.getImageType() == TGA.IMAGETYPE_COLORMAPPED_HUFFMAN || header.getImageType() == TGA.IMAGETYPE_COLORMAPPED_HUFFMAN_QUADTREE
? "Uknown" : "RLE";
? "Unknown" : "RLE";
compressionTypeName.setAttribute("value", value);
IIOMetadataNode lossless = new IIOMetadataNode("Lossless");
@@ -155,7 +160,7 @@ final class TGAMetadata extends AbstractMetadata {
return node;
default:
// No compreesion
// No compression
return null;
}
}
@@ -199,10 +204,10 @@ final class TGAMetadata extends AbstractMetadata {
}
break;
case 24:
bitsPerSample.setAttribute("value", createListValue(3, Integer.toString(8)));
bitsPerSample.setAttribute("value", createListValue(3, "8"));
break;
case 32:
bitsPerSample.setAttribute("value", createListValue(4, Integer.toString(8)));
bitsPerSample.setAttribute("value", createListValue(4, "8"));
break;
}