Example #1
0
 private static int calculateColor(float[] f, ColorSpace colorSpace) {
   int n = colorSpace.getNumComponents();
   // Get the reverse of f, and only take n values
   // Might as well limit the bounds while we're at it
   float[] fvalue = new float[n];
   int toCopy = n;
   int fLength = f.length;
   if (fLength < toCopy) {
     toCopy = fLength;
   }
   for (int i = 0; i < toCopy; i++) {
     float curr = f[fLength - 1 - i];
     if (curr < 0.0f) {
       curr = 0.0f;
     } else if (curr > 1.0f) {
       curr = 1.0f;
     }
     fvalue[i] = curr;
   }
   float[] frgbvalue = colorSpace.toRGB(fvalue);
   return (0xFF000000)
       | ((((int) (frgbvalue[0] * 255)) & 0xFF) << 16)
       | ((((int) (frgbvalue[1] * 255)) & 0xFF) << 8)
       | ((((int) (frgbvalue[2] * 255)) & 0xFF));
 }
Example #2
0
 /**
  * Returns a <code>float</code> array containing the color and alpha components of the <code>Color
  * </code>, in the <code>ColorSpace</code> specified by the <code>cspace</code> parameter. If
  * <code>compArray</code> is <code>null</code>, an array with length equal to the number of
  * components in <code>cspace</code> plus one is created for the return value. Otherwise, <code>
  * compArray</code> must have at least this length, and it is filled in with the components and
  * returned.
  *
  * @param cspace a specified <code>ColorSpace</code>
  * @param compArray an array that this method fills with the color and alpha components of this
  *     <code>Color</code> in the specified <code>ColorSpace</code> and returns
  * @return the color and alpha components in a <code>float</code> array.
  */
 @Override
 public float[] getComponents(ColorSpace cspace, float[] compArray) {
   if (cs == null) {
     cs = ColorSpace.getInstance(ColorSpace.CS_sRGB);
   }
   float f[];
   if (fvalue == null) {
     f = new float[3];
     f[0] = ((float) getRed()) / 255f;
     f[1] = ((float) getGreen()) / 255f;
     f[2] = ((float) getBlue()) / 255f;
   } else {
     f = fvalue;
   }
   float tmp[] = cs.toCIEXYZ(f);
   float tmpout[] = cspace.fromCIEXYZ(tmp);
   if (compArray == null) {
     compArray = new float[tmpout.length + 1];
   }
   for (int i = 0; i < tmpout.length; i++) {
     compArray[i] = tmpout[i];
   }
   if (fvalue == null) {
     compArray[tmpout.length] = ((float) getAlpha()) / 255f;
   } else {
     compArray[tmpout.length] = falpha;
   }
   return compArray;
 }
 @Override
 public String getName(GridCoverage2DReader reader, Map<String, String> map) {
   ImageLayout layout;
   String coverageName = null;
   try {
     layout = reader.getImageLayout();
     ColorModel cm = layout.getColorModel(null);
     ColorSpace cs = cm.getColorSpace();
     int type = cs.getType();
     switch (type) {
       case ColorSpace.TYPE_GRAY:
         coverageName = GRAY;
         break;
       case ColorSpace.TYPE_RGB:
         coverageName = RGB;
         break;
       default:
         throw new IllegalArgumentException(
             "The specified ColorSpace's type is not supported: " + type);
     }
   } catch (IOException e) {
     throw new IllegalArgumentException(e);
   }
   return coverageName;
 }
