Java Code Examples for java.awt.image.BufferedImage#getAlphaRaster()

The following examples show how to use java.awt.image.BufferedImage#getAlphaRaster() . 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: ColorUtil.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Create a backing bitmap, painting the texture into it with the specified
 * parameters.  The bitmap will be created at 2*height, so that even if
 * there is some minor variation in height, it will not force recreating the
 * bitmap
 */
private static BufferedImage createBitmap(int height, int type,
                                          int yDecline) {

    //Create an optimal image for blitting to the screen with no format conversion
    BufferedImage result = GraphicsEnvironment.getLocalGraphicsEnvironment()
            .getDefaultScreenDevice().getDefaultConfiguration().createCompatibleImage(
                    200, height * 2);

    Graphics g = result.getGraphics();

    if (result.getAlphaRaster() == null) {
        Color c = type == FOCUS_TYPE ?
                MetalViewTabDisplayerUI.getActBgColor() :
                MetalViewTabDisplayerUI.getInactBgColor();
        g.setColor(c);
        g.fillRect(0, 0, DEFAULT_IMAGE_WIDTH, height * 2);
    }

    //draw the texture into the offscreen image
    _drawTexture(g, 0, 0, DEFAULT_IMAGE_WIDTH, height * 2, type, yDecline);
    return result;
}
 
Example 2
Source File: JPEGFactory.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
private static BufferedImage getAlphaImage(BufferedImage image) throws IOException
{
    if (!image.getColorModel().hasAlpha())
    {
        return null;
    }
    if (image.getTransparency() == Transparency.BITMASK)
    {
        throw new UnsupportedOperationException("BITMASK Transparency JPEG compression is not" +
                " useful, use LosslessImageFactory instead");
    }
    WritableRaster alphaRaster = image.getAlphaRaster();
    if (alphaRaster == null)
    {
        // happens sometimes (PDFBOX-2654) despite colormodel claiming to have alpha
        return null;
    }
    BufferedImage alphaImage = new BufferedImage(image.getWidth(), image.getHeight(),
            BufferedImage.TYPE_BYTE_GRAY);
    alphaImage.setData(alphaRaster);
    return alphaImage;
}
 
Example 3
Source File: FastRGB.java    From mars-sim with GNU General Public License v3.0 6 votes vote down vote up
public static int getRGB(BufferedImage image, int x, int y)
{
  
	byte[] pixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
	int width = image.getWidth();
	int height = image.getHeight();
	boolean hasAlphaChannel = image.getAlphaRaster() != null;
    int pixelLength = 3;
    if (hasAlphaChannel)
    {
        pixelLength = 4;
    }
    
    int pos = (y * pixelLength * width) + (x * pixelLength);

    int argb = -16777216; // 255 alpha
    if (hasAlphaChannel)
    {
        argb = (((int) pixels[pos++] & 0xff) << 24); // alpha
    }

    argb += ((int) pixels[pos++] & 0xff); // blue
    argb += (((int) pixels[pos++] & 0xff) << 8); // green
    argb += (((int) pixels[pos++] & 0xff) << 16); // red
    return argb;
}
 
Example 4
Source File: FeatureTiles.java    From geopackage-java with MIT License 6 votes vote down vote up
/**
 * Determine if the image is transparent
 *
 * @param image
 *            image
 * @return true if transparent
 */
protected boolean isTransparent(BufferedImage image) {
	boolean transparent = false;
	if (image != null) {
		WritableRaster raster = image.getAlphaRaster();
		if (raster != null) {
			transparent = true;
			done: for (int x = 0; x < image.getWidth(); x++) {
				for (int y = 0; y < image.getHeight(); y++) {
					if (raster.getSample(x, y, 0) > 0) {
						transparent = false;
						break done;
					}
				}
			}
		}
	}
	return transparent;
}
 
Example 5
Source File: JPEGFactory.java    From sambox with Apache License 2.0 6 votes vote down vote up
private static BufferedImage getAlphaImage(BufferedImage image)
{
    if (!image.getColorModel().hasAlpha())
    {
        return null;
    }
    if (image.getTransparency() == Transparency.BITMASK)
    {
        throw new UnsupportedOperationException("BITMASK Transparency JPEG compression is not"
                + " useful, use LosslessImageFactory instead");
    }
    WritableRaster alphaRaster = image.getAlphaRaster();
    if (alphaRaster == null)
    {
        // happens sometimes (PDFBOX-2654) despite colormodel claiming to have alpha
        return null;
    }
    BufferedImage alphaImage = new BufferedImage(image.getWidth(), image.getHeight(),
            BufferedImage.TYPE_BYTE_GRAY);
    alphaImage.setData(alphaRaster);
    return alphaImage;
}
 
