| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
package uk.me.parabola.imgfmt.app.typ; |
| 14 |
|
| 15 |
import uk.me.parabola.imgfmt.app.BitWriter; |
| 16 |
import uk.me.parabola.imgfmt.app.ImgFileWriter; |
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
public class TrueImage implements Image { |
| 26 |
private final ColourInfo colourInfo; |
| 27 |
private final int[] image; |
| 28 |
|
| 29 |
|
| 30 |
private int transparentPixel; |
| 31 |
|
| 32 |
public TrueImage(ColourInfo colourInfo, int[] image) { |
| 33 |
analyzeColours(image, colourInfo); |
| 34 |
this.colourInfo = colourInfo; |
| 35 |
this.image = image; |
| 36 |
} |
| 37 |
|
| 38 |
|
| 39 |
|
| 40 |
|
| 41 |
|
| 42 |
|
| 43 |
|
| 44 |
|
| 45 |
|
| 46 |
public void write(ImgFileWriter writer) { |
| 47 |
int width = colourInfo.getWidth(); |
| 48 |
int height = colourInfo.getHeight(); |
| 49 |
|
| 50 |
int mode = colourInfo.getColourMode(); |
| 51 |
|
| 52 |
|
| 53 |
if (mode == 16) { |
| 54 |
writer.put1u(transparentPixel>>8); |
| 55 |
writer.put1u(transparentPixel>>16); |
| 56 |
writer.put1u(transparentPixel>>24); |
| 57 |
} |
| 58 |
|
| 59 |
boolean hasAlpha = mode == 32; |
| 60 |
|
| 61 |
|
| 62 |
|
| 63 |
BitWriter bitWriter = new BitWriter(); |
| 64 |
for (int h = 0; h < height; h++) { |
| 65 |
|
| 66 |
for (int w = 0; w < width; w++) { |
| 67 |
int col = image[h * width + w]; |
| 68 |
|
| 69 |
bitWriter.putn(col>>8 & 0xff, 8); |
| 70 |
bitWriter.putn(col>>16 & 0xff, 8); |
| 71 |
bitWriter.putn(col>>24 & 0xff, 8); |
| 72 |
|
| 73 |
if (hasAlpha) { |
| 74 |
int alpha = 0xff - (col & 0xff); |
| 75 |
alpha = ColourInfo.alphaRound4(alpha); |
| 76 |
bitWriter.putn(alpha, 4); |
| 77 |
} |
| 78 |
} |
| 79 |
} |
| 80 |
writer.put(bitWriter.getBytes(), 0, bitWriter.getLength()); |
| 81 |
} |
| 82 |
|
| 83 |
|
| 84 |
|
| 85 |
|
| 86 |
|
| 87 |
|
| 88 |
|
| 89 |
|
| 90 |
|
| 91 |
|
| 92 |
private void analyzeColours(int[] image, ColourInfo colourInfo) { |
| 93 |
boolean hasTransparent = false; |
| 94 |
boolean hasAlpha = false; |
| 95 |
|
| 96 |
int nPixels = colourInfo.getWidth() * colourInfo.getHeight(); |
| 97 |
for (int i = 0; i < nPixels; i++) { |
| 98 |
int col = image[i]; |
| 99 |
int a = col & 0xff; |
| 100 |
if (a == 0) { |
| 101 |
|
| 102 |
if (hasTransparent) |
| 103 |
image[i] = transparentPixel; |
| 104 |
else |
| 105 |
transparentPixel = image[i]; |
| 106 |
hasTransparent = true; |
| 107 |
} else if (a < 255) { |
| 108 |
|
| 109 |
hasAlpha = true; |
| 110 |
} |
| 111 |
} |
| 112 |
|
| 113 |
if (hasAlpha) |
| 114 |
colourInfo.setColourMode(32); |
| 115 |
else if (hasTransparent) |
| 116 |
colourInfo.setColourMode(16); |
| 117 |
} |
| 118 |
} |