Example #4
0
 /**
  * Creates a color in the specified <code>ColorSpace</code> with the color components specified in
  * the <code>float</code> array and the specified alpha. The number of components is determined by
  * the type of the <code>ColorSpace</code>. For example, RGB requires 3 components, but CMYK
  * requires 4 components.
  *
  * @param cspace the <code>ColorSpace</code> to be used to interpret the components
  * @param components an arbitrary number of color components that is compatible with the <code>
  *     ColorSpace</code>
  * @param alpha alpha value
  * @throws IllegalArgumentException if any of the values in the <code>components</code> array or
  *     <code>alpha</code> is outside of the range supported by cspace.
  * @see #getComponents
  * @see #getColorComponents
  */
 public CompositeColor(ColorSpace cspace, float components[], float alpha) {
   super(((int) (alpha * 255) << 24) | ColorUtil.toRGB24(cspace, components), true);
   boolean rangeError = false;
   StringBuilder badComponentString = new StringBuilder();
   int n = cspace.getNumComponents();
   fvalue = new float[n];
   for (int i = 0; i < n; i++) {
     if (components[i] < cspace.getMinValue(i) || components[i] > cspace.getMaxValue(i)) {
       rangeError = true;
       badComponentString.append("Component ");
       badComponentString.append(i);
       badComponentString.append(' ');
     } else {
       fvalue[i] = components[i];
     }
   }
   if (alpha < 0.0 || alpha > 1.0) {
     rangeError = true;
     badComponentString.append("Alpha");
   } else {
     falpha = alpha;
   }
   if (rangeError) {
     throw new IllegalArgumentException(
         "Color parameter outside of expected range: " + badComponentString);
   }
   cs = cspace;
 }
  public ColorModel createColorModel() {
    int[] bits;
    if (hasAlpha) bits = new int[cspace.getNumComponents() + 1];
    else bits = new int[cspace.getNumComponents()];
    Arrays.fill(bits, 8);

    return new ComponentColorModel(cspace, bits, hasAlpha, alphaPre, transparency, transferType);
  }
  // Create an appropriate array of bits, given a colorspace (ie, number of
  // bands), size of the storage data type, and presence of an alpha band.
  private static int[] findBits(ColorSpace colorSpace, int transferType, boolean hasAlpha) {
    int[] bits;
    if (hasAlpha) bits = new int[colorSpace.getNumComponents() + 1];
    else bits = new int[colorSpace.getNumComponents()];

    Arrays.fill(bits, DataBuffer.getDataTypeSize(transferType));

    return bits;
  }
  /**
   * Create string representation of a fop-rgb-icc (or fop-rgb-named-color) function call from the
   * given color.
   *
   * @param color the color to turn into a function call
   * @return the string representing the internal fop-rgb-icc() or fop-rgb-named-color() function
   *     call
   */
  private static String toFunctionCall(ColorWithAlternatives color) {
    ColorSpace cs = color.getColorSpace();
    if (cs.isCS_sRGB() && !color.hasAlternativeColors()) {
      return toRGBFunctionCall(color);
    }
    if (cs instanceof CIELabColorSpace) {
      return toCIELabFunctionCall(color);
    }

    Color specColor = color;
    if (color.hasAlternativeColors()) {
      Color alt = color.getAlternativeColors()[0];
      if (ColorSpaces.isDeviceColorSpace(alt.getColorSpace())) {
        cs = alt.getColorSpace();
        specColor = alt;
      }
    }
    ColorSpaceOrigin origin = ColorSpaces.getColorSpaceOrigin(cs);
    String functionName;

    Color fallbackColor = getsRGBFallback(color);
    float[] rgb = fallbackColor.getColorComponents(null);
    assert rgb.length == 3;
    StringBuffer sb = new StringBuffer(40);
    sb.append("(");
    sb.append(rgb[0]).append(",");
    sb.append(rgb[1]).append(",");
    sb.append(rgb[2]).append(",");
    String profileName = origin.getProfileName();
    sb.append(profileName).append(",");
    if (origin.getProfileURI() != null) {
      sb.append("\"").append(origin.getProfileURI()).append("\"");
    }

    if (cs instanceof NamedColorSpace) {
      NamedColorSpace ncs = (NamedColorSpace) cs;
      if (SEPARATION_PSEUDO_PROFILE.equalsIgnoreCase(profileName)) {
        functionName = "fop-rgb-icc";
      } else {
        functionName = "fop-rgb-named-color";
      }
      sb.append(",").append(ncs.getColorName());
    } else {
      functionName = "fop-rgb-icc";
      float[] colorComponents = specColor.getColorComponents(null);
      for (float colorComponent : colorComponents) {
        sb.append(",");
        sb.append(colorComponent);
      }
    }
    sb.append(")");
    return functionName + sb.toString();
  }
  /**
   * Construct an OpImage given a String representation of a URL, a resolution, and a sub-image
   * index.
   *
   * @param URLSpec The URL of the IIP image including the FIF cimmand if needed and possibly an SDS
   *     command.
   * @param level The resolution level with 0 as the lowest resolution.
   * @param subImage The subimage number.
   * @param layout The layout hint; may be null.
   */
  public IIPResolutionOpImage(Map config, String URLSpec, int level, int subImage) {
    super(
        (Vector) null, // the image is sourceless
        layoutHelper(URLSpec, level, subImage),
        config,
        false);

    this.renderHints = (RenderingHints) config;

    // Cache the constructor parameters.
    URLString = URLSpec;
    this.subImage = subImage;

    // Retrieve required parameters from server.
    String[] cmd = new String[] {"OBJ=Resolution-number"};
    InputStream stream = postCommands(cmd);
    String label = null;
    while ((label = getLabel(stream)) != null) {
      if (label.equals("resolution-number")) {
        String data = getDataAsString(stream, false);
        int numRes = Integer.valueOf(data).intValue();
        if (level < 0) {
          resolution = 0;
        } else if (level >= numRes) {
          resolution = numRes - 1;
        } else {
          resolution = level;
        }
      } else {
        checkError(label, stream, true);
      }
    }
    endResponse(stream);

    // Cache some values which will be used repetitively.
    ColorSpace cs = colorModel.getColorSpace();
    if (cs.isCS_sRGB()) {
      colorSpaceType = CS_NIFRGB;
    } else if (cs.equals(ColorSpace.getInstance(ColorSpace.CS_GRAY))) {
      colorSpaceType = CS_MONOCHROME;
    } else {
      colorSpaceType = CS_PHOTOYCC;
    }
    hasAlpha = colorModel.hasAlpha();
    isAlphaPremultilpied = colorModel.isAlphaPremultiplied();
    minTileX = getMinTileX();
    minTileY = getMinTileY();
    numXTiles = getNumXTiles();
  }
