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

The following examples show how to use java.awt.image.BufferedImage#getType() . These examples are extracted from open source projects. 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
/**
 * <p>Returns an array of pixels, stored as integers, from a
 * <code>BufferedImage</code>. The pixels are grabbed from a rectangular
 * area defined by a location and two dimensions. Calling this method on
 * an image of type different from <code>BufferedImage.TYPE_INT_ARGB</code>
 * and <code>BufferedImage.TYPE_INT_RGB</code> will unmanage the image.</p>
 *
 * @param img the source image
 * @param x the x location at which to start grabbing pixels
 * @param y the y location at which to start grabbing pixels
 * @param w the width of the rectangle of pixels to grab
 * @param h the height of the rectangle of pixels to grab
 * @param pixels a pre-allocated array of pixels of size w*h; can be null
 * @return <code>pixels</code> if non-null, a new array of integers
 *   otherwise
 * @throws IllegalArgumentException is <code>pixels</code> is non-null and
 *   of length &lt; w*h
 */
public static int[] getPixels(BufferedImage img,
                              int x, int y, int w, int h, int[] pixels) {
    if (w == 0 || h == 0) {
        return new int[0];
    }

    if (pixels == null) {
        pixels = new int[w * h];
    } else if (pixels.length < w * h) {
        throw new IllegalArgumentException("pixels array must have a length" +
                                           " >= w*h");
    }

    int imageType = img.getType();
    if (imageType == BufferedImage.TYPE_INT_ARGB ||
        imageType == BufferedImage.TYPE_INT_RGB) {
        Raster raster = img.getRaster();
        return (int[]) raster.getDataElements(x, y, w, h, pixels);
    }

    // Unmanages the image
    return img.getRGB(x, y, w, h, pixels, 0, w);
}
 
Example 2
/**
 * <p>Returns an array of pixels, stored as integers, from a <code>BufferedImage</code>. The pixels are grabbed from
 * a rectangular area defined by a location and two dimensions. Calling this method on an image of type different
 * from <code>BufferedImage.TYPE_INT_ARGB</code> and <code>BufferedImage.TYPE_INT_RGB</code> will unmanage the
 * image.</p>
 *
 * @param img    the source image
 * @param x      the x location at which to start grabbing pixels
 * @param y      the y location at which to start grabbing pixels
 * @param w      the width of the rectangle of pixels to grab
 * @param h      the height of the rectangle of pixels to grab
 * @param pixels a pre-allocated array of pixels of size w*h; can be null
 * @return <code>pixels</code> if non-null, a new array of integers otherwise
 * @throws IllegalArgumentException is <code>pixels</code> is non-null and of length &lt; w*h
 */
static byte[] getPixels(BufferedImage img,
                               int x, int y, int w, int h, byte[] pixels) {
    if (w == 0 || h == 0) {
        return new byte[0];
    }

    if (pixels == null) {
        pixels = new byte[w * h];
    } else if (pixels.length < w * h) {
        throw new IllegalArgumentException("pixels array must have a length >= w*h");
    }

    int imageType = img.getType();
    if (imageType == BufferedImage.TYPE_BYTE_GRAY) {
        Raster raster = img.getRaster();
        return (byte[]) raster.getDataElements(x, y, w, h, pixels);
    } else {
        throw new IllegalArgumentException("Only type BYTE_GRAY is supported");
    }
}
 
Example 3
public void doTest(int type) {
    System.out.println("Test for type " + describeType(type));

    BufferedImage src = createTestImage(type);

    BufferedImage res = null;

    System.out.println("Testing null destination...");
    try {
        res = op.filter(src, null);
    } catch (ImagingOpException e) {
        throw new RuntimeException("Test FAILED!", e);
    }

    if (res == null ||
        ((src.getType() != BufferedImage.TYPE_BYTE_INDEXED) &&
         (res.getType() != src.getType())))
    {
        throw new RuntimeException("Test FAILED!");
    }
    System.out.println("Test PASSED.");
}
 
