Java Code Examples for java.awt.image.WritableRaster#setPixel()

The following examples show how to use java.awt.image.WritableRaster#setPixel() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PDIndexed.java    From sambox with Apache License 2.0 6 votes vote down vote up
@Override
public BufferedImage toRGBImage(WritableRaster raster) throws IOException
{
    // use lookup table
    int width = raster.getWidth();
    int height = raster.getHeight();

    BufferedImage rgbImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    WritableRaster rgbRaster = rgbImage.getRaster();

    int[] src = new int[1];
    for (int y = 0; y < height; y++)
    {
        for (int x = 0; x < width; x++)
        {
            raster.getPixel(x, y, src);

            // lookup
            int index = Math.min(src[0], actualMaxIndex);
            rgbRaster.setPixel(x, y, rgbColorTable[index]);
        }
    }

    return rgbImage;
}
 
Example 2
Source File: PixelatedImageSectionFilter.java    From cognitivej with Apache License 2.0 6 votes vote down vote up
@NotNull
@Override
public BufferedImage applyFilter(@NotNull BufferedImage bufferedImage) {
    Raster src = bufferedImage.getData();
    WritableRaster dest = src.createCompatibleWritableRaster();
    bufferedImage.copyData(dest);
    for (int y = pixelateSection.y; y < pixelateSection.y + pixelateSection.getHeight(); y += PIX_SIZE) {
        for (int x = pixelateSection.x; x < pixelateSection.x + pixelateSection.getWidth(); x += PIX_SIZE) {
            double[] pixel = new double[3];
            pixel = src.getPixel(x, y, pixel);
            for (int yd = y; (yd < y + PIX_SIZE) && (yd < dest.getHeight()); yd++) {
                for (int xd = x; (xd < x + PIX_SIZE) && (xd < dest.getWidth()); xd++) {
                    dest.setPixel(xd, yd, pixel);
                }
            }
        }
    }
    bufferedImage.setData(dest);
    return bufferedImage;
}
 
Example 3
Source File: DCTFilter.java    From sambox with Apache License 2.0 6 votes vote down vote up
private WritableRaster fromYCbCrtoCMYK(Raster raster)
{
    WritableRaster writableRaster = raster.createCompatibleWritableRaster();

    int[] value = new int[4];
    for (int y = 0, height = raster.getHeight(); y < height; y++)
    {
        for (int x = 0, width = raster.getWidth(); x < width; x++)
        {
            raster.getPixel(x, y, value);

            // 4-channels 0..255
            float Y = value[0];
            float Cb = value[1];
            float Cr = value[2];
            float K = value[3];

            // YCbCr to RGB, see http://www.equasys.de/colorconversion.html
            int r = clamp( (1.164f * (Y-16)) + (1.596f * (Cr - 128)) );
            int g = clamp( (1.164f * (Y-16)) + (-0.392f * (Cb-128)) + (-0.813f * (Cr-128)));
            int b = clamp( (1.164f * (Y-16)) + (2.017f * (Cb-128)));

            // naive RGB to CMYK
            int cyan = 255 - r;
            int magenta = 255 - g;
            int yellow = 255 - b;

            // update new raster
            value[0] = cyan;
            value[1] = magenta;
            value[2] = yellow;
            value[3] = (int)K;
            writableRaster.setPixel(x, y, value);
        }
    }
    return writableRaster;
}
 
