aboutsummaryrefslogtreecommitdiffstats
path: root/src/jake2/imageio/PCXImageReader.java
blob: c81e623c8cdb01dfa6c86b42822aeaf5c23d2ebf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
/*
 * Created on Nov 17, 2003
 *
 */
package jake2.imageio;

import java.awt.Point;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.awt.image.DataBuffer;
import java.awt.image.DataBufferByte;
import java.awt.image.Raster;
import java.awt.image.WritableRaster;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.imageio.IIOException;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.ImageTypeSpecifier;
import javax.imageio.metadata.IIOMetadata;
import javax.imageio.spi.ImageReaderSpi;
import javax.imageio.stream.ImageInputStream;

/**
 * @author cwei
 *
 */
public class PCXImageReader extends ImageReader {

	private static Logger logger =
		Logger.getLogger(PCXImageReader.class.getName());

	ImageInputStream stream = null;
	PCX.Header header = null;

	public PCXImageReader(ImageReaderSpi originatingProvider) {
		super(originatingProvider);
	}

	public void setInput(Object input, boolean seekForwardOnly) {
		super.setInput(input, seekForwardOnly);
		if (input == null) {
			this.stream = null;
			return;
		}
		if (input instanceof ImageInputStream) {
			this.stream = (ImageInputStream) input;
		} else {
			throw new IllegalArgumentException("bad input");
		}
	}

	public int getHeight(int imageIndex) throws IOException {
		checkIndex(imageIndex);
		readHeader();
		return header.getHeight();
	}

	public int getWidth(int imageIndex) throws IOException {
		checkIndex(imageIndex);
		readHeader();
		return header.getWidth();
	}

	public int getNumImages(boolean allowSearch) throws IOException {
		// only 1 image
		return 1;
	}

	public Iterator getImageTypes(int imageIndex) throws IOException {
		checkIndex(imageIndex);
		readHeader();

		ImageTypeSpecifier imageType = null;
		java.util.List l = new ArrayList(1);

		imageType =
			ImageTypeSpecifier.createIndexed(
				Q2ColorMap.RED,
				Q2ColorMap.GREEN,
				Q2ColorMap.BLUE,
				Q2ColorMap.ALPHA,
				8,
				DataBuffer.TYPE_BYTE);

		l.add(imageType);
		return l.iterator();
	}

	public IIOMetadata getStreamMetadata() throws IOException {
		return null;
	}

	public IIOMetadata getImageMetadata(int imageIndex) throws IOException {
		return null;
	}