Example 4
Source Project: JDKSourceCode1.8   File: EffectUtils.java    License: MIT License 6 votes vote down vote up
/**
 * <p>Returns an array of pixels, stored as integers, from a <code>BufferedImage</code>. The pixels are grabbed from
 * a rectangular area defined by a location and two dimensions. Calling this method on an image of type different
 * from <code>BufferedImage.TYPE_INT_ARGB</code> and <code>BufferedImage.TYPE_INT_RGB</code> will unmanage the
 * image.</p>
 *
 * @param img    the source image
 * @param x      the x location at which to start grabbing pixels
 * @param y      the y location at which to start grabbing pixels
 * @param w      the width of the rectangle of pixels to grab
 * @param h      the height of the rectangle of pixels to grab
 * @param pixels a pre-allocated array of pixels of size w*h; can be null
 * @return <code>pixels</code> if non-null, a new array of integers otherwise
 * @throws IllegalArgumentException is <code>pixels</code> is non-null and of length &lt; w*h
 */
static byte[] getPixels(BufferedImage img,
                               int x, int y, int w, int h, byte[] pixels) {
    if (w == 0 || h == 0) {
        return new byte[0];
    }

    if (pixels == null) {
        pixels = new byte[w * h];
    } else if (pixels.length < w * h) {
        throw new IllegalArgumentException("pixels array must have a length >= w*h");
    }

    int imageType = img.getType();
    if (imageType == BufferedImage.TYPE_BYTE_GRAY) {
        Raster raster = img.getRaster();
        return (byte[]) raster.getDataElements(x, y, w, h, pixels);
    } else {
        throw new IllegalArgumentException("Only type BYTE_GRAY is supported");
    }
}
 
Example 5
Source Project: scrimage   File: ImageUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static int nrChannels(BufferedImage img) {
   switch (img.getType()) {
      case BufferedImage.TYPE_3BYTE_BGR:
      case BufferedImage.TYPE_INT_BGR:
      case BufferedImage.TYPE_INT_RGB:
      case BufferedImage.TYPE_USHORT_555_RGB:
      case BufferedImage.TYPE_USHORT_565_RGB:
         return 3;
      case BufferedImage.TYPE_4BYTE_ABGR:
      case BufferedImage.TYPE_INT_ARGB:
      case BufferedImage.TYPE_CUSTOM:
      case BufferedImage.TYPE_4BYTE_ABGR_PRE:
      case BufferedImage.TYPE_INT_ARGB_PRE:
         return 4;
      case BufferedImage.TYPE_BYTE_GRAY:
      case BufferedImage.TYPE_USHORT_GRAY:
         return 1;
   }
   return 0;
}
 
Example 6
public void doTest(int type) {
    System.out.println("Test for type " + describeType(type));

    BufferedImage src = createTestImage(type);

    BufferedImage res = null;

    System.out.println("Testing null destination...");
    try {
        res = op.filter(src, null);
    } catch (ImagingOpException e) {
        throw new RuntimeException("Test FAILED!", e);
    }

    if (res == null ||
        ((src.getType() != BufferedImage.TYPE_BYTE_INDEXED) &&
         (res.getType() != src.getType())))
    {
        throw new RuntimeException("Test FAILED!");
    }
    System.out.println("Test PASSED.");
}
 
Example 7
Source Project: JglTF   File: ImageUtils.java    License: MIT License 6 votes vote down vote up
/**
 * Returns a direct byte buffer that contains the ARGB pixel values of
 * the given image. <br>
 * <br>
 * The given image might become unmanaged/untrackable by this operation.
 * 
 * @param inputImage The input image
 * @param flipVertically Whether the contents of the image should be
 * flipped vertically. This is always a hassle.
 * @return The byte buffer containing the ARGB pixel values
 */
