summaryrefslogtreecommitdiffstats
path: root/awt/java/awt/image/IndexColorModel.java
blob: 0b06acda61047f4faa8fb97d63bf706a801d1fc3 (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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
/*
 *  Licensed to the Apache Software Foundation (ASF) under one or more
 *  contributor license agreements.  See the NOTICE file distributed with
 *  this work for additional information regarding copyright ownership.
 *  The ASF licenses this file to You under the Apache License, Version 2.0
 *  (the "License"); you may not use this file except in compliance with
 *  the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
/**
 * @author Igor V. Stolyarov
 * @version $Revision$
 */

package java.awt.image;

import java.awt.Transparency;
import java.awt.color.ColorSpace;
import java.math.BigInteger;

import org.apache.harmony.awt.internal.nls.Messages;

/**
 * The Class IndexColorModel represents a color model in which the color values
 * of the pixels are read from a palette.
 * 
 * @since Android 1.0
 */
public class IndexColorModel extends ColorModel {

    /**
     * The color map.
     */
    private int colorMap[]; // Color Map

    /**
     * The map size.
     */
    private int mapSize; // Color Map size

    /**
     * The transparent index.
     */
    private int transparentIndex; // Index of fully transparent pixel

    /**
     * The gray palette.
     */
    private boolean grayPalette; // Color Model has Color Map with Gray Pallete

    /**
     * The valid bits.
     */
    private BigInteger validBits; // Specify valid Color Map values

    /**
     * The Constant CACHESIZE.
     */
    private static final int CACHESIZE = 20; // Cache size. Cache used for

    // improving performace of selection
    // nearest color in Color Map

    /**
     * The cachetable.
     */
    private final int cachetable[] = new int[CACHESIZE * 2]; // Cache table -

    // used for

    // storing RGB values and that appropriate indices
    // in the Color Map

    /**
     * The next insert idx.
     */
    private int nextInsertIdx = 0; // Next index for insertion into Cache table

    /**
     * The total inserted.
     */
    private int totalInserted = 0; // Number of inserted values into Cache table

    /**
     * Instantiates a new index color model.
     * 
     * @param bits
     *            the array of component masks.
     * @param size
     *            the size of the color map.
     * @param cmap
     *            the array that gives the color mapping.
     * @param start
     *            the start index of the color mapping data within the cmap
     *            array.
     * @param transferType
     *            the transfer type (primitive java type to use for the
     *            components).
     * @param validBits
     *            a list of which bits represent valid colormap values, or null
     *            if all are valid.
     * @throws IllegalArgumentException
     *             if the size of the color map is less than one.
     */
    public IndexColorModel(int bits, int size, int cmap[], int start, int transferType,
            BigInteger validBits) {

        super(bits, IndexColorModel.createBits(true), ColorSpace.getInstance(ColorSpace.CS_sRGB),
                true, false, Transparency.OPAQUE, validateTransferType(transferType));

        if (size < 1) {
            // awt.264=Size of the color map is less than 1
            throw new IllegalArgumentException(Messages.getString("awt.264")); //$NON-NLS-1$
        }

        mapSize = size;
        colorMap = new int[mapSize];
        transparentIndex = -1;

        if (validBits != null) {
            for (int i = 0; i < mapSize; i++) {
                if (!validBits.testBit(i)) {
                    this.validBits = validBits;
                }
                break;
            }
        }

        transparency = Transparency.OPAQUE;
        int alphaMask = 0xff000000;
        int alpha = 0;

        for (int i = 0; i < mapSize; i++, start++) {
            colorMap[i] = cmap[start];
            alpha = cmap[start] & alphaMask;

            if (alpha == alphaMask) {
                continue;
            }
            if (alpha == 0) {
                if (transparentIndex < 0) {
                    transparentIndex = i;
                }
                if (transparency == Transparency.OPAQUE) {
                    transparency = Transparency.BITMASK;
                }
            } else if (alpha != alphaMask && transparency != Transparency.TRANSLUCENT) {
                transparency = Transparency.TRANSLUCENT;
            }

        }
        checkPalette();

    }

    /**
     * Instantiates a new index color model.
     * 
     * @param bits
     *            the array of component masks.
     * @param size
     *            the size of the color map.
     * @param cmap
     *            the array that gives the color mapping.
     * @param start
     *            the start index of the color mapping data within the cmap
     *            array.
     * @param hasalpha
     *            whether this color model uses alpha.
     * @param trans
     *            the transparency supported, @see java.awt.Transparency.
     * @param transferType
     *            the transfer type (primitive java type to use for the
     *            components).
     * @throws IllegalArgumentException
     *             if the size of the color map is less than one.
     */
    public IndexColorModel(int bits, int size, int cmap[], int start, boolean hasalpha, int trans,
            int transferType) {

        super(bits, IndexColorModel.createBits(hasalpha || (trans >= 0)), ColorSpace
                .getInstance(ColorSpace.CS_sRGB), (hasalpha || (trans >= 0)), false,
                Transparency.OPAQUE, validateTransferType(transferType));

        if (size < 1) {
            // awt.264=Size of the color map is less than 1
            throw new IllegalArgumentException(Messages.getString("awt.264")); //$NON-NLS-1$
        }

        mapSize = size;
        colorMap = new int[mapSize];
        if (trans >= 0 && trans < mapSize) {
            transparentIndex = trans;
            transparency = Transparency.BITMASK;
        } else {
            transparentIndex = -1;
            transparency = Transparency.OPAQUE;
        }

        int alphaMask = 0xff000000;
        int alpha = 0;

        for (int i = 0; i < mapSize; i++, start++) {
            if (transparentIndex == i) {
                colorMap[i] = cmap[start] & 0x00ffffff;
                continue;
            }
            if (hasalpha) {
                alpha = cmap[start] & alphaMask;
                colorMap[i] = cmap[start];

                if (alpha == alphaMask) {
                    continue;
                }
                if (alpha == 0) {
                    if (trans < 0) {
                        trans = i;
                    }
                    if (transparency == Transparency.OPAQUE) {
                        transparency = Transparency.BITMASK;
                    }
                } else if (alpha != 0 && transparency != Transparency.TRANSLUCENT) {
                    transparency = Transparency.TRANSLUCENT;
                }
            } else {
                colorMap[i] = alphaMask | cmap[start];
            }
        }
        checkPalette();

    }

    /**
     * Instantiates a new index color model by building the color map from
     * arrays of red, green, blue, and alpha values.
     * 
     * @param bits
     *            the array of component masks.
     * @param size
     *            the size of the color map.
     * @param r
     *            the array giving the red components of the entries in the
     *            color map.
     * @param g
     *            the array giving the green components of the entries in the
     *            color map.
     * @param b
     *            the array giving the blue components of the entries in the
     *            color map.
     * @param a
     *            the array giving the alpha components of the entries in the
     *            color map.
     * @throws IllegalArgumentException
     *             if the size of the color map is less than one.
     * @throws ArrayIndexOutOfBoundsException
     *             if the size of one of the component arrays is less than the
     *             size of the color map.
     */
    public IndexColorModel(int bits, int size, byte r[], byte g[], byte b[], byte a[]) {

        super(bits, IndexColorModel.createBits(true), ColorSpace.getInstance(ColorSpace.CS_sRGB),
                true, false, Transparency.OPAQUE, validateTransferType(ColorModel
                        .getTransferType(bits)));

        createColorMap(size, r, g, b, a, -1);
        checkPalette();
    }

    /**
     * Instantiates a new index color model by building the color map from
     * arrays of red, green, and blue values.
     * 
     * @param bits
     *            the array of component masks.
     * @param size
     *            the size of the color map.
     * @param r
     *            the array giving the red components of the entries in the
     *            color map.
     * @param g
     *            the array giving the green components of the entries in the
     *            color map.
     * @param b
     *            the array giving the blue components of the entries in the
     *            color map.
     * @param trans
     *            the transparency supported, @see java.awt.Transparency.
     * @throws IllegalArgumentException
     *             if the size of the color map is less than one.
     * @throws ArrayIndexOutOfBoundsException
     *             if the size of one of the component arrays is less than the
     *             size of the color map.
     */
    public IndexColorModel(int bits, int size, byte r[], byte g[], byte b[], int trans) {

        super(bits, IndexColorModel.createBits((trans >= 0)), ColorSpace
                .getInstance(ColorSpace.CS_sRGB), (trans >= 0), false, Transparency.OPAQUE,
                validateTransferType(ColorModel.getTransferType(bits)));

        createColorMap(size, r, g, b, null, trans);
        checkPalette();
    }

    /**
     * Instantiates a new index color model by building the color map from
     * arrays of red, green, and blue values.
     * 
     * @param bits
     *            the array of component masks.
     * @param size
     *            the size of the color map.
     * @param r
     *            the array giving the red components of the entries in the
     *            color map.
     * @param g
     *            the array giving the green components of the entries in the
     *            color map.
     * @param b
     *            the array giving the blue components of the entries in the
     *            color map.
     * @throws IllegalArgumentException
     *             if the size of the color map is less than one.
     * @throws ArrayIndexOutOfBoundsException
     *             if the size of one of the component arrays is less than the
     *             size of the color map.
     */
    public IndexColorModel(int bits, int size, byte r[], byte g[], byte b[]) {
        super(bits, IndexColorModel.createBits(false), ColorSpace.getInstance(ColorSpace.CS_sRGB),
                false, false, Transparency.OPAQUE, validateTransferType(ColorModel
                        .getTransferType(bits)));

        createColorMap(size, r, g, b, null, -1);
        checkPalette();
    }

    /**
     * Instantiates a new index color model.
     * 
     * @param bits
     *            the array of component masks.
     * @param size
     *            the size of the color map.
     * @param cmap
     *            the array that gives the color mapping.
     * @param start
     *            the start index of the color mapping data within the cmap
     *            array.
     * @param hasalpha
     *            whether this color model uses alpha.
     * @param trans
     *            the transparency supported, @see java.awt.Transparency.
     * @throws IllegalArgumentException
     *             if the size of the color map is less than one.
     */
    public IndexColorModel(int bits, int size, byte cmap[], int start, boolean hasalpha, int trans) {

        super(bits, IndexColorModel.createBits(hasalpha || (trans >= 0)), ColorSpace
                .getInstance(ColorSpace.CS_sRGB), (hasalpha || (trans >= 0)), false,
                Transparency.OPAQUE, validateTransferType(ColorModel.getTransferType(bits)));

        if (size < 1) {
            // awt.264=Size of the color map is less than 1
            throw new IllegalArgumentException(Messages.getString("awt.264")); //$NON-NLS-1$
        }

        mapSize = size;
        colorMap = new int[mapSize];
        transparentIndex = -1;

        transparency = Transparency.OPAQUE;
        int alpha = 0xff000000;

        for (int i = 0; i < mapSize; i++) {
            colorMap[i] = (cmap[start++] & 0xff) << 16 | (cmap[start++] & 0xff) << 8
                    | (cmap[start++] & 0xff);
            if (trans == i) {
                if (transparency == Transparency.OPAQUE) {
                    transparency = Transparency.BITMASK;
                }
                if (hasalpha) {
                    start++;
                }
                continue;
            }
            if (hasalpha) {
                alpha = cmap[start++] & 0xff;
                if (alpha == 0) {
                    if (transparency == Transparency.OPAQUE) {
                        transparency = Transparency.BITMASK;
                        if (trans < 0) {
                            trans = i;
                        }
                    }
                } else {
                    if (alpha != 0xff && transparency != Transparency.TRANSLUCENT) {
                        transparency = Transparency.TRANSLUCENT;
                    }
                }
                alpha <<= 24;
            }
            colorMap[i] |= alpha;
        }

        if (trans >= 0 && trans < mapSize) {
            transparentIndex = trans;
        }
        checkPalette();

    }

    /**
     * Instantiates a new index color model.
     * 
     * @param bits
     *            the array of component masks.
     * @param size
     *            the size of the color map.
     * @param cmap
     *            the array that gives the color mapping.
     * @param start
     *            the start index of the color mapping data within the cmap
     *            array.
     * @param hasalpha
     *            whether this color model uses alpha.
     * @throws IllegalArgumentException
     *             if the size of the color map is less than one.
     */
    public IndexColorModel(int bits, int size, byte cmap[], int start, boolean hasalpha) {

        this(bits, size, cmap, start, hasalpha, -1);
    }

    @Override
    public Object getDataElements(int[] components, int offset, Object pixel) {
        int rgb = (components[offset] << 16) | (components[offset + 1]) << 8
                | components[offset + 2];
        if (hasAlpha) {
            rgb |= components[offset + 3] << 24;
        } else {
            rgb |= 0xff000000;
        }
        return getDataElements(rgb, pixel);
    }

    @Override
    public synchronized Object getDataElements(int rgb, Object pixel) {
        int red = (rgb >> 16) & 0xff;
        int green = (rgb >> 8) & 0xff;
        int blue = rgb & 0xff;
        int alpha = rgb >>> 24;
        int pixIdx = 0;

        for (int i = 0; i < totalInserted; i++) {
            int idx = i * 2;
            if (rgb == cachetable[idx]) {
                return createDataObject(cachetable[idx + 1], pixel);
            }
        }

        if (!hasAlpha && grayPalette) {
            int grey = (red * 77 + green * 150 + blue * 29 + 128) >>> 8;
            int minError = 255;
            int error = 0;

            for (int i = 0; i < mapSize; i++) {
                error = Math.abs((colorMap[i] & 0xff) - grey);
                if (error < minError) {
                    pixIdx = i;
                    if (error == 0) {
                        break;
                    }
                    minError = error;
                }
            }
        } else if (alpha == 0 && transparentIndex > -1) {
            pixIdx = transparentIndex;
        } else {
            int minAlphaError = 255;
            int minError = 195075; // 255^2 + 255^2 + 255^2
            int alphaError;
            int error = 0;

            for (int i = 0; i < mapSize; i++) {
                int pix = colorMap[i];
                if (rgb == pix) {
                    pixIdx = i;
                    break;
                }
                alphaError = Math.abs(alpha - (pix >>> 24));
                if (alphaError <= minAlphaError) {
                    minAlphaError = alphaError;

                    int buf = ((pix >> 16) & 0xff) - red;
                    error = buf * buf;

                    if (error < minError) {
                        buf = ((pix >> 8) & 0xff) - green;
                        error += buf * buf;

                        if (error < minError) {
                            buf = (pix & 0xff) - blue;
                            error += buf * buf;

                            if (error < minError) {
                                pixIdx = i;
                                minError = error;
                            }
                        }
                    }
                }
            }
        }

        cachetable[nextInsertIdx] = rgb;
        cachetable[nextInsertIdx + 1] = pixIdx;

        nextInsertIdx = (nextInsertIdx + 2) % (CACHESIZE * 2);
        if (totalInserted < CACHESIZE) {
            totalInserted++;
        }

        return createDataObject(pixIdx, pixel);
    }

    /**
     * Converts an image from indexed to RGB format.
     * 
     * @param raster
     *            the raster containing the source image.
     * @param forceARGB
     *            whether to use the default RGB color model.
     * @return the buffered image.
     * @throws IllegalArgumentException
     *             if the raster is not compatible with this color model.
     */
    public BufferedImage convertToIntDiscrete(Raster raster, boolean forceARGB) {

        if (!isCompatibleRaster(raster)) {
            // awt.265=The raster argument is not compatible with this
            // IndexColorModel
            throw new IllegalArgumentException(Messages.getString("awt.265")); //$NON-NLS-1$
        }

        ColorModel model;
        if (forceARGB || transparency == Transparency.TRANSLUCENT) {
            model = ColorModel.getRGBdefault();
        } else if (transparency == Transparency.BITMASK) {
            model = new DirectColorModel(25, 0x00ff0000, 0x0000ff00, 0x000000ff, 0x01000000);
        } else {
            model = new DirectColorModel(24, 0x00ff0000, 0x0000ff00, 0x000000ff);
        }

        int w = raster.getWidth();
        int h = raster.getHeight();

        WritableRaster distRaster = model.createCompatibleWritableRaster(w, h);

        int minX = raster.getMinX();
        int minY = raster.getMinY();

        Object obj = null;
        int pixels[] = null;

        for (int i = 0; i < h; i++, minY++) {
            obj = raster.getDataElements(minX, minY, w, 1, obj);
            if (obj instanceof byte[]) {
                byte ba[] = (byte[])obj;
                if (pixels == null) {
                    pixels = new int[ba.length];
                }
                for (int j = 0; j < ba.length; j++) {
                    pixels[j] = colorMap[ba[j] & 0xff];
                }
            } else if (obj instanceof short[]) {
                short sa[] = (short[])obj;
                if (pixels == null) {
                    pixels = new int[sa.length];
                }
                for (int j = 0; j < sa.length; j++) {
                    pixels[j] = colorMap[sa[j] & 0xffff];
                }
            }
            if (obj instanceof int[]) {
                int ia[] = (int[])obj;
                if (pixels == null) {
                    pixels = new int[ia.length];
                }
                for (int j = 0; j < ia.length; j++) {
                    pixels[j] = colorMap[ia[j]];
                }
            }

            distRaster.setDataElements(0, i, w, 1, pixels);
        }

        return new BufferedImage(model, distRaster, false, null);
    }

    /**
     * Gets the valid pixels.
     * 
     * @return the valid pixels.
     */
    public BigInteger getValidPixels() {
        return validBits;
    }

    @Override
    public String toString() {
        // The output format based on 1.5 release behaviour.
        // It could be reveled such way:
        // BufferedImage bi = new BufferedImage(1, 1,
        // BufferedImage.TYPE_BYTE_INDEXED);
        // ColorModel cm = bi.getColorModel();
        // System.out.println(cm.toString());
        String str = "IndexColorModel: #pixel_bits = " + pixel_bits + //$NON-NLS-1$
                " numComponents = " + numComponents + " color space = " + cs + //$NON-NLS-1$ //$NON-NLS-2$
                " transparency = "; //$NON-NLS-1$

        if (transparency == Transparency.OPAQUE) {
            str = str + "Transparency.OPAQUE"; //$NON-NLS-1$
        } else if (transparency == Transparency.BITMASK) {
            str = str + "Transparency.BITMASK"; //$NON-NLS-1$
        } else {
            str = str + "Transparency.TRANSLUCENT"; //$NON-NLS-1$
        }

        str = str + " transIndex = " + transparentIndex + " has alpha = " + //$NON-NLS-1$ //$NON-NLS-2$
                hasAlpha + " isAlphaPre = " + isAlphaPremultiplied; //$NON-NLS-1$

        return str;
    }

    @Override
    public int[] getComponents(Object pixel, int components[], int offset) {
        int pixIdx = -1;
        if (pixel instanceof byte[]) {
            byte ba[] = (byte[])pixel;
            pixIdx = ba[0] & 0xff;
        } else if (pixel instanceof short[]) {
            short sa[] = (short[])pixel;
            pixIdx = sa[0] & 0xffff;
        } else if (pixel instanceof int[]) {
            int ia[] = (int[])pixel;
            pixIdx = ia[0];
        } else {
            // awt.219=This transferType is not supported by this color model
            throw new UnsupportedOperationException(Messages.getString("awt.219")); //$NON-NLS-1$
        }

        return getComponents(pixIdx, components, offset);
    }

    @Override
    public WritableRaster createCompatibleWritableRaster(int w, int h) {
        WritableRaster raster;
        if (pixel_bits == 1 || pixel_bits == 2 || pixel_bits == 4) {
            raster = Raster.createPackedRaster(DataBuffer.TYPE_BYTE, w, h, 1, pixel_bits, null);
        } else if (pixel_bits <= 8) {
            raster = Raster.createInterleavedRaster(DataBuffer.TYPE_BYTE, w, h, 1, null);
        } else if (pixel_bits <= 16) {
            raster = Raster.createInterleavedRaster(DataBuffer.TYPE_USHORT, w, h, 1, null);
        } else {
            // awt.266=The number of bits in a pixel is greater than 16
            throw new UnsupportedOperationException(Messages.getString("awt.266")); //$NON-NLS-1$
        }

        return raster;
    }

    @Override
    public boolean isCompatibleSampleModel(SampleModel sm) {
        if (sm == null) {
            return false;
        }

        if (!(sm instanceof MultiPixelPackedSampleModel) && !(sm instanceof ComponentSampleModel)) {
            return false;
        }

        if (sm.getTransferType() != transferType) {
            return false;
        }
        if (sm.getNumBands() != 1) {
            return false;
        }

        return true;
    }

    @Override
    public SampleModel createCompatibleSampleModel(int w, int h) {
        if (pixel_bits == 1 || pixel_bits == 2 || pixel_bits == 4) {
            return new MultiPixelPackedSampleModel(DataBuffer.TYPE_BYTE, w, h, pixel_bits);
        }
        int bandOffsets[] = new int[1];
        bandOffsets[0] = 0;
        return new ComponentSampleModel(transferType, w, h, 1, w, bandOffsets);

    }

    @Override
    public boolean isCompatibleRaster(Raster raster) {
        int sampleSize = raster.getSampleModel().getSampleSize(0);
        return (raster.getTransferType() == transferType && raster.getNumBands() == 1 && (1 << sampleSize) >= mapSize);
    }

    @Override
    public int getDataElement(int components[], int offset) {
        int rgb = (components[offset] << 16) | (components[offset + 1]) << 8
                | components[offset + 2];

        if (hasAlpha) {
            rgb |= components[offset + 3] << 24;
        } else {
            rgb |= 0xff000000;
        }

        int pixel;

        switch (transferType) {
            case DataBuffer.TYPE_BYTE:
                byte ba[] = (byte[])getDataElements(rgb, null);
                pixel = ba[0] & 0xff;
                break;
            case DataBuffer.TYPE_USHORT:
                short sa[] = (short[])getDataElements(rgb, null);
                pixel = sa[0] & 0xffff;
                break;
            default:
                // awt.267=The transferType is invalid
                throw new UnsupportedOperationException(Messages.getString("awt.267")); //$NON-NLS-1$
        }

        return pixel;
    }

    /**
     * Gets the color map.
     * 
     * @param rgb
     *            the destination array where the color map is written.
     */
    public final void getRGBs(int rgb[]) {
        System.arraycopy(colorMap, 0, rgb, 0, mapSize);
    }

    /**
     * Gets the red component of the color map.
     * 
     * @param r
     *            the destination array.
     */
    public final void getReds(byte r[]) {
        for (int i = 0; i < mapSize; i++) {
            r[i] = (byte)(colorMap[i] >> 16);
        }
    }

    /**
     * Gets the green component of the color map.
     * 
     * @param g
     *            the destination array.
     */
    public final void getGreens(byte g[]) {
        for (int i = 0; i < mapSize; i++) {
            g[i] = (byte)(colorMap[i] >> 8);
        }
    }

    /**
     * Gets the blue component of the color map.
     * 
     * @param b
     *            the destination array.
     */
    public final void getBlues(byte b[]) {
        for (int i = 0; i < mapSize; i++) {
            b[i] = (byte)colorMap[i];
        }
    }

    /**
     * Gets the alpha component of the color map.
     * 
     * @param a
     *            the destination array.
     */
    public final void getAlphas(byte a[]) {
        for (int i = 0; i < mapSize; i++) {
            a[i] = (byte)(colorMap[i] >> 24);
        }
    }

    @Override
    public int[] getComponents(int pixel, int components[], int offset) {
        if (components == null) {
            components = new int[offset + numComponents];
        }

        components[offset + 0] = getRed(pixel);
        components[offset + 1] = getGreen(pixel);
        components[offset + 2] = getBlue(pixel);
        if (hasAlpha && (components.length - offset) > 3) {
            components[offset + 3] = getAlpha(pixel);
        }

        return components;
    }

    /**
     * Checks if the specified pixel is valid for this color model.
     * 
     * @param pixel
     *            the pixel.
     * @return true, if the pixel is valid.
     */
    public boolean isValid(int pixel) {
        if (validBits == null) {
            return (pixel >= 0 && pixel < mapSize);
        }
        return (pixel < mapSize && validBits.testBit(pixel));
    }

    @Override
    public final int getRed(int pixel) {
        return (colorMap[pixel] >> 16) & 0xff;
    }

    @Override
    public final int getRGB(int pixel) {
        return colorMap[pixel];
    }

    @Override
    public final int getGreen(int pixel) {
        return (colorMap[pixel] >> 8) & 0xff;
    }

    @Override
    public final int getBlue(int pixel) {
        return colorMap[pixel] & 0xff;
    }

    @Override
    public final int getAlpha(int pixel) {
        return (colorMap[pixel] >> 24) & 0xff;
    }

    @Override
    public int[] getComponentSize() {
        return bits.clone();
    }

    /**
     * Checks if this color model validates pixels.
     * 
     * @return true, if all pixels are valid, otherwise false.
     */
    public boolean isValid() {
        return (validBits == null);
    }

    @Override
    public void finalize() {
        // TODO: implement
        return;
    }

    /**
     * Gets the index that represents the transparent pixel.
     * 
     * @return the index that represents the transparent pixel.
     */
    public final int getTransparentPixel() {
        return transparentIndex;
    }

    @Override
    public int getTransparency() {
        return transparency;
    }

    /**
     * Gets the size of the color map.
     * 
     * @return the map size.
     */
    public final int getMapSize() {
        return mapSize;
    }

    /**
     * Creates the color map.
     * 
     * @param size
     *            the size.
     * @param r
     *            the r.
     * @param g
     *            the g.
     * @param b
     *            the b.
     * @param a
     *            the a.
     * @param trans
     *            the trans.
     */
    private void createColorMap(int size, byte r[], byte g[], byte b[], byte a[], int trans) {
        if (size < 1) {
            // awt.264=Size of the color map is less than 1
            throw new IllegalArgumentException(Messages.getString("awt.264")); //$NON-NLS-1$
        }

        mapSize = size;
        colorMap = new int[mapSize];
        if (trans >= 0 && trans < mapSize) {
            transparency = Transparency.BITMASK;
            transparentIndex = trans;
        } else {
            transparency = Transparency.OPAQUE;
            transparentIndex = -1;
        }
        int alpha = 0;

        for (int i = 0; i < mapSize; i++) {
            colorMap[i] = ((r[i] & 0xff) << 16) | ((g[i] & 0xff) << 8) | (b[i] & 0xff);

            if (trans == i) {
                continue;
            }

            if (a == null) {
                colorMap[i] |= 0xff000000;
            } else {
                alpha = a[i] & 0xff;
                if (alpha == 0xff) {
                    colorMap[i] |= 0xff000000;
                } else if (alpha == 0) {
                    if (transparency == Transparency.OPAQUE) {
                        transparency = Transparency.BITMASK;
                    }
                    if (transparentIndex < 0) {
                        transparentIndex = i;
                    }
                } else {
                    colorMap[i] |= (a[i] & 0xff) << 24;
                    if (transparency != Transparency.TRANSLUCENT) {
                        transparency = Transparency.TRANSLUCENT;
                    }
                }
            }

        }

    }

    /**
     * This method checking, if Color Map has Gray palette.
     */
    private void checkPalette() {
        grayPalette = false;
        if (transparency > Transparency.OPAQUE) {
            return;
        }
        int rgb = 0;

        for (int i = 0; i < mapSize; i++) {
            rgb = colorMap[i];
            if (((rgb >> 16) & 0xff) != ((rgb >> 8) & 0xff) || ((rgb >> 8) & 0xff) != (rgb & 0xff)) {
                return;
            }
        }
        grayPalette = true;
    }

    /**
     * Construction an array pixel representation.
     * 
     * @param colorMapIdx
     *            the index into Color Map.
     * @param pixel
     *            the pixel
     * @return the pixel representation array.
     */
    private Object createDataObject(int colorMapIdx, Object pixel) {
        if (pixel == null) {
            switch (transferType) {
                case DataBuffer.TYPE_BYTE:
                    byte[] ba = new byte[1];
                    ba[0] = (byte)colorMapIdx;
                    pixel = ba;
                    break;
                case DataBuffer.TYPE_USHORT:
                    short[] sa = new short[1];
                    sa[0] = (short)colorMapIdx;
                    pixel = sa;
                    break;
                default:
                    // awt.267=The transferType is invalid
                    throw new UnsupportedOperationException(Messages.getString("awt.267")); //$NON-NLS-1$
            }
        } else if (pixel instanceof byte[] && transferType == DataBuffer.TYPE_BYTE) {
            byte ba[] = (byte[])pixel;
            ba[0] = (byte)colorMapIdx;
            pixel = ba;
        } else if (pixel instanceof short[] && transferType == DataBuffer.TYPE_USHORT) {
            short[] sa = (short[])pixel;
            sa[0] = (short)colorMapIdx;
            pixel = sa;
        } else if (pixel instanceof int[]) {
            int ia[] = (int[])pixel;
            ia[0] = colorMapIdx;
            pixel = ia;
        } else {
            // awt.268=The pixel is not a primitive array of type transferType
            throw new ClassCastException(Messages.getString("awt.268")); //$NON-NLS-1$
        }
        return pixel;
    }

    /**
     * Creates the bits.
     * 
     * @param hasAlpha
     *            the has alpha.
     * @return the int[].
     */
    private static int[] createBits(boolean hasAlpha) {

        int numChannels;
        if (hasAlpha) {
            numChannels = 4;
        } else {
            numChannels = 3;
        }

        int bits[] = new int[numChannels];
        for (int i = 0; i < numChannels; i++) {
            bits[i] = 8;
        }

        return bits;

    }

    /**
     * Validate transfer type.
     * 
     * @param transferType
     *            the transfer type.
     * @return the int.
     */
    private static int validateTransferType(int transferType) {
        if (transferType != DataBuffer.TYPE_BYTE && transferType != DataBuffer.TYPE_USHORT) {
            // awt.269=The transferType is not one of DataBuffer.TYPE_BYTE or
            // DataBuffer.TYPE_USHORT
            throw new IllegalArgumentException(Messages.getString("awt.269")); //$NON-NLS-1$
        }
        return transferType;
    }

    /**
     * Checks if is gray palette.
     * 
     * @return true, if is gray palette.
     */
    boolean isGrayPallete() {
        return grayPalette;
    }

}