	public BufferedImage read(int imageIndex, ImageReadParam param)
		throws IOException {

		checkIndex(imageIndex);
		readHeader();

		int width = header.getWidth();
		int height = header.getHeight();

		//		Compute initial source region, clip against destination later
		Rectangle sourceRegion = getSourceRegion(param, width, height);

		// Set everything to default values
		int sourceXSubsampling = 1;
		int sourceYSubsampling = 1;
		int[] sourceBands = null;
		int[] destinationBands = null;
		Point destinationOffset = new Point(0, 0);

		// Get values from the ImageReadParam, if any
		if (param != null) {
			sourceXSubsampling = param.getSourceXSubsampling();
			sourceYSubsampling = param.getSourceYSubsampling();
			sourceBands = param.getSourceBands();
			destinationBands = param.getDestinationBands();
			destinationOffset = param.getDestinationOffset();
		}

		//		 Get the specified detination image or create a new one
		BufferedImage dst =
			getDestination(param, getImageTypes(0), width, height);

		// Enure band settings from param are compatible with images
		int inputBands = 1;
		checkReadParamBandSettings(
			param,
			inputBands,
			dst.getSampleModel().getNumBands());

		int[] bandOffsets = new int[inputBands];
		for (int i = 0; i < inputBands; i++) {
			bandOffsets[i] = i;
		}
		int bytesPerRow = width * inputBands;
		DataBufferByte rowDB = new DataBufferByte(bytesPerRow);
		WritableRaster rowRas =
			Raster.createInterleavedRaster(
				rowDB,
				width,
				1,
				bytesPerRow,
				inputBands,
				bandOffsets,
				new Point(0, 0));
		byte[] rowBuf = rowDB.getData();

		// Create an int[] that can a single pixel
		int[] pixel = rowRas.getPixel(0, 0, (int[]) null);

		WritableRaster imRas = dst.getWritableTile(0, 0);
		int dstMinX = imRas.getMinX();
		int dstMaxX = dstMinX + imRas.getWidth() - 1;
		int dstMinY = imRas.getMinY();
		int dstMaxY = dstMinY + imRas.getHeight() - 1;

		// Create a child raster exposing only the desired source bands
		if (sourceBands != null) {
			rowRas =
				rowRas.createWritableChild(0, 0, width, 1, 0, 0, sourceBands);
		}

		// Create a child raster exposing only the desired dest bands
		if (destinationBands != null) {
			imRas =
				imRas.createWritableChild(
					0,
					0,
					imRas.getWidth(),
					imRas.getHeight(),
					0,
					0,
					destinationBands);

		}

		int dataByte = 0;
		int runLength = 0;

		for (int srcY = 0; srcY < height; srcY++) {
			// Read the row
			try {
				/*
				 * run length decoding for PCX images
				 */
				int index = 0;

				while (index < rowBuf.length) {
					while (runLength-- > 0 && index < rowBuf.length) {
						rowBuf[index++] = (byte) (dataByte & 0xff);
					}
					dataByte = stream.readUnsignedByte();
					if ((dataByte & 0xc0) == 0xc0) {
						runLength = dataByte & 0x3f;
						dataByte = stream.readUnsignedByte();
					} else {
						runLength = 1;
					}
				}
			} catch (IOException e) {
				throw new IIOException("Error reading line " + srcY, e);
			}

			// Reject rows that lie outside the source region,
			// or which aren't part of the subsampling
			if ((srcY < sourceRegion.y)
				|| (srcY >= sourceRegion.y + sourceRegion.height)
				|| (((srcY - sourceRegion.y) % sourceYSubsampling) != 0)) {
				continue;
			}

			// Determine where the row will go in the destination
			int dstY =
				destinationOffset.y
					+ (srcY - sourceRegion.y) / sourceYSubsampling;
			if (dstY < dstMinY) {
				continue; // The row is above imRas
			}
			if (dstY > dstMaxY) {
				break; // We're done with the image
			}

			// Copy each (subsampled) source pixel into imRas
			for (int srcX = sourceRegion.x;
				srcX < sourceRegion.x + sourceRegion.width;
				srcX++) {
				if (((srcX - sourceRegion.x) % sourceXSubsampling) != 0) {
					continue;
				}
				int dstX =
					destinationOffset.x
						+ (srcX - sourceRegion.x) / sourceXSubsampling;
				if (dstX < dstMinX) {
					continue; // The pixel is to the left of imRas
				}
				if (dstX > dstMaxX) {
					break; // We're done with the row
				}

				// Copy the pixel, sub-banding is done automatically
				rowRas.getPixel(srcX, 0, pixel);
				imRas.setPixel(dstX, dstY, pixel);
			}
		}
		if ((stream.readUnsignedByte()) == 0x0c) {
			logger.log(
				Level.FINE,
				"PCX has a color palette with "
					+ (stream.length() - stream.getStreamPosition())
					+ " Bytes, but use the default palette (quake2)");
		}
		return dst;
	}

	private void checkIndex(int imageIndex) {
		if (imageIndex != 0) {
			throw new IndexOutOfBoundsException("bad image index");
		}
	}

// buggy version 
/*	private void decodeRow(byte[] buffer) throws IOException {
		int dataByte = 0;
		int runLength = 0;
		int index = 0;

		while (index < buffer.length) {
			dataByte = stream.readUnsignedByte();
			if ((dataByte & 0xc0) == 0xc0) {
				runLength = dataByte & 0x3f;
				dataByte = stream.readUnsignedByte();
			} else {
				runLength = 1;
			}

			while (runLength-- > 0 && index < buffer.length) {
				buffer[index++] = (byte) (dataByte & 0xff);
			}
			assert(runLength == -1) : "runLength decoding bug: " + runLength;
		}
	}
*/
	private void readHeader() throws IIOException {

		if (header != null)
			return;

		logger.log(Level.FINE, "PCX read header");

		if (stream == null) {
			if (this.input == null) {
				throw new IllegalStateException("No input stream");
			}
			stream = (ImageInputStream) input;
		}

		byte[] buffer = new byte[PCX.HEADER_SIZE];

		try {
			stream.readFully(buffer);
			this.header = new PCX.Header(buffer);
			logger.log(
				Level.FINE,
				"PCX horzRes: "
					+ header.getWidth()
					+ " height: "
					+ header.getHeight());
		} catch (IOException e) {
			throw new IIOException("Error reading quake2 PCX header", e);
		}
	}
}