Example usage for java.awt.image BufferedImage getColorModel

List of usage examples for java.awt.image BufferedImage getColorModel

Introduction

In this page you can find the example usage for java.awt.image BufferedImage getColorModel.

Prototype

public ColorModel getColorModel() 

Source Link

Document

Returns the ColorModel .

Usage

From source file:Main.java

public static BufferedImage create(BufferedImage image, double angle, GraphicsConfiguration gc) {
    double sin = Math.abs(Math.sin(angle)), cos = Math.abs(Math.cos(angle));
    int w = image.getWidth(), h = image.getHeight();
    int neww = (int) Math.floor(w * cos + h * sin), newh = (int) Math.floor(h * cos + w * sin);
    int transparency = image.getColorModel().getTransparency();
    BufferedImage result = gc.createCompatibleImage(neww, newh, transparency);
    Graphics2D g = result.createGraphics();
    g.translate((neww - w) / 2, (newh - h) / 2);
    g.rotate(angle, w / 2, h / 2);/*w ww  .  j a  va  2 s. c  o m*/
    g.drawRenderedImage(image, null);
    return result;
}

From source file:de.fhg.igd.swingrcp.SwingRCPUtilities.java

/**
 * Convert a {@link BufferedImage} to a SWT Image.
 * /*  w  w w .j  a v  a  2  s. c o m*/
 * {@link "http://dev.eclipse.org/viewcvs/index.cgi/org.eclipse.swt.snippets/src/org/eclipse/swt/snippets/Snippet156.java?view=co"}
 * 
 * @param bufferedImage the AWT {@link BufferedImage}
 * @return the SWT {@link ImageData}
 */
public static ImageData convertToSWT(BufferedImage bufferedImage) {
    if (bufferedImage.getColorModel() instanceof DirectColorModel) {
        DirectColorModel colorModel = (DirectColorModel) bufferedImage.getColorModel();
        PaletteData palette = new PaletteData(colorModel.getRedMask(), colorModel.getGreenMask(),
                colorModel.getBlueMask());
        ImageData data = new ImageData(bufferedImage.getWidth(), bufferedImage.getHeight(),
                colorModel.getPixelSize(), palette);
        for (int y = 0; y < data.height; y++) {
            for (int x = 0; x < data.width; x++) {
                int rgb = bufferedImage.getRGB(x, y);
                int pixel = palette.getPixel(new RGB((rgb >> 16) & 0xFF, (rgb >> 8) & 0xFF, rgb & 0xFF));
                data.setPixel(x, y, pixel);
                // also set the alpha value (ST)
                data.setAlpha(x, y, colorModel.getAlpha(rgb));
            }
        }
        return data;
    } else if (bufferedImage.getColorModel() instanceof IndexColorModel) {
        IndexColorModel colorModel = (IndexColorModel) bufferedImage.getColorModel();
        int size = colorModel.getMapSize();
        byte[] reds = new byte[size];
        byte[] greens = new byte[size];
        byte[] blues = new byte[size];
        colorModel.getReds(reds);
        colorModel.getGreens(greens);
        colorModel.getBlues(blues);
        RGB[] rgbs = new RGB[size];
        for (int i = 0; i < rgbs.length; i++) {
            rgbs[i] = new RGB(reds[i] & 0xFF, greens[i] & 0xFF, blues[i] & 0xFF);
        }
        PaletteData palette = new PaletteData(rgbs);
        ImageData data = new ImageData(bufferedImage.getWidth(), bufferedImage.getHeight(),
                colorModel.getPixelSize(), palette);
        data.transparentPixel = colorModel.getTransparentPixel();
        WritableRaster raster = bufferedImage.getRaster();
        int[] pixelArray = new int[1];
        for (int y = 0; y < data.height; y++) {
            for (int x = 0; x < data.width; x++) {
                raster.getPixel(x, y, pixelArray);
                data.setPixel(x, y, pixelArray[0]);
            }
        }
        return data;
    }
    return null;
}

From source file:org.uva.itast.blended.omr.scanners.MarkScanner.java

/**
 * Aplica un filtro para reconstruir imagenes de mala calidad, a travs del
 * valor de los pxeles vecinos/*from ww w  . j  a v  a 2 s.c  o m*/
 * 
 * @param subimage
 */
public static BufferedImage medianFilter(BufferedImage subimage) {

    com.jhlabs.image.MedianFilter filter = new com.jhlabs.image.MedianFilter();
    BufferedImage result = filter.createCompatibleDestImage(subimage, subimage.getColorModel());
    filter.filter(subimage, result);

    return result;

}

From source file:com.ackpdfbox.app.imageio.TIFFUtil.java