Example #9
0
 /**
  * Set the non stroking color, specified as RGB.
  *
  * @param color The color to set.
  * @throws IOException If an IO error occurs while writing to the stream.
  */
 public void setNonStrokingColor(Color color) throws IOException {
   ColorSpace colorSpace = color.getColorSpace();
   if (colorSpace.getType() == ColorSpace.TYPE_RGB) {
     setNonStrokingColor(color.getRed(), color.getGreen(), color.getBlue());
   } else if (colorSpace.getType() == ColorSpace.TYPE_GRAY) {
     color.getColorComponents(colorComponents);
     setNonStrokingColor(colorComponents[0]);
   } else if (colorSpace.getType() == ColorSpace.TYPE_CMYK) {
     color.getColorComponents(colorComponents);
     setNonStrokingColor(
         colorComponents[0], colorComponents[2], colorComponents[2], colorComponents[3]);
   } else {
     throw new IOException("Error: unknown colorspace:" + colorSpace);
   }
 }
  public void testCreateBanded() {
    int[] bankIndices = new int[] {0, 1, 2};
    int[] bandOffsets = new int[] {1, 1, 1};
    ColorSpace colorSpace = ColorSpace.getInstance(ColorSpace.CS_sRGB);
    int dataType = DataBuffer.TYPE_BYTE;
    boolean hasAlpha = false;

    ImageTypeSpecifier typeSpecifier =
        ImageTypeSpecifier.createBanded(
            colorSpace, bankIndices, bandOffsets, dataType, hasAlpha, false);

    ColorModel colorModel = typeSpecifier.getColorModel();
    assertEquals(
        "Failed to create with the correct colorspace type",
        ColorSpace.TYPE_RGB,
        colorModel.getColorSpace().getType());
    assertEquals(
        "Failed to create with the correct transparency",
        Transparency.OPAQUE,
        colorModel.getTransparency());
    assertEquals(
        "Failed to create with the correcttransfer type",
        DataBuffer.TYPE_BYTE,
        colorModel.getTransferType());

    BandedSampleModel sampleModel = (BandedSampleModel) typeSpecifier.getSampleModel();
    assertArrayEquals(
        "Failed to create with the correct bankIndices", bankIndices, sampleModel.getBankIndices());
    assertArrayEquals(
        "Failed to create with the correct bankIndices", bandOffsets, sampleModel.getBandOffsets());
  }
  public void testCreateInterleaved() {
    ColorSpace colorSpace = ColorSpace.getInstance(ColorSpace.CS_sRGB);
    int[] bandOffsets = new int[] {1, 2, 3};
    int dataType = DataBuffer.TYPE_BYTE;

    ImageTypeSpecifier type =
        ImageTypeSpecifier.createInterleaved(colorSpace, bandOffsets, dataType, false, false);
    ColorModel colorModel = type.getColorModel();
    PixelInterleavedSampleModel sampleModel = (PixelInterleavedSampleModel) type.getSampleModel();

    // validate the colorModel
    assertEquals(
        "Failed to create with the correct colorspace type",
        ColorSpace.TYPE_RGB,
        colorModel.getColorSpace().getType());
    assertEquals(
        "Failed to create with the correct transparency",
        Transparency.OPAQUE,
        colorModel.getTransparency());
    assertEquals(
        "Failed to create with the correct transfer type",
        DataBuffer.TYPE_BYTE,
        colorModel.getTransferType());

    // validate the sampleModel
    assertTrue(
        "The sampleModel and colorModel are not compatible",
        colorModel.isCompatibleSampleModel(sampleModel));
    assertArrayEquals(
        "Failed to create with the correct bandOffsets", bandOffsets, sampleModel.getBandOffsets());
    assertEquals("Failed to create with the correct pixel stride", 3, sampleModel.getPixelStride());
  }