Example 4
Source File: MaterialDesignIconGenerateDialog.java    From android-material-design-icon-generator-plugin with Apache License 2.0 5 votes vote down vote up
private BufferedImage generateColoredIcon(BufferedImage image) {
    Color color = null;
    if (model.getColorCode() != null) {
        String colorString = model.getColorCode();
        color = decodeColor(colorString);
    }
    if (color == null) return image;

    int width = image.getWidth();
    int height = image.getHeight();
    boolean hasAlpha = image.getColorModel().hasAlpha();

    BufferedImage newImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    WritableRaster raster = newImage.getRaster();
    for (int xx = 0; xx < width; xx++) {
        for (int yy = 0; yy < height; yy++) {
            int originalPixel = image.getRGB(xx, yy);
            int originalAlpha;
            if (hasAlpha) {
                originalAlpha = new Color(originalPixel, true).getAlpha();
            } else {
                // Due to ImageIO's issue, `hasAlpha` is assigned `false` although PNG file has alpha channel.
                // Regarding PNG files of Material Icon, in this case, the file is 1bit depth binary(BLACK or WHITE).
                // Therefore BLACK is `alpha = 0` and WHITE is `alpha = 255`
                originalAlpha = originalPixel == 0xFF000000 ? 0 : 255;
            }

            int[] pixels = new int[4];
            pixels[0] = color.getRed();
            pixels[1] = color.getGreen();
            pixels[2] = color.getBlue();
            pixels[3] = combineAlpha(originalAlpha, color.getAlpha());
            raster.setPixel(xx, yy, pixels);
        }
    }
    return newImage;
}
 
Example 5
Source File: RequiredTimeTable.java    From unitime with Apache License 2.0 5 votes vote down vote up
/** put pixel */
private void putPixel(WritableRaster raster, int x, int y, Color color) {
    //Debug.log("setPixel("+x+","+y+","+color+")");
    raster.setPixel(
        x, y,
        new int[] { color.getRed(), color.getGreen(), color.getBlue() });
}
 
Example 6
Source File: ColorYCbCrComposite.java    From TrakEM2 with GNU General Public License v3.0 5 votes vote down vote up
public CompositeContext createContext( ColorModel srcColorModel, ColorModel dstColorModel, RenderingHints hints )
{
	final Composer c;
	if ( srcColorModel.getNumColorComponents() > 1 )
	{
		if ( srcColorModel.hasAlpha() )
			c = new ARGB2ARGB();
		else
			c = new RGB2ARGB();
	}
	else
		c = new Gray2ARGB();
	
	return new CompositeContext()
	{
		private Composer composer = c;
		public void compose( Raster src, Raster dstIn, WritableRaster dstOut )
		{
			final int[] srcPixel = new int[ 4 ];
			final int[] dstInPixel = new int[ 4 ];
			
			for ( int x = 0; x < dstOut.getWidth(); x++ )
			{
				for ( int y = 0; y < dstOut.getHeight(); y++ )
				{
					src.getPixel( x, y, srcPixel );
					dstIn.getPixel( x, y, dstInPixel );
					
					composer.compose( srcPixel, dstInPixel, alpha );
					
					dstOut.setPixel( x, y, dstInPixel );
				}
			}
		}

		public void dispose()
		{}
	};
}
 
Example 7
Source File: PixelTests.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
public void runTest(Object context, int numReps) {
    WritableRaster ras = ((Context) context).ras;
    int pixeldata[] = ((Context) context).pixeldata;
    do {
        ras.setPixel(numReps&7, 0, pixeldata);
    } while (--numReps > 0);
}
 
Example 8
Source File: PDCIEBasedColorSpace.java    From sambox with Apache License 2.0 5 votes vote down vote up
@Override
public BufferedImage toRGBImage(WritableRaster raster) throws IOException
{
    // This method calls toRGB to convert images one pixel at a time. For matrix-based
    // CIE color spaces this is fast enough. However, it should not be used with any
    // color space which uses an ICC Profile as it will be far too slow.

    int width = raster.getWidth();
    int height = raster.getHeight();

    BufferedImage rgbImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    WritableRaster rgbRaster = rgbImage.getRaster();

    // always three components: ABC
    float[] abc = new float[3];
    for (int y = 0; y < height; y++)
    {
        for (int x = 0; x < width; x++)
        {
            raster.getPixel(x, y, abc);

            // 0..255 -> 0..1
            abc[0] /= 255;
            abc[1] /= 255;
            abc[2] /= 255;

            float[] rgb = toRGB(abc);

            // 0..1 -> 0..255
            rgb[0] *= 255;
            rgb[1] *= 255;
            rgb[2] *= 255;

            rgbRaster.setPixel(x, y, rgb);
        }
    }

    return rgbImage;
}
 
