Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
epoxy
GitHub Repository: epoxy/proj11
Path: blob/master/SLICK_HOME/src/org/newdawn/slick/imageout/TGAWriter.java
1461 views
1
package org.newdawn.slick.imageout;
2
3
import java.io.BufferedOutputStream;
4
import java.io.DataOutputStream;
5
import java.io.IOException;
6
import java.io.OutputStream;
7
8
import org.newdawn.slick.Color;
9
import org.newdawn.slick.Image;
10
11
/**
12
* A utility to save TGA's given a Slick image.
13
*
14
* @author Jon
15
*/
16
public class TGAWriter implements ImageWriter {
17
/**
18
* Flip the endian-ness of the short
19
*
20
* @param signedShort The short to flip
21
* @return The flipped short
22
*/
23
private static short flipEndian(short signedShort) {
24
int input = signedShort & 0xFFFF;
25
return (short) (input << 8 | (input & 0xFF00) >>> 8);
26
}
27
28
/**
29
* @see org.newdawn.slick.imageout.ImageWriter#saveImage(org.newdawn.slick.Image, java.lang.String, java.io.OutputStream, boolean)
30
*/
31
public void saveImage(Image image, String format, OutputStream output, boolean writeAlpha) throws IOException {
32
DataOutputStream out = new DataOutputStream(new BufferedOutputStream(output));
33
34
// ID Length
35
out.writeByte((byte) 0);
36
37
// Color Map
38
out.writeByte((byte) 0);
39
40
// Image Type
41
out.writeByte((byte) 2);
42
43
// Color Map - Ignored
44
out.writeShort(flipEndian((short) 0));
45
out.writeShort(flipEndian((short) 0));
46
out.writeByte((byte) 0);
47
48
// X, Y Offset
49
out.writeShort(flipEndian((short) 0));
50
out.writeShort(flipEndian((short) 0));
51
52
// Width, Height, Depth
53
out.writeShort(flipEndian((short) image.getWidth()));
54
out.writeShort(flipEndian((short) image.getHeight()));
55
if (writeAlpha) {
56
out.writeByte((byte) 32);
57
// Image Descriptor (can't be 0 since we're using 32-bit TGAs)
58
// needs to not have 0x20 set to indicate it's not a flipped image
59
out.writeByte((byte) 1);
60
} else {
61
out.writeByte((byte) 24);
62
// Image Descriptor (must be 0 since we're using 24-bit TGAs)
63
// needs to not have 0x20 set to indicate it's not a flipped image
64
out.writeByte((byte) 0);
65
}
66
67
68
// Write out the image data
69
Color c;
70
71
for (int y = 0; y < image.getHeight(); y++) {
72
for (int x = 0; x < image.getWidth(); x++) {
73
c = image.getColor(x, y);
74
75
out.writeByte((byte) (c.b * 255.0f));
76
out.writeByte((byte) (c.g * 255.0f));
77
out.writeByte((byte) (c.r * 255.0f));
78
if (writeAlpha) {
79
out.writeByte((byte) (c.a * 255.0f));
80
}
81
}
82
}
83
84
out.close();
85
}
86
}
87
88