Example 6
Source File: ScreenCapture.java    From logbook-kai with MIT License 6 votes vote down vote up
/**
 * BufferedImageを指定された形式にエンコードします
 *
 * @param image BufferedImage
 * @param format 画像形式
 * @return 指定された形式の画像
 * @throws IOException 入出力例外
 */
static byte[] encodeOther(BufferedImage image, String format) throws IOException {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    if ("png".equals(format)) {
        int width = image.getWidth(), height = image.getHeight();
        BufferedImage newImg = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR);
        Graphics2D gd = newImg.createGraphics();
        gd.drawImage(image, 0, 0, null);
        gd.dispose();
        WritableRaster r = newImg.getAlphaRaster();
        int[] alpha = new int[] { 0xfe };
        r.setPixel(0, 0, alpha);
        image = newImg;
    }
    try (ImageOutputStream ios = ImageIO.createImageOutputStream(out)) {
        ImageWriter writer = ImageIO.getImageWritersByFormatName(format).next();
        try {
            writer.setOutput(ios);
            writer.write(null, new IIOImage(image, null, null), null);
        } finally {
            writer.dispose();
        }
    }
    return out.toByteArray();
}
 
Example 7
Source File: ICOEncoder.java    From jclic with GNU General Public License v2.0 6 votes vote down vote up
private static void writeXorBitmap(BufferedImage img, InfoHeader ih, LittleEndianOutputStream out) throws IOException {
  Raster raster = img.getRaster();
  switch (ih.sBitCount) {
    case 1:
      BMPEncoder.write1(raster, out);
      break;
    case 4:
      BMPEncoder.write4(raster, out);
      break;
    case 8:
      BMPEncoder.write8(raster, out);
      break;
    case 24:
      BMPEncoder.write24(raster, out);
      break;
    case 32:
      Raster alpha = img.getAlphaRaster();
      BMPEncoder.write32(raster, alpha, out);
      break;
  }
}
 
Example 8
Source File: SVGFigure.java    From bonita-studio with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Converts an AWT based buffered image into an SWT <code>Image</code>. This will always return an <code>Image</code> that
 * has 24 bit depth regardless of the type of AWT buffered image that is passed into the method.
 * 
 * @param awtImage the {@link java.awt.image.BufferedImage} to be converted to an <code>Image</code>
 * @return an <code>Image</code> that represents the same image data as the AWT <code>BufferedImage</code> type.
 */
protected static org.eclipse.swt.graphics.Image toSWT(final Device device, final BufferedImage awtImage) {
    // We can force bitdepth to be 24 bit because BufferedImage getRGB
    // allows us to always retrieve 24 bit data regardless of source color depth.
    final PaletteData palette = new PaletteData(0xFF0000, 0xFF00, 0xFF);
    final ImageData swtImageData = new ImageData(awtImage.getWidth(), awtImage.getHeight(), 24, palette);
    // Ensure scansize is aligned on 32 bit.
    final int scansize = (awtImage.getWidth() * 3 + 3) * 4 / 4;
    final WritableRaster alphaRaster = awtImage.getAlphaRaster();
    final byte[] alphaBytes = new byte[awtImage.getWidth()];
    for (int y = 0; y < awtImage.getHeight(); y++) {
        final int[] buff = awtImage.getRGB(0, y, awtImage.getWidth(), 1, null, 0, scansize);
        swtImageData.setPixels(0, y, awtImage.getWidth(), buff, 0);
        if (alphaRaster != null) {
            final int[] alpha = alphaRaster.getPixels(0, y, awtImage.getWidth(), 1, (int[]) null);
            for (int i = 0; i < awtImage.getWidth(); i++) {
                alphaBytes[i] = (byte) alpha[i];
            }
            swtImageData.setAlphas(0, y, awtImage.getWidth(), alphaBytes, 0);
        }
    }
    return new org.eclipse.swt.graphics.Image(device, swtImageData);
}
 