Example 9
Source File: PDCIEBasedColorSpace.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
@Override
public BufferedImage toRGBImage(WritableRaster raster) throws IOException
{
    // This method calls toRGB to convert images one pixel at a time. For matrix-based
    // CIE color spaces this is fast enough. However, it should not be used with any
    // color space which uses an ICC Profile as it will be far too slow.

    int width = raster.getWidth();
    int height = raster.getHeight();

    BufferedImage rgbImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    WritableRaster rgbRaster = rgbImage.getRaster();

    // always three components: ABC
    float[] abc = new float[3];
    for (int y = 0; y < height; y++)
    {
        for (int x = 0; x < width; x++)
        {
            raster.getPixel(x, y, abc);

            // 0..255 -> 0..1
            abc[0] /= 255;
            abc[1] /= 255;
            abc[2] /= 255;

            float[] rgb = toRGB(abc);

            // 0..1 -> 0..255
            rgb[0] *= 255;
            rgb[1] *= 255;
            rgb[2] *= 255;

            rgbRaster.setPixel(x, y, rgb);
        }
    }

    return rgbImage;
}
 
Example 10
Source File: DataRaster.java    From osp with GNU General Public License v3.0 5 votes vote down vote up
void append(double x, double y) {
  if(Double.isNaN(x)||Double.isInfinite(x)||Double.isNaN(y)||Double.isInfinite(y)) {
    return; // do not append bad data
  }
  if(nextPoint>=data[0].length) {
    increaseCapacity(data[0].length*2);
  }
  data[0][nextPoint] = (float) x; // save value for later use
  data[1][nextPoint] = (float) y;
  nextPoint++;
  WritableRaster raster = image.getRaster();
  if(raster.getWidth()<2) {
    return; // image is too small
  }
  double xmin = Math.max(primaryDrawingPanel.getXMin(), DataRaster.this.xmin);
  double ymax = Math.min(primaryDrawingPanel.getYMax(), DataRaster.this.ymax);
  int i = (int) (primaryDrawingPanel.getXPixPerUnit()*(x-xmin)+0.5);
  int j = (int) (primaryDrawingPanel.getYPixPerUnit()*(ymax-y)+0.5);
  if((i<0)||(j<0)||(i>=raster.getWidth())||(j>=raster.getHeight())) {
    return; // outside the image
  }
  try {
    raster.setPixel(i, j, color);                                    // set the image pixel
  } catch(Exception ex) {
    System.out.println("Error setting raster in ImageData append."); //$NON-NLS-1$
  }
}
 
Example 11
Source File: PDSeparation.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
private BufferedImage toRGBImage2(WritableRaster raster) throws IOException
{
    int width = raster.getWidth();
    int height = raster.getHeight();
    BufferedImage rgbImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    WritableRaster rgbRaster = rgbImage.getRaster();
    float[] samples = new float[1];

    Map<Integer, int[]> calculatedValues = new HashMap<Integer, int[]>();
    Integer hash;
    for (int y = 0; y < height; y++)
    {
        for (int x = 0; x < width; x++)
        {
            raster.getPixel(x, y, samples);
            int[] rgb = calculatedValues.get(hash = Float.floatToIntBits(samples[0]));
            if (rgb == null)
            {
                samples[0] /= 255;
                float[] altColor = tintTransform.eval(samples);
                float[] fltab = alternateColorSpace.toRGB(altColor);
                rgb = new int[3];
                rgb[0] = (int) (fltab[0] * 255);
                rgb[1] = (int) (fltab[1] * 255);
                rgb[2] = (int) (fltab[2] * 255);
                calculatedValues.put(hash, rgb);
            }
            rgbRaster.setPixel(x, y, rgb);
        }
    }
    return rgbImage;
}
 