static ByteBuffer getImagePixelsARGB(
    BufferedImage inputImage, boolean flipVertically)
{
    BufferedImage image = inputImage;
    if (flipVertically)
    {
        image = flipVertically(image);
    }
    if (image.getType() != BufferedImage.TYPE_INT_ARGB)
    {
        image = convertToARGB(image);
    }
    IntBuffer imageBuffer = getBuffer(image);
    
    // Note: The byte order is BIG_ENDIAN by default. This order
    // is kept here, to keep the ARGB order, and not convert them
    // to BGRA implicitly.
    ByteBuffer outputByteBuffer = ByteBuffer
        .allocateDirect(imageBuffer.remaining() * Integer.BYTES)
        .order(ByteOrder.BIG_ENDIAN);
    IntBuffer output = outputByteBuffer.asIntBuffer();
    output.put(imageBuffer.slice());
    return outputByteBuffer;
}
 
Example 8
Source Project: dl4j-tutorials   File: ImageUtils.java    License: MIT License 5 votes vote down vote up
public static void setRGB( BufferedImage image, int x, int y, int width, int height, int[] pixels ) {
    int type = image.getType();
    if ( type == BufferedImage.TYPE_INT_ARGB || type == BufferedImage.TYPE_INT_RGB )
        image.getRaster().setDataElements( x, y, width, height, pixels );
    else
        image.setRGB( x, y, width, height, pixels, 0, width );
}
 
Example 9
private static BufferedImage resizeImage(BufferedImage originalImage, int width, int height) {
    BufferedImage resizedImage = new BufferedImage(width, height,
            originalImage.getType());
    Graphics2D g = resizedImage.createGraphics();

    g.drawImage(originalImage, 0, 0, width, height, null);
    g.dispose();

    return resizedImage;
}
 
Example 10
public static BufferedImage testImageTransform(BufferedImage image,
                                               AffineTransform transform) {
    AffineTransformOp op =
            new AffineTransformOp(transform, AffineTransformOp.TYPE_BILINEAR);

    BufferedImage transformedImage = new BufferedImage(image.getWidth(),
                                                       image.getHeight(),
                                                       image.getType());

    return op.filter(image, transformedImage);
}
 
Example 11
private BufferedImage makeOpaque(BufferedImage image) {
	if (image.getType() == BufferedImage.TYPE_CUSTOM) {
		log.warn("makeOpaque {} Unknown Image Type 0: ", getTitle());
		return image;
	}
	BufferedImage opaqueCopy = new BufferedImage(image.getWidth(), image.getHeight(), image.getType());
	Graphics2D g1 = opaqueCopy.createGraphics();
	g1.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, getOpacity()));
	g1.drawImage(image, null, 0, 0);
	g1.dispose();
	return opaqueCopy;
}
 