Example 9
Source File: ImageUtil.java    From gp2srv with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static double calculateAverageBrightness(BufferedImage image) {
	double result = 0;

	int imageType = image.getType();
	if (imageType != BufferedImage.TYPE_INT_ARGB && imageType != BufferedImage.TYPE_INT_RGB && imageType != BufferedImage.TYPE_3BYTE_BGR
			&& imageType != BufferedImage.TYPE_4BYTE_ABGR && imageType != BufferedImage.TYPE_4BYTE_ABGR_PRE && imageType != BufferedImage.TYPE_INT_ARGB_PRE
			&& imageType != BufferedImage.TYPE_INT_BGR) {
		throw new RuntimeException("Unsupported image type: " + image.getType());
	}
	boolean hasAlpha = image.getAlphaRaster() != null;
	int pixelSize = hasAlpha ? 4 : 3;
	byte[] pixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();

	int cpuCores = Runtime.getRuntime().availableProcessors();
	final ForkJoinPool pool = new ForkJoinPool(cpuCores);

	BrightnessCalcTask[] tasks = new BrightnessCalcTask[cpuCores];
	int subArraySize = (int) Math.ceil(((double) pixels.length) / cpuCores);
	if (subArraySize % pixelSize != 0) {
		subArraySize += pixelSize - subArraySize % pixelSize;
	}
	for (int i = 0; i < cpuCores; i++) {
		tasks[i] = new BrightnessCalcTask(pixels, subArraySize * i, Math.min(subArraySize * (i + 1), pixels.length), pixelSize);
		pool.submit(tasks[i]);
	}
	pool.shutdown();
	while (!pool.isTerminated()) {
		try {
			pool.awaitTermination(5, TimeUnit.SECONDS);
		} catch (InterruptedException e) {
		}
	}

	for (BrightnessCalcTask task : tasks) {
		result += task.getRawResult();
	}
	result = result / tasks.length;
	return result;
}
 