Example 12
Source File: DCTFilter.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
private WritableRaster fromYCCKtoCMYK(Raster raster)
{
    WritableRaster writableRaster = raster.createCompatibleWritableRaster();

    int[] value = new int[4];
    for (int y = 0, height = raster.getHeight(); y < height; y++)
    {
        for (int x = 0, width = raster.getWidth(); x < width; x++)
        {
            raster.getPixel(x, y, value);

            // 4-channels 0..255
            float Y = value[0];
            float Cb = value[1];
            float Cr = value[2];
            float K = value[3];

            // YCCK to RGB, see http://software.intel.com/en-us/node/442744
            int r = clamp(Y + 1.402f * Cr - 179.456f);
            int g = clamp(Y - 0.34414f * Cb - 0.71414f * Cr + 135.45984f);
            int b = clamp(Y + 1.772f * Cb - 226.816f);

            // naive RGB to CMYK
            int cyan = 255 - r;
            int magenta = 255 - g;
            int yellow = 255 - b;

            // update new raster
            value[0] = cyan;
            value[1] = magenta;
            value[2] = yellow;
            value[3] = (int)K;
            writableRaster.setPixel(x, y, value);
        }
    }
    return writableRaster;
}
 
Example 13
Source File: PixelTests.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
public void runTest(Object context, int numReps) {
    WritableRaster ras = ((Context) context).ras;
    int pixeldata[] = ((Context) context).pixeldata;
    do {
        ras.setPixel(numReps&7, 0, pixeldata);
    } while (--numReps > 0);
}
 
Example 14
Source File: SubtractARGBComposite.java    From TrakEM2 with GNU General Public License v3.0 5 votes vote down vote up
public CompositeContext createContext( ColorModel srcColorModel, ColorModel dstColorModel, RenderingHints hints )
{
	final Composer c;
	if ( srcColorModel.getNumColorComponents() > 1 )
	{
		if ( srcColorModel.hasAlpha() )
			c = new ARGB2ARGB();
		else
			c = new RGB2ARGB();
	}
	else
		c = new Gray2ARGB();
	
	return new CompositeContext()
	{
		private Composer composer = c;
		public void compose( Raster src, Raster dstIn, WritableRaster dstOut )
		{
			final int[] srcPixel = new int[ 4 ];
			final int[] dstInPixel = new int[ 4 ];
			
			for ( int x = 0; x < dstOut.getWidth(); x++ )
			{
				for ( int y = 0; y < dstOut.getHeight(); y++ )
				{
					src.getPixel( x, y, srcPixel );
					dstIn.getPixel( x, y, dstInPixel );
					
					composer.compose( srcPixel, dstInPixel, alpha );
					
					dstOut.setPixel( x, y, dstInPixel );
				}
			}
		}

		public void dispose()
		{}
	};
}
 
Example 15
Source File: BadgeUtils.java    From MantaroBot with GNU General Public License v3.0 4 votes vote down vote up
public static byte[] applyBadge(byte[] avatarBytes, byte[] badgeBytes, int startX, int startY, boolean allWhite) {
    BufferedImage avatar;
    BufferedImage badge;
    try {
        avatar = ImageIO.read(new ByteArrayInputStream(avatarBytes));
        badge = ImageIO.read(new ByteArrayInputStream(badgeBytes));
    } catch (IOException impossible) {
        throw new AssertionError(impossible);
    }
    WritableRaster raster = badge.getRaster();

    if (allWhite) {
        for (int xx = 0, width = badge.getWidth(); xx < width; xx++) {
            for (int yy = 0, height = badge.getHeight(); yy < height; yy++) {
                int[] pixels = raster.getPixel(xx, yy, (int[]) null);
                pixels[0] = 255;
                pixels[1] = 255;
                pixels[2] = 255;
                pixels[3] = pixels[3] == 255 ? 165 : 0;
                raster.setPixel(xx, yy, pixels);
            }
        }
    }

    BufferedImage res = new BufferedImage(128, 128, BufferedImage.TYPE_INT_ARGB);

    int circleCenterX = 88, circleCenterY = 88;
    int width = 32, height = 32;
    int circleRadius = 40;

    Graphics2D g2d = res.createGraphics();
    g2d.drawImage(avatar, 0, 0, 128, 128, null);
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g2d.setColor(new Color(0, 0, 165, 165));
    g2d.fillOval(circleCenterX, circleCenterY, circleRadius, circleRadius);


    g2d.drawImage(badge, startX, startY, width, height, null);
    g2d.dispose();

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
        ImageIO.write(res, "png", baos);
    } catch (IOException e) {
        throw new AssertionError(e);
    }
    return baos.toByteArray();
}
 