/**
 * Sets the ImageIO parameter compression type based on the given image.
 * @param image buffered image used to decide compression type
 * @param param ImageIO write parameter to update
 *//* w ww.  j a v  a  2 s.  com*/
public static void setCompressionType(ImageWriteParam param, BufferedImage image) {
    // avoid error: first compression type is RLE, not optimal and incorrect for color images
    // TODO expose this choice to the user?
    if (image.getType() == BufferedImage.TYPE_BYTE_BINARY && image.getColorModel().getPixelSize() == 1) {
        param.setCompressionType("CCITT T.6");
    } else {
        param.setCompressionType("LZW");
    }
}

From source file:ro.nextreports.designer.util.ImageUtil.java

private static boolean hasAlpha(Image image) {
    // If buffered image, the color model is readily available
    if (image instanceof BufferedImage) {
        BufferedImage bimage = (BufferedImage) image;
        return bimage.getColorModel().hasAlpha();
    }//  w w w  .  ja  v a 2s.  c  o m

    // Use a pixel grabber to retrieve the image's color model;
    // grabbing a single pixel is usually sufficient
    PixelGrabber pg = new PixelGrabber(image, 0, 0, 1, 1, false);
    try {
        pg.grabPixels();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    // Get the image's color model
    ColorModel cm = pg.getColorModel();
    return cm.hasAlpha();
}

From source file:lucee.runtime.img.ImageUtil.java

public static BufferedImage createBufferedImage(BufferedImage image, int columns, int rows) {
    ColorModel colormodel = image.getColorModel();
    BufferedImage newImage;//from  w  w  w .j  av a 2 s  .co m
    if (colormodel instanceof IndexColorModel) {
        if (colormodel.getTransparency() != 1)
            newImage = new BufferedImage(columns, rows, 2);
        else
            newImage = new BufferedImage(columns, rows, 1);
    } else {
        newImage = new BufferedImage(colormodel,
                image.getRaster().createCompatibleWritableRaster(columns, rows),
                colormodel.isAlphaPremultiplied(), null);
    }
    return newImage;
}

From source file:software.uncharted.image.ImageProcessing.java

/**
 * histogramByteHash -- compute a color histogram of an image
 *                      returned as a byte[]
 * @param img/*from  w w w. ja  v a 2 s  .  c o m*/
 * @return byte[] histogram
 */
public static byte[] histogramByteHash(BufferedImage img) {

    Raster raster = img.getData();
    int h = raster.getHeight();
    int w = raster.getWidth();
    int components = img.getColorModel().getNumComponents();
    int pixels = w * h;
    int[] colors = new int[pixels * components];
    raster.getPixels(0, 0, w, h, colors);
    int[] counts = new int[DISTINCT_COLORS];
    int grayScaleCount = 0;
    for (int i = 0; i < DISTINCT_COLORS; i++)
        counts[i] = 0;

    int cIndx = 0; // 'colours' array index
    for (int i = 0; i < pixels; i++) {
        int r = colors[cIndx] / COLOR_DIVISOR; // quantizes down to 'COLOR_DEPTH' range
        int g = (colors[cIndx + 1]) / COLOR_DIVISOR;
        int b = (colors[cIndx + 2]) / COLOR_DIVISOR;
        int truncColor = (r * COLOR_DEPTH + g) * COLOR_DEPTH + b; // converts 3D histogram values to 1D concatenated histogram
        counts[truncColor]++;
        if (r == g && r == b)
            grayScaleCount++;
        cIndx += components;
    }
    byte[] result = new byte[DISTINCT_COLORS];

    if (grayScaleCount > pixels * 0.95) {
        //---- grayscale image detected!
        // set black and white hist bins == max value
        // and set all other bins == hist values along one of the colour axes
        // (since r-axis vals = g-axis = b-axis for grayscale)
        counts[0] = pixels;
        counts[DISTINCT_COLORS - 1] = pixels;
        for (int i = 1; i < DISTINCT_COLORS - 1; i++) {
            counts[i] = 0;
        }
        for (int i = 0; i < pixels; i++) {
            int idx = colors[i * components] * (DISTINCT_COLORS - 2) / 256 + 1;
            counts[idx]++;
        }
    }

    //---- normalize final histogram
    for (int i = 0; i < DISTINCT_COLORS; i++) {
        //int count = (int)Math.ceil((counts[i]*RATIO_MULTIPLIER)/pixels);
        int count = (int) Math.round((counts[i] * RATIO_MULTIPLIER) / ((double) pixels * HIST_NORM_FACTOR));
        result[i] = (byte) (Math.min(count, RATIO_MULTIPLIER) & 0xFF); // Min here to handle potential saturation of hist values
    }

    return result;
}

From source file:org.polymap.rhei.batik.engine.svg.Svg2Png.java

public static BufferedImage transform(BufferedImage img, ImageConfiguration imageConfiguration) {
    ColorSpace imgCS = img.getColorModel().getColorSpace();
    ColorSpace grayCS = ColorSpace.getInstance(ColorSpace.CS_GRAY);
    ColorConvertOp cop = new ColorConvertOp(imgCS, grayCS, null);
    BufferedImage finalThresholdImage = cop.filter(img, null);
    finalThresholdImage = shiftHue(finalThresholdImage, imageConfiguration);
    return finalThresholdImage;
}

From source file:ConvertUtil.java

/**
 * Converts the source image to 4-bit colour using the given colour map. No
 * transparency./*from  ww  w  .  j a va2s .c o  m*/
 * 
 * @param src
 *            the source image to convert
 * @param cmap
 *            the colour map, which should contain no more than 16 entries
 *            The entries are in the form RRGGBB (hex).
 * @return a copy of the source image with a 4-bit colour depth, with the
 *         custom colour pallette
 */
public static BufferedImage convert4(BufferedImage src, int[] cmap) {
    IndexColorModel icm = new IndexColorModel(4, cmap.length, cmap, 0, false, Transparency.OPAQUE,
            DataBuffer.TYPE_BYTE);
    BufferedImage dest = new BufferedImage(src.getWidth(), src.getHeight(), BufferedImage.TYPE_BYTE_BINARY,
            icm);
    ColorConvertOp cco = new ColorConvertOp(src.getColorModel().getColorSpace(),
            dest.getColorModel().getColorSpace(), null);
    cco.filter(src, dest);

    return dest;
}

From source file:nl.b3p.kaartenbalie.service.KBImageTool.java

/** Reads an image from an http input stream.
 *
 * @param is Inputstream//from www.  j a v  a 2s . c om
 * @param mime String representing the mime type of the image.
 *
 * @return BufferedImage
 *
 * @throws Exception
 */
// <editor-fold defaultstate="" desc="readImage(GetMethod method, String mime) method.">
public static BufferedImage readImage(InputStream is, String mime, ServiceProviderRequest wmsRequest)
        throws Exception {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    int bytesRead = 0;
    byte[] buffer = new byte[2048];
    while (bytesRead != -1) {
        bytesRead = is.read(buffer, 0, buffer.length);
        if (bytesRead > 0)
            baos.write(buffer, 0, bytesRead);
    }

    if (mime.indexOf(";") != -1) {
        mime = mime.substring(0, mime.indexOf(";"));
    }
    String mimeType = getMimeType(mime);
    if (mimeType == null) {
        String message = baos.toString();
        message = message.replaceAll("(\\r|\\n)", "");
        log.error("Response from server not understood (mime = " + mime + "): " + message);
        throw new Exception("Response from server not understood (mime = " + mime + "): " + message);
    }

    ImageReader ir = getReader(mimeType);
    if (ir == null) {
        log.error("no reader available for imageformat: " + mimeType.substring(mimeType.lastIndexOf("/") + 1));
        throw new Exception(
                "no reader available for imageformat: " + mimeType.substring(mimeType.lastIndexOf("/") + 1));
    }

    //TODO Make smarter.. Possibly faster... But keep reporting!
    wmsRequest.setBytesReceived(new Long(baos.size()));
    ImageInputStream stream = ImageIO.createImageInputStream(new ByteArrayInputStream(baos.toByteArray()));
    ir.setInput(stream, true);
    try {
        //if image is a png, has no alpha and has a tRNS then make that color transparent.
        BufferedImage i = ir.read(0);
        if (!i.getColorModel().hasAlpha() && ir.getImageMetadata(0) instanceof PNGMetadata) {
            PNGMetadata metadata = (PNGMetadata) ir.getImageMetadata(0);
            if (metadata.tRNS_present) {
                int alphaPix = (metadata.tRNS_red << 16) | (metadata.tRNS_green << 8) | (metadata.tRNS_blue);
                BufferedImage tmp = new BufferedImage(i.getWidth(), i.getHeight(), BufferedImage.TYPE_INT_ARGB);
                for (int x = 0; x < i.getWidth(); x++) {
                    for (int y = 0; y < i.getHeight(); y++) {
                        int rgb = i.getRGB(x, y);
                        rgb = (rgb & 0xFFFFFF) == alphaPix ? alphaPix : rgb;
                        tmp.setRGB(x, y, rgb);
                    }
                }
                i = tmp;
            }
        }
        return i;
    } finally {
        ir.dispose();
    }
}