Example #12
0
 /**
  * Constructs IntegerRaster with the given size.
  *
  * @param _nrow the number of rows
  * @param _ncol the number of columns
  */
 public IntegerRaster(int _nrow, int _ncol) {
   nrow = _nrow;
   ncol = _ncol;
   dimension = new Dimension(ncol, nrow);
   int size = nrow * ncol;
   ComponentColorModel ccm =
       new ComponentColorModel(
           ColorSpace.getInstance(ColorSpace.CS_sRGB),
           new int[] {8, 8, 8},
           false, // hasAlpha
           false,
           Transparency.OPAQUE,
           DataBuffer.TYPE_BYTE);
   BandedSampleModel csm =
       new BandedSampleModel(
           DataBuffer.TYPE_BYTE, ncol, nrow, ncol, new int[] {0, 1, 2}, new int[] {0, 0, 0});
   rgbData = new byte[3][size];
   DataBuffer databuffer = new DataBufferByte(rgbData, size);
   WritableRaster raster = Raster.createWritableRaster(csm, databuffer, new Point(0, 0));
   image = new BufferedImage(ccm, raster, false, null);
   // col in x direction, row in y direction
   xmin = 0;
   xmax = ncol;
   ymin = nrow;
   ymax = 0; // zero is on top
 }
Example #13
0
 /**
  * Create a raster that can be used in {@link #createGlyphRaster(WritableRaster, double)}.
  *
  * @param width
  * @param height
  * @return the raster
  */
 public static final WritableRaster createRaster(int width, int height) {
   final ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_GRAY);
   final int[] nBits = {8};
   final ComponentColorModel cm =
       new ComponentColorModel(cs, nBits, false, true, Transparency.OPAQUE, DataBuffer.TYPE_BYTE);
   return cm.createCompatibleWritableRaster(width, height);
 }
Example #14
0
  /** Generate a tiled image that contains a view of the mask. */
  @SuppressWarnings("restriction")
  public TiledImage getMaskImage() {
    TiledImage ti =
        new TiledImage(
            0,
            0,
            mwidth,
            mheight,
            0,
            0,
            new PixelInterleavedSampleModel(
                DataBuffer.TYPE_BYTE, mwidth, mheight, 1, mwidth, Transform.bandstride),
            new ComponentColorModel(
                ColorSpace.getInstance(ColorSpace.CS_GRAY),
                false,
                false,
                ComponentColorModel.OPAQUE,
                DataBuffer.TYPE_BYTE));

    WritableRaster gradRaster = ti.getWritableTile(0, 0);
    DataBufferByte gradDB = (DataBufferByte) gradRaster.getDataBuffer();
    byte[] gradImageData = gradDB.getData();

    int maskwh = mwidth * mheight;
    for (int i = 0; i < maskwh; i++) gradImageData[i] = (byte) mask[i];

    return ti;
  }