Example 16
Source File: PDLab.java    From sambox with Apache License 2.0 4 votes vote down vote up
@Override
public BufferedImage toRGBImage(WritableRaster raster) throws IOException
{
    int width = raster.getWidth();
    int height = raster.getHeight();

    BufferedImage rgbImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    WritableRaster rgbRaster = rgbImage.getRaster();

    float minA = getARange().getMin();
    float maxA = getARange().getMax();
    float minB = getBRange().getMin();
    float maxB = getBRange().getMax();

    // always three components: ABC
    float[] abc = new float[3];
    for (int y = 0; y < height; y++)
    {
        for (int x = 0; x < width; x++)
        {
            raster.getPixel(x, y, abc);

            // 0..255 -> 0..1
            abc[0] /= 255;
            abc[1] /= 255;
            abc[2] /= 255;
            
            // scale to range
            abc[0] *= 100;
            abc[1] = minA + (abc[1] * (maxA - minA));
            abc[2] = minB + (abc[2] * (maxB - minB));

            float[] rgb = toRGB(abc);

            // 0..1 -> 0..255
            rgb[0] *= 255;
            rgb[1] *= 255;
            rgb[2] *= 255;

            rgbRaster.setPixel(x, y, rgb);
        }
    }

    return rgbImage;
}
 
Example 17
Source File: PDDeviceN.java    From gcs with Mozilla Public License 2.0 4 votes vote down vote up
private BufferedImage toRGBWithAttributes(WritableRaster raster) throws IOException
{
    int width = raster.getWidth();
    int height = raster.getHeight();

    BufferedImage rgbImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    WritableRaster rgbRaster = rgbImage.getRaster();

    // white background
    Graphics2D g = rgbImage.createGraphics();
    g.setBackground(Color.WHITE);
    g.clearRect(0, 0, width, height);
    g.dispose();

    // look up each colorant
    for (int c = 0; c < numColorants; c++)
    {
        PDColorSpace componentColorSpace;
        if (colorantToComponent[c] >= 0)
        {
            // process color
            componentColorSpace = processColorSpace;
        }
        else if (spotColorSpaces[c] == null)
        {
            // TODO this happens in the Altona Visual test, is there a better workaround?
            // missing spot color, fallback to using tintTransform
            return toRGBWithTintTransform(raster);
        }
        else
        {
            // spot color
            componentColorSpace = spotColorSpaces[c];
        }

        // copy single-component to its own raster in the component color space
        WritableRaster componentRaster = Raster.createBandedRaster(DataBuffer.TYPE_BYTE,
            width, height, componentColorSpace.getNumberOfComponents(), new Point(0, 0));

        int[] samples = new int[numColorants];
        int[] componentSamples = new int[componentColorSpace.getNumberOfComponents()];
        boolean isProcessColorant = colorantToComponent[c] >= 0;
        int componentIndex = colorantToComponent[c];
        for (int y = 0; y < height; y++)
        {
            for (int x = 0; x < width; x++)
            {
                raster.getPixel(x, y, samples);
                if (isProcessColorant)
                {
                    // process color
                    componentSamples[componentIndex] = samples[c];
                }
                else
                {
                    // spot color
                    componentSamples[0] = samples[c];
                }
                componentRaster.setPixel(x, y, componentSamples);
            }
        }

        // convert single-component raster to RGB
        BufferedImage rgbComponentImage = componentColorSpace.toRGBImage(componentRaster);
        WritableRaster rgbComponentRaster = rgbComponentImage.getRaster();

        // combine the RGB component with the RGB composite raster
        int[] rgbChannel = new int[3];
        int[] rgbComposite = new int[3];
        for (int y = 0; y < height; y++)
        {
            for (int x = 0; x < width; x++)
            {
                rgbComponentRaster.getPixel(x, y, rgbChannel);
                rgbRaster.getPixel(x, y, rgbComposite);

                // multiply (blend mode)
                rgbChannel[0] = rgbChannel[0] * rgbComposite[0] >> 8;
                rgbChannel[1] = rgbChannel[1] * rgbComposite[1] >> 8;
                rgbChannel[2] = rgbChannel[2] * rgbComposite[2] >> 8;

                rgbRaster.setPixel(x, y, rgbChannel);
            }
        }
    }

    return rgbImage;
}
 