Example 10
Source File: BMPDecoder.java    From jclic with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Reads 32-bit uncompressed bitmap raster data, with transparency.
 * @param lis the source input
 * @param infoHeader the <tt>InfoHeader</tt> structure, which was read using
 * {@link #readInfoHeader(net.sf.image4j.io.LittleEndianInputStream) readInfoHeader()}
 * @throws java.io.IOException if an error occurs
 * @return the decoded image read from the source input
 */
public static BufferedImage read32(InfoHeader infoHeader,
    net.sf.image4j.io.LittleEndianInputStream lis) throws IOException {
  //4 bytes per pixel
  // blue 1
  // green 1
  // red 1
  // alpha 1
  //No padding since each pixel = 32 bits
  
  BufferedImage img = new BufferedImage(
      infoHeader.iWidth, infoHeader.iHeight,
      BufferedImage.TYPE_INT_ARGB
      );
  
  WritableRaster rgb = img.getRaster();
  WritableRaster alpha = img.getAlphaRaster();
  
  for (int y = infoHeader.iHeight - 1; y >= 0; y--) {
    for (int x = 0; x < infoHeader.iWidth; x++) {
      int b = lis.readUnsignedByte();
      int g = lis.readUnsignedByte();
      int r = lis.readUnsignedByte();
      int a = lis.readUnsignedByte();
      rgb.setSample(x, y, 0, r);
      rgb.setSample(x, y, 1, g);
      rgb.setSample(x, y, 2, b);
      alpha.setSample(x, y, 0, a);
    }
  }
  
  return img;
}
 
Example 11
Source File: GraphBuffer.java    From diirt with MIT License 5 votes vote down vote up
/**
 * Creates a GraphBuffer with the given image on which to draw a graph.
 *
 * @param image an image on which we can draw a graph
 */
private GraphBuffer(BufferedImage image){
    this.image = image;
    width = image.getWidth();
    height = image.getHeight();
    pixels = ((DataBufferByte)this.image.getRaster().getDataBuffer()).getData();
    hasAlphaChannel = image.getAlphaRaster() != null;
    g = image.createGraphics();
}
 
Example 12
Source File: IntensityGraph2DRenderer.java    From diirt with MIT License 5 votes vote down vote up
private void drawRectanglesArray(Graphics2D g, Cell2DDataset data, double xStartGraph, double yEndGraph,
        double xWidthTotal, double yHeightTotal, double cellHeight, double cellWidth, BufferedImage image){

    byte pixels[] = ((DataBufferByte)image.getRaster().getDataBuffer()).getData();
    boolean hasAlphaChannel = image.getAlphaRaster() != null;
    int countY = 0;
    int countX;
    double yPosition = yEndGraph-yHeightTotal;
    int yPositionInt = (int)(yEndGraph-yHeightTotal);
    while (countY < data.getYCount()){
            countX = 0;
            double xPosition = xStartGraph;
            int xPositionInt = (int)xStartGraph;
            while (countX < data.getXCount()){
                int rgb = colorMapInstance.colorFor(data.getValue((int)countX, data.getYCount()-1-(int)countY));
                for(int w = 0; w < (int)cellWidth + 1; w++){
                    for(int h = 0; h < (int)cellHeight + 1; h++){
                        if(hasAlphaChannel){
                        pixels[(yPositionInt+h)*getImageWidth()*4 + 4*xPositionInt + 0] = (byte)(rgb >> 24 & 0xFF);
                        pixels[(yPositionInt+h)*getImageWidth()*4 + 4*xPositionInt + 1] = (byte)(rgb & 0xFF);
                        pixels[(yPositionInt+h)*getImageWidth()*4 + 4*xPositionInt + 2] = (byte)(rgb >> 8 & 0xFF);
                        pixels[(yPositionInt+h)*getImageWidth()*4 + 4*xPositionInt + 3] = (byte)(rgb >> 16 & 0xFF);
                        }
                        else{
                        pixels[(yPositionInt+h)*getImageWidth()*3 + 3*(xPositionInt+w) + 0] = (byte)(rgb & 0xFF);
                        pixels[(yPositionInt+h)*getImageWidth()*3 + 3*(xPositionInt+w) + 1] = (byte)((rgb >> 8 & 0xFF) );
                        pixels[(yPositionInt+h)*getImageWidth()*3 + 3*(xPositionInt+w) + 2] = (byte)((rgb >> 16 & 0xFF));
                        }
                    }
                }
                xPosition = xPosition + cellWidth;
                xPositionInt = (int)xPosition;
                countX++;
            }
            yPosition = yPosition + cellHeight;
            yPositionInt = (int)yPosition;
            countY++;
        }
}
 
Example 13
Source File: OracleText.java    From magarena with GNU General Public License v3.0 4 votes vote down vote up
private static BufferedImage trimTransparency(BufferedImage image) {
    WritableRaster raster = image.getAlphaRaster();
    int width = raster.getWidth();
    int height = raster.getHeight();
    int left = 0;
    int top = 0;
    int right = width - 1;
    int bottom = height - 1;
    int minRight = width - 1;
    int minBottom = height - 1;

    top:
    for (;top < bottom; top++){
        for (int x = 0; x < width; x++){
            if (raster.getSample(x, top, 0) != 0){
                minRight = x;
                minBottom = top;
                break top;
            }
        }
    }

    left:
    for (;left < minRight; left++){
        for (int y = height - 1; y > top; y--){
            if (raster.getSample(left, y, 0) != 0){
                minBottom = y;
                break left;
            }
        }
    }

    bottom:
    for (;bottom > minBottom; bottom--){
        for (int x = width - 1; x >= left; x--){
            if (raster.getSample(x, bottom, 0) != 0){
                minRight = x;
                break bottom;
            }
        }
    }

    right:
    for (;right > minRight; right--){
        for (int y = bottom; y >= top; y--){
            if (raster.getSample(right, y, 0) != 0){
                break right;
            }
        }
    }

    return image.getSubimage(left, top, right - left + 1, bottom - top + 1);
}
 
Example 14
Source File: ImageTrimUtil.java    From Pixelitor with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Returns image bounding box trimmed from transparent pixels (alpha channel = 0)
 */
public static Rectangle getTrimRect(BufferedImage image) {
    WritableRaster raster = image.getAlphaRaster();
    int width = raster.getWidth();
    int height = raster.getHeight();
    int left = 0;
    int top = 0;
    int right = width - 1;
    int bottom = height - 1;
    int minRight = width - 1;
    int minBottom = height - 1;

    top:
    for (; top < bottom; top++) {
        for (int x = 0; x < width; x++) {
            if (raster.getSample(x, top, 0) != 0) {
                minRight = x;
                minBottom = top;
                break top;
            }
        }
    }

    left:
    for (; left < minRight; left++) {
        for (int y = height - 1; y > top; y--) {
            if (raster.getSample(left, y, 0) != 0) {
                minBottom = y;
                break left;
            }
        }
    }

    bottom:
    for (; bottom > minBottom; bottom--) {
        for (int x = width - 1; x >= left; x--) {
            if (raster.getSample(x, bottom, 0) != 0) {
                minRight = x;
                break bottom;
            }
        }
    }

    right:
    for (; right > minRight; right--) {
        for (int y = bottom; y >= top; y--) {
            if (raster.getSample(right, y, 0) != 0) {
                break right;
            }
        }
    }

    return new Rectangle(left, top, right - left + 1, bottom - top + 1);
}