Example #15
0
 private BufferedImage toImage(byte[][] bands, int xSize, int ySize) {
   int numberOfBands = bands.length;
   int numBytes = xSize * ySize * numberOfBands;
   DataBuffer imgBuffer = new DataBufferByte(bands, numBytes);
   SampleModel sampleModel = new BandedSampleModel(TYPE_BYTE, xSize, ySize, numberOfBands);
   WritableRaster raster = Raster.createWritableRaster(sampleModel, imgBuffer, null);
   if (numberOfBands == 1) {
     Band band = dataset.GetRasterBand(1);
     int bufType = band.getDataType();
     int dataType = detectDataType(band, bufType);
     BufferedImage img;
     if (BufferedImage.TYPE_BYTE_INDEXED == dataType) {
       ColorTable ct = band.GetRasterColorTable();
       IndexColorModel cm = ct.getIndexColorModel(gdal.GetDataTypeSize(bufType));
       img = new BufferedImage(xSize, ySize, dataType, cm);
     } else {
       img = new BufferedImage(xSize, ySize, dataType);
     }
     img.setData(raster);
     return img;
   }
   ColorSpace cs = ColorSpace.getInstance(CS_sRGB);
   ColorModel cm;
   if (numberOfBands == 3) {
     cm = new ComponentColorModel(cs, false, false, ColorModel.OPAQUE, TYPE_BYTE);
   } else if (numberOfBands == 4) {
     cm = new ComponentColorModel(cs, true, false, ColorModel.TRANSLUCENT, TYPE_BYTE);
   } else {
     throw new IllegalArgumentException("Unsupported number of bands: " + numberOfBands);
   }
   return new BufferedImage(cm, raster, false, null);
 }
Example #16
0
 public void extract(BufferedImage image) {
   histogram = new double[18];
   double[] directionality;
   ColorConvertOp op =
       new ColorConvertOp(
           image.getColorModel().getColorSpace(),
           ColorSpace.getInstance(ColorSpace.CS_GRAY),
           new RenderingHints(
               RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY));
   BufferedImage bimg = op.filter(image, null);
   bimg = ImageUtils.scaleImage(bimg, MAX_IMG_HEIGHT);
   Raster raster = bimg.getRaster();
   int[] tmp = new int[3];
   this.grayScales = new int[raster.getWidth()][raster.getHeight()];
   for (int i = 0; i < raster.getWidth(); i++) {
     for (int j = 0; j < raster.getHeight(); j++) {
       raster.getPixel(i, j, tmp);
       this.grayScales[i][j] = tmp[0];
     }
   }
   imgWidth = bimg.getWidth();
   imgHeight = bimg.getHeight();
   histogram[0] = this.coarseness(bimg.getWidth(), bimg.getHeight());
   histogram[1] = this.contrast();
   directionality = this.directionality();
   for (int i = 2; i < histogram.length; i++) {
     histogram[i] = directionality[i - 2];
   }
 }
Example #17
0
  /**
   * Constructs a {@code PackedColorModel} from a color mask array, which specifies which bits in an
   * {@code int} pixel representation contain each of the color samples, and an alpha mask. Color
   * components are in the specified {@code ColorSpace}. The length of {@code colorMaskArray} should
   * be the number of components in the {@code ColorSpace}. All of the bits in each mask must be
   * contiguous and fit in the specified number of least significant bits of an {@code int} pixel
   * representation. If the {@code alphaMask} is 0, there is no alpha. If there is alpha, the {@code
   * boolean isAlphaPremultiplied} specifies how to interpret color and alpha samples in pixel
   * values. If the {@code boolean} is {@code true}, color samples are assumed to have been
   * multiplied by the alpha sample. The transparency, {@code trans}, specifies what alpha values
   * can be represented by this color model. The transfer type is the type of primitive array used
   * to represent pixel values.
   *
   * @param space the specified {@code ColorSpace}
   * @param bits the number of bits in the pixel values
   * @param colorMaskArray array that specifies the masks representing the bits of the pixel values
   *     that represent the color components
   * @param alphaMask specifies the mask representing the bits of the pixel values that represent
   *     the alpha component
   * @param isAlphaPremultiplied {@code true} if color samples are premultiplied by the alpha
   *     sample; {@code false} otherwise
   * @param trans specifies the alpha value that can be represented by this color model
   * @param transferType the type of array used to represent pixel values
   * @throws IllegalArgumentException if {@code bits} is less than 1 or greater than 32
   */
  public PackedColorModel(
      ColorSpace space,
      int bits,
      int[] colorMaskArray,
      int alphaMask,
      boolean isAlphaPremultiplied,
      int trans,
      int transferType) {
    super(
        bits,
        PackedColorModel.createBitsArray(colorMaskArray, alphaMask),
        space,
        (alphaMask == 0 ? false : true),
        isAlphaPremultiplied,
        trans,
        transferType);
    if (bits < 1 || bits > 32) {
      throw new IllegalArgumentException("Number of bits must be between" + " 1 and 32.");
    }
    maskArray = new int[numComponents];
    maskOffsets = new int[numComponents];
    scaleFactors = new float[numComponents];

    for (int i = 0; i < numColorComponents; i++) {
      // Get the mask offset and #bits
      DecomposeMask(colorMaskArray[i], i, space.getName(i));
    }
    if (alphaMask != 0) {
      DecomposeMask(alphaMask, numColorComponents, "alpha");
      if (nBits[numComponents - 1] == 1) {
        transparency = Transparency.BITMASK;
      }
    }
  }