Example 18
Source File: SoftMask.java    From sambox with Apache License 2.0 4 votes vote down vote up
@Override
public Raster getRaster(int x1, int y1, int w, int h)
{
    Raster raster = context.getRaster(x1, y1, w, h);
    ColorModel rasterCM = context.getColorModel();
    float[] input = null;
    Float[] map = null;

    if (transferFunction != null)
    {
        map = new Float[256];
        input = new float[1];
    }

    // buffer
    WritableRaster output = getColorModel().createCompatibleWritableRaster(w, h);

    // the soft mask has its own bbox
    x1 = x1 - (int) bboxDevice.getX();
    y1 = y1 - (int) bboxDevice.getY();

    int[] gray = new int[4];
    Object pixelInput = null;
    int[] pixelOutput = new int[4];
    for (int y = 0; y < h; y++)
    {
        for (int x = 0; x < w; x++)
        {
            pixelInput = raster.getDataElements(x, y, pixelInput);

            pixelOutput[0] = rasterCM.getRed(pixelInput);
            pixelOutput[1] = rasterCM.getGreen(pixelInput);
            pixelOutput[2] = rasterCM.getBlue(pixelInput);
            pixelOutput[3] = rasterCM.getAlpha(pixelInput);

            // get the alpha value from the gray mask, if within mask bounds
            gray[0] = 0;
            if (x1 + x >= 0 && y1 + y >= 0 && x1 + x < mask.getWidth()
                    && y1 + y < mask.getHeight())
            {
                mask.getRaster().getPixel(x1 + x, y1 + y, gray);
                int g = gray[0];
                if (transferFunction != null)
                {
                    // apply transfer function
                    try
                    {
                        if (map[g] != null)
                        {
                            // was calculated before
                            pixelOutput[3] = Math.round(pixelOutput[3] * map[g]);
                        }
                        else
                        {
                            // calculate and store in map
                            input[0] = g / 255f;
                            float f = transferFunction.eval(input)[0];
                            map[g] = f;
                            pixelOutput[3] = Math.round(pixelOutput[3] * f);
                        }
                    }
                    catch (IOException ex)
                    {
                        // ignore exception, treat as outside
                        pixelOutput[3] = Math.round(pixelOutput[3] * (bc / 255f));
                    }
                }
                else
                {
                    pixelOutput[3] = Math.round(pixelOutput[3] * (g / 255f));
                }
            }
            else
            {
                pixelOutput[3] = Math.round(pixelOutput[3] * (bc / 255f));
            }
            output.setPixel(x, y, pixelOutput);
        }
    }

    return output;
}
 
