1 
   2 /*
   3  * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
   4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   5  *
   6  * This code is free software; you can redistribute it and/or modify it
   7  * under the terms of the GNU General Public License version 2 only, as
   8  * published by the Free Software Foundation.  Oracle designates this
   9  * particular file as subject to the "Classpath" exception as provided
  10  * by Oracle in the LICENSE file that accompanied this code.
  11  *
  12  * This code is distributed in the hope that it will be useful, but WITHOUT
  13  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  14  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  15  * version 2 for more details (a copy is included in the LICENSE file that
  16  * accompanied this code).
  17  *
  18  * You should have received a copy of the GNU General Public License version
  19  * 2 along with this work; if not, write to the Free Software Foundation,
  20  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  21  *
  22  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  23  * or visit www.oracle.com if you need additional information or have any
  24  * questions.
  25  */
  26 
  27 
  28 package java.awt.image;
  29 
  30 import java.awt.color.ColorSpace;
  31 import java.awt.geom.Rectangle2D;
  32 import java.awt.Rectangle;
  33 import java.awt.RenderingHints;
  34 import java.awt.geom.Point2D;
  35 import sun.awt.image.ImagingLib;
  36 
  37 /**
  38  * This class implements a lookup operation from the source
  39  * to the destination.  The LookupTable object may contain a single array
  40  * or multiple arrays, subject to the restrictions below.
  41  * <p>
  42  * For Rasters, the lookup operates on bands.  The number of
  43  * lookup arrays may be one, in which case the same array is
  44  * applied to all bands, or it must equal the number of Source
  45  * Raster bands.
  46  * <p>
  47  * For BufferedImages, the lookup operates on color and alpha components.
  48  * The number of lookup arrays may be one, in which case the
  49  * same array is applied to all color (but not alpha) components.
  50  * Otherwise, the number of lookup arrays may
  51  * equal the number of Source color components, in which case no
  52  * lookup of the alpha component (if present) is performed.
  53  * If neither of these cases apply, the number of lookup arrays
  54  * must equal the number of Source color components plus alpha components,
  55  * in which case lookup is performed for all color and alpha components.
  56  * This allows non-uniform rescaling of multi-band BufferedImages.
  57  * <p>
  58  * BufferedImage sources with premultiplied alpha data are treated in the same
  59  * manner as non-premultiplied images for purposes of the lookup.  That is,
  60  * the lookup is done per band on the raw data of the BufferedImage source
  61  * without regard to whether the data is premultiplied.  If a color conversion
  62  * is required to the destination ColorModel, the premultiplied state of
  63  * both source and destination will be taken into account for this step.
  64  * <p>
  65  * Images with an IndexColorModel cannot be used.
  66  * <p>
  67  * If a RenderingHints object is specified in the constructor, the
  68  * color rendering hint and the dithering hint may be used when color
  69  * conversion is required.
  70  * <p>
  71  * This class allows the Source to be the same as the Destination.
  72  *
  73  * @see LookupTable
  74  * @see java.awt.RenderingHints#KEY_COLOR_RENDERING
  75  * @see java.awt.RenderingHints#KEY_DITHERING
  76  */
  77 
  78 public class LookupOp implements BufferedImageOp, RasterOp {
  79     private LookupTable ltable;
  80     private int numComponents;
  81     RenderingHints hints;
  82 
  83     /**
  84      * Constructs a {@code LookupOp} object given the lookup
  85      * table and a {@code RenderingHints} object, which might
  86      * be {@code null}.
  87      * @param lookup the specified {@code LookupTable}
  88      * @param hints the specified {@code RenderingHints},
  89      *        or {@code null}
  90      */
  91     public LookupOp(LookupTable lookup, RenderingHints hints) {
  92         this.ltable = lookup;
  93         this.hints  = hints;
  94         numComponents = ltable.getNumComponents();
  95     }
  96 
  97     /**
  98      * Returns the {@code LookupTable}.
  99      * @return the {@code LookupTable} of this
 100      *         {@code LookupOp}.
 101      */
 102     public final LookupTable getTable() {
 103         return ltable;
 104     }
 105 
 106     /**
 107      * Performs a lookup operation on a {@code BufferedImage}.
 108      * If the color model in the source image is not the same as that
 109      * in the destination image, the pixels will be converted
 110      * in the destination.  If the destination image is {@code null},
 111      * a {@code BufferedImage} will be created with an appropriate
 112      * {@code ColorModel}.  An {@code IllegalArgumentException}
 113      * might be thrown if the number of arrays in the
 114      * {@code LookupTable} does not meet the restrictions
 115      * stated in the class comment above, or if the source image
 116      * has an {@code IndexColorModel}.
 117      * @param src the {@code BufferedImage} to be filtered
 118      * @param dst the {@code BufferedImage} in which to
 119      *            store the results of the filter operation
 120      * @return the filtered {@code BufferedImage}.
 121      * @throws IllegalArgumentException if the number of arrays in the
 122      *         {@code LookupTable} does not meet the restrictions
 123      *         described in the class comments, or if the source image
 124      *         has an {@code IndexColorModel}.
 125      */
 126     public final BufferedImage filter(BufferedImage src, BufferedImage dst) {
 127         ColorModel srcCM = src.getColorModel();
 128         int numBands = srcCM.getNumColorComponents();
 129         ColorModel dstCM;
 130         if (srcCM instanceof IndexColorModel) {
 131             throw new
 132                 IllegalArgumentException("LookupOp cannot be "+
 133                                          "performed on an indexed image");
 134         }
 135         int numComponents = ltable.getNumComponents();
 136         if (numComponents != 1 &&
 137             numComponents != srcCM.getNumComponents() &&
 138             numComponents != srcCM.getNumColorComponents())
 139         {
 140             throw new IllegalArgumentException("Number of arrays in the "+
 141                                                " lookup table ("+
 142                                                numComponents+
 143                                                " is not compatible with the "+
 144                                                " src image: "+src);
 145         }
 146 
 147 
 148         boolean needToConvert = false;
 149 
 150         int width = src.getWidth();
 151         int height = src.getHeight();
 152 
 153         if (dst == null) {
 154             dst = createCompatibleDestImage(src, null);
 155             dstCM = srcCM;
 156         }
 157         else {
 158             if (width != dst.getWidth()) {
 159                 throw new
 160                     IllegalArgumentException("Src width ("+width+
 161                                              ") not equal to dst width ("+
 162                                              dst.getWidth()+")");
 163             }
 164             if (height != dst.getHeight()) {
 165                 throw new
 166                     IllegalArgumentException("Src height ("+height+
 167                                              ") not equal to dst height ("+
 168                                              dst.getHeight()+")");
 169             }
 170 
 171             dstCM = dst.getColorModel();
 172             if (srcCM.getColorSpace().getType() !=
 173                 dstCM.getColorSpace().getType())
 174             {
 175                 needToConvert = true;
 176                 dst = createCompatibleDestImage(src, null);
 177             }
 178 
 179         }
 180 
 181         BufferedImage origDst = dst;
 182 
 183         if (ImagingLib.filter(this, src, dst) == null) {
 184             // Do it the slow way
 185             WritableRaster srcRaster = src.getRaster();
 186             WritableRaster dstRaster = dst.getRaster();
 187 
 188             if (srcCM.hasAlpha()) {
 189                 if (numBands-1 == numComponents || numComponents == 1) {
 190                     int minx = srcRaster.getMinX();
 191                     int miny = srcRaster.getMinY();
 192                     int[] bands = new int[numBands-1];
 193                     for (int i=0; i < numBands-1; i++) {
 194                         bands[i] = i;
 195                     }
 196                     srcRaster =
 197                         srcRaster.createWritableChild(minx, miny,
 198                                                       srcRaster.getWidth(),
 199                                                       srcRaster.getHeight(),
 200                                                       minx, miny,
 201                                                       bands);
 202                 }
 203             }
 204             if (dstCM.hasAlpha()) {
 205                 int dstNumBands = dstRaster.getNumBands();
 206                 if (dstNumBands-1 == numComponents || numComponents == 1) {
 207                     int minx = dstRaster.getMinX();
 208                     int miny = dstRaster.getMinY();
 209                     int[] bands = new int[numBands-1];
 210                     for (int i=0; i < numBands-1; i++) {
 211                         bands[i] = i;
 212                     }
 213                     dstRaster =
 214                         dstRaster.createWritableChild(minx, miny,
 215                                                       dstRaster.getWidth(),
 216                                                       dstRaster.getHeight(),
 217                                                       minx, miny,
 218                                                       bands);
 219                 }
 220             }
 221 
 222             filter(srcRaster, dstRaster);
 223         }
 224 
 225         if (needToConvert) {
 226             // ColorModels are not the same
 227             ColorConvertOp ccop = new ColorConvertOp(hints);
 228             ccop.filter(dst, origDst);
 229         }
 230 
 231         return origDst;
 232     }
 233 
 234     /**
 235      * Performs a lookup operation on a {@code Raster}.
 236      * If the destination {@code Raster} is {@code null},
 237      * a new {@code Raster} will be created.
 238      * The {@code IllegalArgumentException} might be thrown
 239      * if the source {@code Raster} and the destination
 240      * {@code Raster} do not have the same
 241      * number of bands or if the number of arrays in the
 242      * {@code LookupTable} does not meet the
 243      * restrictions stated in the class comment above.
 244      * @param src the source {@code Raster} to filter
 245      * @param dst the destination {@code WritableRaster} for the
 246      *            filtered {@code src}
 247      * @return the filtered {@code WritableRaster}.
 248      * @throws IllegalArgumentException if the source and destinations
 249      *         rasters do not have the same number of bands, or the
 250      *         number of arrays in the {@code LookupTable} does
 251      *         not meet the restrictions described in the class comments.
 252      *
 253      */
 254     public final WritableRaster filter (Raster src, WritableRaster dst) {
 255         int numBands  = src.getNumBands();
 256         int height    = src.getHeight();
 257         int width     = src.getWidth();
 258         int[] srcPix  = new int[numBands];
 259 
 260         // Create a new destination Raster, if needed
 261 
 262         if (dst == null) {
 263             dst = createCompatibleDestRaster(src);
 264         }
 265         else if (height != dst.getHeight() || width != dst.getWidth()) {
 266             throw new
 267                 IllegalArgumentException ("Width or height of Rasters do not "+
 268                                           "match");
 269         }
 270         int dstLength = dst.getNumBands();
 271 
 272         if (numBands != dstLength) {
 273             throw new
 274                 IllegalArgumentException ("Number of channels in the src ("
 275                                           + numBands +
 276                                           ") does not match number of channels"
 277                                           + " in the destination ("
 278                                           + dstLength + ")");
 279         }
 280         int numComponents = ltable.getNumComponents();
 281         if (numComponents != 1 && numComponents != src.getNumBands()) {
 282             throw new IllegalArgumentException("Number of arrays in the "+
 283                                                " lookup table ("+
 284                                                numComponents+
 285                                                " is not compatible with the "+
 286                                                " src Raster: "+src);
 287         }
 288 
 289 
 290         if (ImagingLib.filter(this, src, dst) != null) {
 291             return dst;
 292         }
 293 
 294         // Optimize for cases we know about
 295         if (ltable instanceof ByteLookupTable) {
 296             byteFilter ((ByteLookupTable) ltable, src, dst,
 297                         width, height, numBands);
 298         }
 299         else if (ltable instanceof ShortLookupTable) {
 300             shortFilter ((ShortLookupTable) ltable, src, dst, width,
 301                          height, numBands);
 302         }
 303         else {
 304             // Not one we recognize so do it slowly
 305             int sminX = src.getMinX();
 306             int sY = src.getMinY();
 307             int dminX = dst.getMinX();
 308             int dY = dst.getMinY();
 309             for (int y=0; y < height; y++, sY++, dY++) {
 310                 int sX = sminX;
 311                 int dX = dminX;
 312                 for (int x=0; x < width; x++, sX++, dX++) {
 313                     // Find data for all bands at this x,y position
 314                     src.getPixel(sX, sY, srcPix);
 315 
 316                     // Lookup the data for all bands at this x,y position
 317                     ltable.lookupPixel(srcPix, srcPix);
 318 
 319                     // Put it back for all bands
 320                     dst.setPixel(dX, dY, srcPix);
 321                 }
 322             }
 323         }
 324 
 325         return dst;
 326     }
 327 
 328     /**
 329      * Returns the bounding box of the filtered destination image.  Since
 330      * this is not a geometric operation, the bounding box does not
 331      * change.
 332      * @param src the {@code BufferedImage} to be filtered
 333      * @return the bounds of the filtered definition image.
 334      */
 335     public final Rectangle2D getBounds2D (BufferedImage src) {
 336         return getBounds2D(src.getRaster());
 337     }
 338 
 339     /**
 340      * Returns the bounding box of the filtered destination Raster.  Since
 341      * this is not a geometric operation, the bounding box does not
 342      * change.
 343      * @param src the {@code Raster} to be filtered
 344      * @return the bounds of the filtered definition {@code Raster}.
 345      */
 346     public final Rectangle2D getBounds2D (Raster src) {
 347         return src.getBounds();
 348 
 349     }
 350 
 351     /**
 352      * Creates a zeroed destination image with the correct size and number of
 353      * bands.  If destCM is {@code null}, an appropriate
 354      * {@code ColorModel} will be used.
 355      * @param src       Source image for the filter operation.
 356      * @param destCM    the destination's {@code ColorModel}, which
 357      *                  can be {@code null}.
 358      * @return a filtered destination {@code BufferedImage}.
 359      */
 360     public BufferedImage createCompatibleDestImage (BufferedImage src,
 361                                                     ColorModel destCM) {
 362         BufferedImage image;
 363         int w = src.getWidth();
 364         int h = src.getHeight();
 365         int transferType = DataBuffer.TYPE_BYTE;
 366         if (destCM == null) {
 367             ColorModel cm = src.getColorModel();
 368             Raster raster = src.getRaster();
 369             if (cm instanceof ComponentColorModel) {
 370                 DataBuffer db = raster.getDataBuffer();
 371                 boolean hasAlpha = cm.hasAlpha();
 372                 boolean isPre    = cm.isAlphaPremultiplied();
 373                 int trans        = cm.getTransparency();
 374                 int[] nbits = null;
 375                 if (ltable instanceof ByteLookupTable) {
 376                     if (db.getDataType() == DataBuffer.TYPE_USHORT) {
 377                         // Dst raster should be of type byte
 378                         if (hasAlpha) {
 379                             nbits = new int[2];
 380                             if (trans == java.awt.Transparency.BITMASK) {
 381                                 nbits[1] = 1;
 382                             }
 383                             else {
 384                                 nbits[1] = 8;
 385                             }
 386                         }
 387                         else {
 388                             nbits = new int[1];
 389                         }
 390                         nbits[0] = 8;
 391                     }
 392                     // For byte, no need to change the cm
 393                 }
 394                 else if (ltable instanceof ShortLookupTable) {
 395                     transferType = DataBuffer.TYPE_USHORT;
 396                     if (db.getDataType() == DataBuffer.TYPE_BYTE) {
 397                         if (hasAlpha) {
 398                             nbits = new int[2];
 399                             if (trans == java.awt.Transparency.BITMASK) {
 400                                 nbits[1] = 1;
 401                             }
 402                             else {
 403                                 nbits[1] = 16;
 404                             }
 405                         }
 406                         else {
 407                             nbits = new int[1];
 408                         }
 409                         nbits[0] = 16;
 410                     }
 411                 }
 412                 if (nbits != null) {
 413                     cm = new ComponentColorModel(cm.getColorSpace(),
 414                                                  nbits, hasAlpha, isPre,
 415                                                  trans, transferType);
 416                 }
 417             }
 418             image = new BufferedImage(cm,
 419                                       cm.createCompatibleWritableRaster(w, h),
 420                                       cm.isAlphaPremultiplied(),
 421                                       null);
 422         }
 423         else {
 424             image = new BufferedImage(destCM,
 425                                       destCM.createCompatibleWritableRaster(w,
 426                                                                             h),
 427                                       destCM.isAlphaPremultiplied(),
 428                                       null);
 429         }
 430 
 431         return image;
 432     }
 433 
 434     /**
 435      * Creates a zeroed-destination {@code Raster} with the
 436      * correct size and number of bands, given this source.
 437      * @param src the {@code Raster} to be transformed
 438      * @return the zeroed-destination {@code Raster}.
 439      */
 440     public WritableRaster createCompatibleDestRaster (Raster src) {
 441         return src.createCompatibleWritableRaster();
 442     }
 443 
 444     /**
 445      * Returns the location of the destination point given a
 446      * point in the source.  If {@code dstPt} is not
 447      * {@code null}, it will be used to hold the return value.
 448      * Since this is not a geometric operation, the {@code srcPt}
 449      * will equal the {@code dstPt}.
 450      * @param srcPt a {@code Point2D} that represents a point
 451      *        in the source image
 452      * @param dstPt a {@code Point2D} that represents the location
 453      *        in the destination
 454      * @return the {@code Point2D} in the destination that
 455      *         corresponds to the specified point in the source.
 456      */
 457     public final Point2D getPoint2D (Point2D srcPt, Point2D dstPt) {
 458         if (dstPt == null) {
 459             dstPt = new Point2D.Float();
 460         }
 461         dstPt.setLocation(srcPt.getX(), srcPt.getY());
 462 
 463         return dstPt;
 464     }
 465 
 466     /**
 467      * Returns the rendering hints for this op.
 468      * @return the {@code RenderingHints} object associated
 469      *         with this op.
 470      */
 471     public final RenderingHints getRenderingHints() {
 472         return hints;
 473     }
 474 
 475     private void byteFilter(ByteLookupTable lookup, Raster src,
 476                                   WritableRaster dst,
 477                                   int width, int height, int numBands) {
 478         int[] srcPix = null;
 479 
 480         // Find the ref to the table and the offset
 481         byte[][] table = lookup.getTable();
 482         int offset = lookup.getOffset();
 483         int tidx;
 484         int step=1;
 485 
 486         // Check if it is one lookup applied to all bands
 487         if (table.length == 1) {
 488             step=0;
 489         }
 490 
 491         int x;
 492         int y;
 493         int band;
 494         int len = table[0].length;
 495 
 496         // Loop through the data
 497         for ( y=0; y < height; y++) {
 498             tidx = 0;
 499             for ( band=0; band < numBands; band++, tidx+=step) {
 500                 // Find data for this band, scanline
 501                 srcPix = src.getSamples(0, y, width, 1, band, srcPix);
 502 
 503                 for ( x=0; x < width; x++) {
 504                     int index = srcPix[x]-offset;
 505                     if (index < 0 || index > len) {
 506                         throw new
 507                             IllegalArgumentException("index ("+index+
 508                                                      "(out of range: "+
 509                                                      " srcPix["+x+
 510                                                      "]="+ srcPix[x]+
 511                                                      " offset="+ offset);
 512                     }
 513                     // Do the lookup
 514                     srcPix[x] = table[tidx][index];
 515                 }
 516                 // Put it back
 517                 dst.setSamples(0, y, width, 1, band, srcPix);
 518             }
 519         }
 520     }
 521 
 522     private void shortFilter(ShortLookupTable lookup, Raster src,
 523                                    WritableRaster dst,
 524                                    int width, int height, int numBands) {
 525         int band;
 526         int[] srcPix = null;
 527 
 528         // Find the ref to the table and the offset
 529         short[][] table = lookup.getTable();
 530         int offset = lookup.getOffset();
 531         int tidx;
 532         int step=1;
 533 
 534         // Check if it is one lookup applied to all bands
 535         if (table.length == 1) {
 536             step=0;
 537         }
 538 
 539         int x = 0;
 540         int y = 0;
 541         int index;
 542         int maxShort = (1<<16)-1;
 543         // Loop through the data
 544         for (y=0; y < height; y++) {
 545             tidx = 0;
 546             for ( band=0; band < numBands; band++, tidx+=step) {
 547                 // Find data for this band, scanline
 548                 srcPix = src.getSamples(0, y, width, 1, band, srcPix);
 549 
 550                 for ( x=0; x < width; x++) {
 551                     index = srcPix[x]-offset;
 552                     if (index < 0 || index > maxShort) {
 553                         throw new
 554                             IllegalArgumentException("index out of range "+
 555                                                      index+" x is "+x+
 556                                                      "srcPix[x]="+srcPix[x]
 557                                                      +" offset="+ offset);
 558                     }
 559                     // Do the lookup
 560                     srcPix[x] = table[tidx][index];
 561                 }
 562                 // Put it back
 563                 dst.setSamples(0, y, width, 1, band, srcPix);
 564             }
 565         }
 566     }
 567 }