Example #18
0
 /**
  * Returns the <code>ColorSpace</code> of this <code>Color</code>.
  *
  * @return this <code>Color</code> object's <code>ColorSpace</code>.
  */
 @Override
 public ColorSpace getColorSpace() {
   if (cs == null) {
     cs = ColorSpace.getInstance(ColorSpace.CS_sRGB);
   }
   return cs;
 }
  public BufferedImage aplicaFiltro(BufferedImage bi) {
    Raster raster = bi.getData();
    int w = raster.getWidth();
    int h = raster.getHeight();
    byte[] rgb = new byte[w * h * 3];
    int[] R = raster.getSamples(0, 0, w, h, 0, (int[]) null);
    int[] G = raster.getSamples(0, 0, w, h, 1, (int[]) null);
    int[] B = raster.getSamples(0, 0, w, h, 2, (int[]) null);
    for (int i = 0, imax = R.length, base = 0; i < imax; i++, base += 3) {
      int r = R[i];
      int g = G[i];
      int b = B[i];
      int oR = r, oG = g, oB = b;

      r = (oR + oG) / 2;
      g = (oR + oG + oB) / 3;
      b = oB;

      rgb[base] = (byte) (Math.min(255f, r));
      rgb[base + 1] = (byte) (Math.min(255f, g));
      rgb[base + 2] = (byte) (Math.min(255f, b));
    }

    raster =
        Raster.createInterleavedRaster(
            new DataBufferByte(rgb, rgb.length), w, h, w * 3, 3, new int[] {0, 1, 2}, null);

    ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_sRGB);
    ColorModel cm =
        new ComponentColorModel(cs, false, true, Transparency.OPAQUE, DataBuffer.TYPE_BYTE);
    return new BufferedImage(cm, (WritableRaster) raster, true, null);
  }
  @Override
  public ImageTypeSpecifier getRawImageType(final int imageIndex) throws IOException {
    checkBounds(imageIndex);
    readHeader();

    int channels = header.getChannels();
    int paletteInfo = header.getPaletteInfo();
    ColorSpace cs =
        paletteInfo == PCX.PALETTEINFO_GRAY
            ? ColorSpace.getInstance(ColorSpace.CS_GRAY)
            : ColorSpace.getInstance(ColorSpace.CS_sRGB);

    switch (header.getBitsPerPixel()) {
      case 1:
      case 2:
      case 4:
        return ImageTypeSpecifiers.createFromIndexColorModel(header.getEGAPalette());
      case 8:
        // We may have IndexColorModel here for 1 channel images
        if (channels == 1 && paletteInfo != PCX.PALETTEINFO_GRAY) {
          IndexColorModel palette = getVGAPalette();
          if (palette == null) {
            throw new IIOException("Expected VGA palette not found");
          }

          return ImageTypeSpecifiers.createFromIndexColorModel(palette);
        }

        // PCX has 1 or 3 channels for 8 bit gray or 24 bit RGB, will be validated by
        // ImageTypeSpecifier
        return ImageTypeSpecifiers.createBanded(
            cs,
            createIndices(channels, 1),
            createIndices(channels, 0),
            DataBuffer.TYPE_BYTE,
            false,
            false);
      case 24:
        // Some sources says this is possible...
        return ImageTypeSpecifiers.createFromBufferedImageType(BufferedImage.TYPE_3BYTE_BGR);
      case 32:
        // Some sources says this is possible...
        return ImageTypeSpecifiers.createFromBufferedImageType(BufferedImage.TYPE_4BYTE_ABGR);
      default:
        throw new IIOException("Unknown number of bytes per pixel: " + header.getBitsPerPixel());
    }
  }