Example 19
Source File: PDDeviceN.java    From sambox with Apache License 2.0 4 votes vote down vote up
private BufferedImage toRGBWithAttributes(WritableRaster raster) throws IOException
{
    int width = raster.getWidth();
    int height = raster.getHeight();

    BufferedImage rgbImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    WritableRaster rgbRaster = rgbImage.getRaster();

    // white background
    Graphics2D g = rgbImage.createGraphics();
    g.setBackground(Color.WHITE);
    g.clearRect(0, 0, width, height);
    g.dispose();

    // look up each colorant
    for (int c = 0; c < numColorants; c++)
    {
        PDColorSpace componentColorSpace;
        if (colorantToComponent[c] >= 0)
        {
            // process color
            componentColorSpace = processColorSpace;
        }
        else if (spotColorSpaces[c] == null)
        {
            // TODO this happens in the Altona Visual test, is there a better workaround?
            // missing spot color, fallback to using tintTransform
            return toRGBWithTintTransform(raster);
        }
        else
        {
            // spot color
            componentColorSpace = spotColorSpaces[c];
        }

        // copy single-component to its own raster in the component color space
        WritableRaster componentRaster = Raster.createBandedRaster(DataBuffer.TYPE_BYTE, width,
                height, componentColorSpace.getNumberOfComponents(), new Point(0, 0));

        int[] samples = new int[numColorants];
        int[] componentSamples = new int[componentColorSpace.getNumberOfComponents()];
        boolean isProcessColorant = colorantToComponent[c] >= 0;
        int componentIndex = colorantToComponent[c];
        for (int y = 0; y < height; y++)
        {
            for (int x = 0; x < width; x++)
            {
                raster.getPixel(x, y, samples);
                if (isProcessColorant)
                {
                    // process color
                    componentSamples[componentIndex] = samples[c];
                }
                else
                {
                    // spot color
                    componentSamples[0] = samples[c];
                }
                componentRaster.setPixel(x, y, componentSamples);
            }
        }

        // convert single-component raster to RGB
        BufferedImage rgbComponentImage = componentColorSpace.toRGBImage(componentRaster);
        WritableRaster rgbComponentRaster = rgbComponentImage.getRaster();

        // combine the RGB component with the RGB composite raster
        int[] rgbChannel = new int[3];
        int[] rgbComposite = new int[3];
        for (int y = 0; y < height; y++)
        {
            for (int x = 0; x < width; x++)
            {
                rgbComponentRaster.getPixel(x, y, rgbChannel);
                rgbRaster.getPixel(x, y, rgbComposite);

                // multiply (blend mode)
                rgbChannel[0] = rgbChannel[0] * rgbComposite[0] >> 8;
                rgbChannel[1] = rgbChannel[1] * rgbComposite[1] >> 8;
                rgbChannel[2] = rgbChannel[2] * rgbComposite[2] >> 8;

                rgbRaster.setPixel(x, y, rgbChannel);
            }
        }
    }

    return rgbImage;
}
 
Example 20
Source File: PDImageXObject.java    From sambox with Apache License 2.0 4 votes vote down vote up
private BufferedImage applyMask(BufferedImage image, BufferedImage mask, boolean isSoft,
        float[] matte)
{
    if (mask == null)
    {
        return image;
    }

    int width = image.getWidth();
    int height = image.getHeight();

    // scale mask to fit image, or image to fit mask, whichever is larger
    if (mask.getWidth() < width || mask.getHeight() < height)
    {
        mask = scaleImage(mask, width, height);
    }
    else if (mask.getWidth() > width || mask.getHeight() > height)
    {
        width = mask.getWidth();
        height = mask.getHeight();
        image = scaleImage(image, width, height);
    }
    else if (image.getRaster().getPixel(0, 0, (int[]) null).length < 3)
    {
        // PDFBOX-4470 bitonal image has only one element => copy into RGB
        image = scaleImage(image, width, height);
    }

    // compose to ARGB
    BufferedImage masked = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    WritableRaster src = image.getRaster();
    WritableRaster dest = masked.getRaster();
    WritableRaster alpha = mask.getRaster();

    float[] rgb = new float[4];
    float[] rgba = new float[4];
    float[] alphaPixel = null;
    for (int y = 0; y < height; y++)
    {
        for (int x = 0; x < width; x++)
        {
            src.getPixel(x, y, rgb);

            rgba[0] = rgb[0];
            rgba[1] = rgb[1];
            rgba[2] = rgb[2];

            alphaPixel = alpha.getPixel(x, y, alphaPixel);
            if (isSoft)
            {
                rgba[3] = alphaPixel[0];
                if (matte != null && Float.compare(alphaPixel[0], 0) != 0)
                {
                    rgba[0] = clampColor(
                            ((rgba[0] / 255 - matte[0]) / (alphaPixel[0] / 255) + matte[0])
                                    * 255);
                    rgba[1] = clampColor(
                            ((rgba[1] / 255 - matte[1]) / (alphaPixel[0] / 255) + matte[1])
                                    * 255);
                    rgba[2] = clampColor(
                            ((rgba[2] / 255 - matte[2]) / (alphaPixel[0] / 255) + matte[2])
                                    * 255);
                }
            }
            else
            {
                rgba[3] = 255 - alphaPixel[0];
            }

            dest.setPixel(x, y, rgba);
        }
    }

    return masked;
}