Example 12
Source Project: sambox   File: CCITTFactory.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new CCITT group 4 (T6) compressed image XObject from a b/w BufferedImage. This compression technique
 * usually results in smaller images than those produced by
 * {@link LosslessFactory#createFromImage(PDDocument, BufferedImage) }.
 *
 * @param image the image.
 * @return a new image XObject.
 * @throws IOException if there is an error creating the image.
 * @throws IllegalArgumentException if the BufferedImage is not a b/w image.
 */
public static PDImageXObject createFromImage(BufferedImage image) throws IOException
{
    if (image.getType() != BufferedImage.TYPE_BYTE_BINARY
            && image.getColorModel().getPixelSize() != 1)
    {
        throw new IllegalArgumentException("Only 1-bit b/w images supported");
    }

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

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    try (MemoryCacheImageOutputStream mcios = new MemoryCacheImageOutputStream(bos))
    {

        for (int y = 0; y < height; ++y)
        {
            for (int x = 0; x < width; ++x)
            {
                // flip bit to avoid having to set /BlackIs1
                mcios.writeBits(~(image.getRGB(x, y) & 1), 1);
            }
            if (mcios.getBitOffset() != 0)
            {
                mcios.writeBits(0, 8 - mcios.getBitOffset());
            }
        }
        mcios.flush();
    }

    return prepareImageXObject(bos.toByteArray(), width, height, PDDeviceGray.INSTANCE);
}
 
Example 13
Source Project: pumpernickel   File: BmpEncoder.java    License: MIT License 5 votes vote down vote up
public static boolean isOpaque(BufferedImage bi) {
	try {
		Method m = BufferedImage.class.getMethod("getTransparency",
				new Class[] {});
		Object returnValue = m.invoke(bi, new Object[] {});
		Field f = BufferedImage.class.getField("OPAQUE");
		return f.get(null).equals(returnValue);
	} catch (Throwable e) {
		// in earlier JVMs this will be a problem:
		int type = bi.getType();
		return (type == BufferedImage.TYPE_4BYTE_ABGR
				|| type == BufferedImage.TYPE_4BYTE_ABGR_PRE
				|| type == BufferedImage.TYPE_INT_ARGB || type == BufferedImage.TYPE_INT_ARGB_PRE);
	}
}
 
Example 14
/**
 * Subtracts img2 from img1
 */
BufferedImage subImages(BufferedImage img1, BufferedImage img2) {
    if (img1.getHeight() != img2.getHeight() ||
            img1.getWidth() != img2.getWidth()) {
        throw new RuntimeException("Different sizes");
    }
    BufferedImage ret = new BufferedImage(img1.getWidth(), img1.getHeight(), img1.getType());

    for (int x = 0; x < ret.getWidth(); x++) {
        for (int y = 0; y < ret.getHeight(); y++) {
            ret.setRGB(x, y, subPixels(img1.getRGB(x, y), img2.getRGB(x, y)));
        }
    }
    return ret;
}
 
Example 15
private BufferedImage writeImage(BufferedImage src) {
    try {
        BufferedImage dst = null;
        if (!writer.getOriginatingProvider().canEncodeImage(src)) {
            throw new RuntimeException(writingFormat+" writer does not support the image type "+type);
        }
        System.out.println(writingFormat+" writer claims it can encode the image "+type);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageOutputStream ios = ImageIO.createImageOutputStream(baos);
        writer.setOutput(ios);
        IIOImage img = new IIOImage(src.getRaster(), null, null);
        writer.write(img);
        ios.close();
        baos.close();

        // save to file
        File f = new File("test"+src.getType()+".bmp");
        FileOutputStream fos = new FileOutputStream(f);
        fos.write(baos.toByteArray());
        fos.close();


        ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
        dst = ImageIO.read(bais);
        return dst;
    } catch (IOException e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    }
}
 
Example 16
private BufferedImage copyImage(BufferedImage source) {
	BufferedImage b = new BufferedImage(source.getWidth(), source.getHeight(), source.getType());
	Graphics g = b.getGraphics();
	g.drawImage(source, 0, 0, null);
	g.dispose();
	return b;
}
 
Example 17
public static boolean isTransparent(BufferedImage bufferedImage) {
	int type = bufferedImage.getType();
	return Arrays.binarySearch(IMAGE_TRANSPARENT_TYPES, type) > -1;
}
 
Example 18
/**
 * Return true if the BufferedImage argument has non-opaque
 * bits in it and therefore can not be directly rendered by
 * GDI. Return false if the image is opaque. If this function
 * can not tell for sure whether the image has transparent
 * pixels then it assumes that it does.
 */
protected boolean hasTransparentPixels(BufferedImage bufferedImage) {
    ColorModel colorModel = bufferedImage.getColorModel();
    boolean hasTransparency = colorModel == null
        ? true
        : colorModel.getTransparency() != ColorModel.OPAQUE;

    /*
     * For the default INT ARGB check the image to see if any pixels are
     * really transparent. If there are no transparent pixels then the
     * transparency of the color model can be ignored.
     * We assume that IndexColorModel images have already been
     * checked for transparency and will be OPAQUE unless they actually
     * have transparent pixels present.
     */
    if (hasTransparency && bufferedImage != null) {
        if (bufferedImage.getType()==BufferedImage.TYPE_INT_ARGB ||
            bufferedImage.getType()==BufferedImage.TYPE_INT_ARGB_PRE) {
            DataBuffer db =  bufferedImage.getRaster().getDataBuffer();
            SampleModel sm = bufferedImage.getRaster().getSampleModel();
            if (db instanceof DataBufferInt &&
                sm instanceof SinglePixelPackedSampleModel) {
                SinglePixelPackedSampleModel psm =
                    (SinglePixelPackedSampleModel)sm;
                // Stealing the data array for reading only...
                int[] int_data =
                    SunWritableRaster.stealData((DataBufferInt) db, 0);
                int x = bufferedImage.getMinX();
                int y = bufferedImage.getMinY();
                int w = bufferedImage.getWidth();
                int h = bufferedImage.getHeight();
                int stride = psm.getScanlineStride();
                boolean hastranspixel = false;
                for (int j = y; j < y+h; j++) {
                    int yoff = j * stride;
                    for (int i = x; i < x+w; i++) {
                        if ((int_data[yoff+i] & 0xff000000)!=0xff000000 ) {
                            hastranspixel = true;
                            break;
                        }
                    }
                    if (hastranspixel) {
                        break;
                    }
                }
                if (hastranspixel == false) {
                    hasTransparency = false;
                }
            }
        }
    }

    return hasTransparency;
}
 
Example 19
/**
 * A convenience method for setting ARGB pixels in an image. This tries to avoid the performance
 * penalty of BufferedImage.setRGB unmanaging the image.
    * @param image   a BufferedImage object
    * @param x       the left edge of the pixel block
    * @param y       the right edge of the pixel block
    * @param width   the width of the pixel arry
    * @param height  the height of the pixel arry
    * @param pixels  the array of pixels to set
    * @see #getRGB
 */
public static void setRGB( BufferedImage image, int x, int y, int width, int height, int[] pixels ) {
	int type = image.getType();
	if ( type == BufferedImage.TYPE_INT_ARGB || type == BufferedImage.TYPE_INT_RGB )
		image.getRaster().setDataElements( x, y, width, height, pixels );
	else
		image.setRGB( x, y, width, height, pixels, 0, width );
   }
 
Example 20
/**
 * Returns an int containing one of the enumerated constant values
 * describing image formats from <code>BufferedImage</code>.
 *
 * @return an <code>int</code> representing a
 * <code>BufferedImage</code> type.
 *
 * @see java.awt.image.BufferedImage
 * @see java.awt.image.BufferedImage#TYPE_CUSTOM
 * @see java.awt.image.BufferedImage#TYPE_INT_RGB
 * @see java.awt.image.BufferedImage#TYPE_INT_ARGB
 * @see java.awt.image.BufferedImage#TYPE_INT_ARGB_PRE
 * @see java.awt.image.BufferedImage#TYPE_INT_BGR
 * @see java.awt.image.BufferedImage#TYPE_3BYTE_BGR
 * @see java.awt.image.BufferedImage#TYPE_4BYTE_ABGR
 * @see java.awt.image.BufferedImage#TYPE_4BYTE_ABGR_PRE
 * @see java.awt.image.BufferedImage#TYPE_USHORT_565_RGB
 * @see java.awt.image.BufferedImage#TYPE_USHORT_555_RGB
 * @see java.awt.image.BufferedImage#TYPE_BYTE_GRAY
 * @see java.awt.image.BufferedImage#TYPE_USHORT_GRAY
 * @see java.awt.image.BufferedImage#TYPE_BYTE_BINARY
 * @see java.awt.image.BufferedImage#TYPE_BYTE_INDEXED
 */
public int getBufferedImageType() {
    BufferedImage bi = createBufferedImage(1, 1);
    return bi.getType();
}