Example #21
0
  private ICC_Profile buildICCProfile(
      final ImageInfo info, final ColorSpace colorSpace, final ByteArrayOutputStream iccStream)
      throws IOException {
    if (iccStream != null && iccStream.size() > 0) {
      if (log.isDebugEnabled()) {
        log.debug("Effective ICC profile size: " + iccStream.size());
      }
      final int alignment = 4;
      final int padding = (alignment - iccStream.size() % alignment) % alignment;
      if (padding != 0) {
        try {
          iccStream.write(new byte[padding]);
        } catch (final IOException ioe) {
          throw new IOException("Error while aligning ICC stream: " + ioe.getMessage());
        }
      }

      ICC_Profile iccProfile = null;
      try {
        iccProfile = ColorProfileUtil.getICC_Profile(iccStream.toByteArray());
        if (log.isDebugEnabled()) {
          log.debug("JPEG has an ICC profile: " + iccProfile.toString());
        }
      } catch (final IllegalArgumentException iae) {
        log.warn(
            "An ICC profile is present in the JPEG file but it is invalid ("
                + iae.getMessage()
                + "). The color profile will be ignored. ("
                + info.getOriginalURI()
                + ")");
        return null;
      }
      if (iccProfile.getNumComponents() != colorSpace.getNumComponents()) {
        log.warn(
            "The number of components of the ICC profile ("
                + iccProfile.getNumComponents()
                + ") doesn't match the image ("
                + colorSpace.getNumComponents()
                + "). Ignoring the ICC color profile.");
        return null;
      } else {
        return iccProfile;
      }
    } else {
      return null; // no ICC profile available
    }
  }
Example #22
0
  /**
   * Returns the color space specified by the given color space constant.
   *
   * <p>For standard Java color spaces, the built-in instance is returned. Otherwise, color spaces
   * are looked up from cache and created on demand.
   *
   * @param colorSpace the color space constant.
   * @return the {@link ColorSpace} specified by the color space constant.
   * @throws IllegalArgumentException if {@code colorSpace} is not one of the defined color spaces
   *     ({@code CS_*}).
   * @see ColorSpace
   * @see ColorSpaces#CS_ADOBE_RGB_1998
   * @see ColorSpaces#CS_GENERIC_CMYK
   */
  public static ColorSpace getColorSpace(int colorSpace) {
    ICC_Profile profile;

    switch (colorSpace) {
      case CS_ADOBE_RGB_1998:
        synchronized (ColorSpaces.class) {
          profile = adobeRGB1998.get();

          if (profile == null) {
            // Try to get system default or user-defined profile
            profile = readProfileFromPath(Profiles.getPath("ADOBE_RGB_1998"));

            if (profile == null) {
              // Fall back to the bundled ClayRGB1998 public domain Adobe RGB 1998 compatible
              // profile,
              // which is identical for all practical purposes
              profile = readProfileFromClasspathResource("/profiles/ClayRGB1998.icc");

              if (profile == null) {
                // Should never happen given we now bundle fallback profile...
                throw new IllegalStateException("Could not read AdobeRGB1998 profile");
              }
            }

            adobeRGB1998 = new WeakReference<ICC_Profile>(profile);
          }
        }

        return createColorSpace(profile);

      case CS_GENERIC_CMYK:
        synchronized (ColorSpaces.class) {
          profile = genericCMYK.get();

          if (profile == null) {
            // Try to get system default or user-defined profile
            profile = readProfileFromPath(Profiles.getPath("GENERIC_CMYK"));

            if (profile == null) {
              if (DEBUG) {
                System.out.println("Using fallback profile");
              }

              // Fall back to generic CMYK ColorSpace, which is *insanely slow* using
              // ColorConvertOp... :-P
              return CMYKColorSpace.getInstance();
            }

            genericCMYK = new WeakReference<ICC_Profile>(profile);
          }
        }

        return createColorSpace(profile);

      default:
        // Default cases for convenience
        return ColorSpace.getInstance(colorSpace);
    }
  }
Example #23
0
  private static ICC_ColorSpace getInternalCS(final int profileCSType, final byte[] profileHeader) {
    if (profileCSType == ColorSpace.TYPE_RGB && Arrays.equals(profileHeader, sRGB.header)) {
      return (ICC_ColorSpace) ColorSpace.getInstance(ColorSpace.CS_sRGB);
    } else if (profileCSType == ColorSpace.TYPE_GRAY && Arrays.equals(profileHeader, GRAY.header)) {
      return (ICC_ColorSpace) ColorSpace.getInstance(ColorSpace.CS_GRAY);
    } else if (profileCSType == ColorSpace.TYPE_3CLR && Arrays.equals(profileHeader, PYCC.header)) {
      return (ICC_ColorSpace) ColorSpace.getInstance(ColorSpace.CS_PYCC);
    } else if (profileCSType == ColorSpace.TYPE_RGB
        && Arrays.equals(profileHeader, LINEAR_RGB.header)) {
      return (ICC_ColorSpace) ColorSpace.getInstance(ColorSpace.CS_LINEAR_RGB);
    } else if (profileCSType == ColorSpace.TYPE_XYZ
        && Arrays.equals(profileHeader, CIEXYZ.header)) {
      return (ICC_ColorSpace) ColorSpace.getInstance(ColorSpace.CS_CIEXYZ);
    }

    return null;
  }
 private static Color toSRGBColor(Color color) {
   float[] comps;
   ColorSpace sRGB = ColorSpace.getInstance(ColorSpace.CS_sRGB);
   comps = color.getRGBColorComponents(null);
   float[] allComps = color.getComponents(null);
   float alpha = allComps[allComps.length - 1]; // Alpha is on last component
   return new Color(sRGB, comps, alpha);
 }
Example #25
0
  /** Create a new texture loader based on the game panel */
  static {
    glAlphaColorModel =
        new ComponentColorModel(
            ColorSpace.getInstance(ColorSpace.CS_sRGB),
            new int[] {8, 8, 8, 8},
            true,
            false,
            ComponentColorModel.TRANSLUCENT,
            DataBuffer.TYPE_BYTE);

    glColorModel =
        new ComponentColorModel(
            ColorSpace.getInstance(ColorSpace.CS_sRGB),
            new int[] {8, 8, 8, 0},
            false,
            false,
            ComponentColorModel.OPAQUE,
            DataBuffer.TYPE_BYTE);
  }
  @Override
  protected BufferedImage createImage(int width, int height) {
    ColorSpace gsColorSpace = ColorSpace.getInstance(ColorSpace.CS_GRAY);
    ComponentColorModel ccm =
        new ComponentColorModel(
            gsColorSpace, true, false, Transparency.TRANSLUCENT, DataBuffer.TYPE_BYTE);
    WritableRaster raster = ccm.createCompatibleWritableRaster(width, height);

    return new BufferedImage(ccm, raster, ccm.isAlphaPremultiplied(), null);
  }
 public float[] toCIEXYZ(float[] colorvalue) {
   if (colorvalue[0] == 1) {
     return prev1;
   } else if (colorvalue[0] == 0) {
     return prev0;
   } else {
     //	    System.out.println("MaskColorSpace converting: "+colorvalue[0]);
     return cie.fromRGB(toRGB(colorvalue));
   }
 }
 private ColorModel getColorModel() {
   return new DirectColorModel(
       ColorSpace.getInstance(ColorSpace.CS_sRGB),
       32,
       0x00ff0000,
       0x0000ff00,
       0x000000ff,
       0xff000000,
       true,
       DataBuffer.TYPE_INT);
 }
Example #29
0
 private static ImageIcon makeGrayImageIcon1(Image img) {
   BufferedImage source =
       new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB);
   Graphics g = source.createGraphics();
   g.drawImage(img, 0, 0, null);
   g.dispose();
   ColorConvertOp colorConvert =
       new ColorConvertOp(ColorSpace.getInstance(ColorSpace.CS_GRAY), null);
   BufferedImage destination = colorConvert.filter(source, null);
   return new ImageIcon(destination);
 }
Example #30
0
 /**
  * 彩色转为黑白
  *
  * @param srcImageFile 源图像地址
  * @param destImageFile 目标图像地址
  */
 public static final void gray(String srcImageFile, String destImageFile) {
   try {
     BufferedImage src = ImageIO.read(new File(srcImageFile));
     ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_GRAY);
     ColorConvertOp op = new ColorConvertOp(cs, null);
     src = op.filter(src, null);
     ImageIO.write(src, "JPEG", new File(destImageFile));
   } catch (IOException e) {
     e.printStackTrace();
   }
 }