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:pl.edu.icm.visnow.lib.utils.ImageUtilities.java

public static void fadeImages(BufferedImage source1, BufferedImage source2, BufferedImage target, int relX,
        int targetX) {
    int pixel1, pixel2, newPixel;
    double f;/*w  ww . jav a  2s  .c o m*/
    int r1, g1, b1, r2, g2, b2;
    byte newR, newG, newB;
    ColorModel cm = source1.getColorModel();

    for (int x = relX; x < source1.getWidth(); x++) {
        f = linearF(x, relX, source1.getWidth());
        for (int y = 0; y < source1.getHeight(); y++) {
            pixel1 = source1.getRGB(x, y);
            pixel2 = source2.getRGB(x - relX, y);

            r1 = cm.getRed(pixel1);
            g1 = cm.getGreen(pixel1);
            b1 = cm.getBlue(pixel1);
            r2 = cm.getRed(pixel2);
            g2 = cm.getGreen(pixel2);
            b2 = cm.getBlue(pixel2);

            int tr = 10;

            if (r1 < tr && g1 < tr && b1 < tr) {
                newPixel = pixel2;
            } else if (r2 < tr && g2 < tr && b2 < tr) {
                newPixel = pixel1;
            } else {
                newR = (byte) Math.round(((double) r1) * (1 - f) + ((double) r2) * f);
                newG = (byte) Math.round(((double) g1) * (1 - f) + ((double) g2) * f);
                newB = (byte) Math.round(((double) b1) * (1 - f) + ((double) b2) * f);
                newPixel = (newR & 0xff) << 16 | (newG & 0xff) << 8 | (newB & 0xff) << 0;
            }
            target.setRGB(x + targetX, y, newPixel);
        }

    }
}

From source file:org.deegree.tile.persistence.geotiff.GeoTIFFTile.java

@Override
public BufferedImage getAsImage() throws TileIOException {
    ImageReader reader = null;//from w w w . j  a  va  2  s . co m
    try {
        reader = (ImageReader) readerPool.borrowObject();
        BufferedImage img = reader.readTile(imageIndex, x, y);
        if (img.getWidth() != sizeX || img.getHeight() != sizeY) {
            Hashtable<Object, Object> table = new Hashtable<Object, Object>();
            String[] props = img.getPropertyNames();
            if (props != null) {
                for (String p : props) {
                    table.put(p, img.getProperty(p));
                }
            }
            BufferedImage img2 = new BufferedImage(img.getColorModel(),
                    img.getData().createCompatibleWritableRaster(sizeX, sizeY), img.isAlphaPremultiplied(),
                    table);
            Graphics2D g = img2.createGraphics();
            g.drawImage(img, 0, 0, null);
            g.dispose();
            img = img2;
        }
        return img;
    } catch (Exception e) {
        throw new TileIOException("Error retrieving image: " + e.getMessage(), e);
    } finally {
        try {
            readerPool.returnObject(reader);
        } catch (Exception e) {
            // ignore closing error
        }
    }
}

From source file:org.csa.rstb.dat.toolviews.HaAlphaPlotPanel.java

private byte[] getValidData(BufferedImage image) {
    if (image != null && image.getColorModel() instanceof IndexColorModel
            && image.getData().getDataBuffer() instanceof DataBufferByte) {
        return ((DataBufferByte) image.getData().getDataBuffer()).getData();
    }//from   w w  w  .  j a v  a2 s .c  o  m
    return null;
}

From source file:uk.co.modularaudio.service.imagefactory.impl.ComponentImageFactoryImpl.java

private BufferedImage getBufferedImageFromPath(final String filename) throws DatastoreException {
    final String pathToLoad = filename;
    BufferedImage retVal = biCache.get(pathToLoad);

    if (retVal == null) {
        try {/*from  w  ww.ja  va 2  s  .  c o  m*/
            final String resourcePath = resourcePrefix + pathToLoad;
            final InputStream iis = this.getClass().getResourceAsStream(resourcePath);
            if (iis == null) {
                throw new DatastoreException("Failed to find image resource at path: " + resourcePath);
            }
            retVal = ImageIO.read(iis);
            if (log.isDebugEnabled()) {
                log.debug("Adding " + pathToLoad + " to buffered image cache");
            }
            if (retVal.getColorModel().hasAlpha()) {
                if (log.isWarnEnabled()) {
                    log.warn("Image " + pathToLoad + " has alpha, and probably shouldn't");
                }
            }
            biCache.put(pathToLoad, retVal);
        } catch (final IOException ie) {
            final String msg = "Exception caught loading image " + pathToLoad + ": " + ie.toString();
            log.error(msg, ie);
            throw new DatastoreException(msg, ie);
        }
    }

    return retVal;
}

From source file:pl.edu.icm.visnow.lib.utils.ImageUtilities.java

public static BufferedImage rgb2gray(BufferedImage img) {
    if (img.getType() == BufferedImage.TYPE_INT_ARGB || img.getType() == BufferedImage.TYPE_INT_RGB) {
        int w, h;
        w = img.getWidth();//from www  . j a v a  2s.co m
        h = img.getHeight();
        BufferedImage out = new BufferedImage(w, h, BufferedImage.TYPE_BYTE_GRAY);

        //----------------------------v3.0----------------------
        ColorModel cm = img.getColorModel();
        int pixel, gr;
        int r, g, b;
        WritableRaster raster = out.getRaster();
        for (int x = 0; x < w; x++) {
            for (int y = 0; y < h; y++) {
                pixel = img.getRGB(x, y);
                r = cm.getRed(pixel);
                g = cm.getGreen(pixel);
                b = cm.getBlue(pixel);

                gr = (int) Math.round(((double) r + (double) g + (double) b) / 3.0);
                raster.setSample(x, y, 0, gr);
            }
        }
        return out;
    }
    return img;
}

From source file:org.codice.alliance.imaging.chip.transformer.CatalogOutputAdapter.java

private void setImageDataFields(BufferedImage chip, ImageSegment chipImageSegment) throws IOException {

    int[] componentSizes = chip.getColorModel().getComponentSize();
    int pixelSize = chip.getColorModel().getPixelSize();

    switch (chip.getType()) {
    case BufferedImage.TYPE_BYTE_GRAY:
    case BufferedImage.TYPE_USHORT_GRAY:
    case BufferedImage.TYPE_BYTE_BINARY:
        setMonochrome(chipImageSegment, componentSizes[0], pixelSize);
        break;//from ww w . j  a v a  2 s  .c  o  m
    case BufferedImage.TYPE_3BYTE_BGR:
    case BufferedImage.TYPE_INT_BGR:
        setImageFieldHelper(chipImageSegment, PixelValueType.INTEGER, ImageRepresentation.RGBTRUECOLOUR,
                componentSizes[0], pixelSize / 3, new String[] { "B", "G", "R" });
        break;
    case BufferedImage.TYPE_4BYTE_ABGR:
    case BufferedImage.TYPE_4BYTE_ABGR_PRE:
        setImageFieldHelper(chipImageSegment, PixelValueType.INTEGER, ImageRepresentation.RGBTRUECOLOUR,
                componentSizes[0], pixelSize / 4, new String[] { "B", "G", "R" });
        break;
    case BufferedImage.TYPE_INT_ARGB_PRE:
    case BufferedImage.TYPE_INT_ARGB:
        setARGB(chipImageSegment, componentSizes[0], pixelSize);
        break;
    case BufferedImage.TYPE_INT_RGB:
    case BufferedImage.TYPE_USHORT_555_RGB:
        setRGB(chipImageSegment, componentSizes[0], pixelSize);
        break;
    case BufferedImage.TYPE_CUSTOM:
        if (componentSizes.length == 1) {
            setMonochrome(chipImageSegment, componentSizes[0], pixelSize);
        } else if (componentSizes.length == 3) {
            setRGB(chipImageSegment, componentSizes[0], pixelSize);
        } else if (componentSizes.length == 4) {
            setARGB(chipImageSegment, componentSizes[0], pixelSize);
        } else {
            throw new IOException(
                    "unsupported color model for image type CUSTOM, only monochrome and 32-bit argb are supported");
        }
        break;
    case BufferedImage.TYPE_BYTE_INDEXED:
        setImageFieldHelper(chipImageSegment, PixelValueType.INTEGER, ImageRepresentation.RGBLUT,
                componentSizes[0], pixelSize, new String[] { "LU" });
        break;
    case BufferedImage.TYPE_USHORT_565_RGB:
        // don't know how to handle this one, since the bitsPerPixelPerBand is not consistent
        break;
    default:
        throw new IOException("unsupported image data type: type=" + chip.getType());
    }
}

From source file:net.pms.util.GenericIcons.java

/**
 * Add the format(container) name of the media to the generic icon image.
 *
 * @param image BufferdImage to be the label added
 * @param label the media container name to be added as a label
 * @param renderer the renderer configuration
 *
 * @return the generic icon with the container label added and scaled in accordance with renderer setting
 *//*from   w  w w.  j  a  v  a  2 s .  c  o  m*/
private DLNAThumbnail addFormatLabelToImage(String label, ImageFormat imageFormat, IconType iconType)
        throws IOException {

    BufferedImage image;
    switch (iconType) {
    case AUDIO:
        image = genericAudioIcon;
        break;
    case IMAGE:
        image = genericImageIcon;
        break;
    case VIDEO:
        image = genericVideoIcon;
        break;
    default:
        image = genericUnknownIcon;
    }

    if (image != null) {
        // Make a copy
        ColorModel colorModel = image.getColorModel();
        image = new BufferedImage(colorModel, image.copyData(null), colorModel.isAlphaPremultiplied(), null);
    }

    ByteArrayOutputStream out = null;

    if (label != null && image != null) {
        out = new ByteArrayOutputStream();
        Graphics2D g = image.createGraphics();
        g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

        try {
            int size = 40;
            Font font = new Font(Font.SANS_SERIF, Font.BOLD, size);
            FontMetrics metrics = g.getFontMetrics(font);
            while (size > 7 && metrics.stringWidth(label) > 135) {
                size--;
                font = new Font(Font.SANS_SERIF, Font.BOLD, size);
                metrics = g.getFontMetrics(font);
            }
            // Text center point 127x, 49y - calculate centering coordinates
            int x = 127 - metrics.stringWidth(label) / 2;
            int y = 46 + metrics.getAscent() / 2;
            g.drawImage(image, 0, 0, null);
            g.setColor(Color.WHITE);
            g.setFont(font);
            g.drawString(label, x, y);

            ImageIO.setUseCache(false);
            ImageIOTools.imageIOWrite(image, imageFormat.toString(), out);
        } finally {
            g.dispose();
        }
    }
    return out != null ? DLNAThumbnail.toThumbnail(out.toByteArray(), 0, 0, ScaleType.MAX, imageFormat, false)
            : null;
}

From source file:com.funambol.foundation.util.MediaUtils.java

/**
 * Rotates given buffered image by given amount of degree.
 * The valid degree values are 0, 90, 180, 270.
 * If the image is a jpg, the rotation is lossless, exif data are preserved
 * and image size is almost the same.//w  w w  .j  a v a 2  s.c  o m
 *
 * @param bufImage the buffered image
 * @param degree amount of degree to apply
 * @return a buffered image containing rotated image data
 * @throws PicturesException if amount of degree is invalid or if an
 *         IOException occurs
 */
private static BufferedImage rotateImage(BufferedImage bufImage, int degree)
        throws FileDataObjecyUtilsException {

    degree = degree % 360;
    int h;
    int w;

    switch (degree) {
    case 0:
    case 180:
        h = bufImage.getHeight();
        w = bufImage.getWidth();
        break;
    case 90:
    case 270:
        h = bufImage.getWidth();
        w = bufImage.getHeight();
        break;
    default:
        throw new FileDataObjecyUtilsException(
                "Error rotating image since the '" + degree + "' degree value is unsupported");
    }

    BufferedImage out = null;

    int bufImageType = bufImage.getType();
    if (BufferedImage.TYPE_BYTE_INDEXED == bufImageType || BufferedImage.TYPE_BYTE_BINARY == bufImageType) {

        IndexColorModel model = (IndexColorModel) bufImage.getColorModel();
        out = new BufferedImage(w, h, bufImage.getType(), model);

    } else if (BufferedImage.TYPE_CUSTOM == bufImageType) {

        // we don't know what type of image it can be

        // there's a bug in some VM that cause some PNG images to have 
        // type custom: this should take care of this issue

        //check if we need to have alpha channel
        boolean alpha = bufImage.getTransparency() != BufferedImage.OPAQUE;

        if (alpha) {
            // TYPE_INT_ARGB_PRE gives you smaller output images
            // than TYPE_INT_ARGB
            out = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB_PRE);
        } else {
            out = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        }

    } else {

        out = new BufferedImage(w, h, bufImage.getType());
    }

    Graphics2D g2d = out.createGraphics();

    Map renderingHints = new HashMap();

    renderingHints.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
    renderingHints.put(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);

    g2d.setRenderingHints(renderingHints);
    g2d.rotate(Math.toRadians(degree));

    switch (degree) {
    case 90:
        g2d.translate(0, -w);
        break;
    case 180:
        g2d.translate(-w, -h);
        break;
    case 270:
        g2d.translate(-h, 0);
        break;
    }

    g2d.drawImage(bufImage, null, 0, 0);
    g2d.dispose();

    return out;
}

From source file:org.geoserver.wms.wms_1_1_1.GetMapIntegrationTest.java

@Test
public void testPng8Opaque() throws Exception {
    MockHttpServletResponse response = getAsServletResponse("wms?bbox=" + bbox + "&styles=&layers=" + layers
            + "&Format=image/png8" + "&request=GetMap" + "&width=550" + "&height=250" + "&srs=EPSG:4326");
    assertEquals("image/png; mode=8bit", response.getContentType());
    assertEquals("inline; filename=sf-states.png", response.getHeader("Content-Disposition"));

    InputStream is = getBinaryInputStream(response);
    BufferedImage bi = ImageIO.read(is);
    IndexColorModel cm = (IndexColorModel) bi.getColorModel();
    assertEquals(Transparency.OPAQUE, cm.getTransparency());
    assertEquals(-1, cm.getTransparentPixel());
}

From source file:org.geoserver.wms.wms_1_1_1.GetMapIntegrationTest.java

@Test
public void testPng8Translucent() throws Exception {
    MockHttpServletResponse response = getAsServletResponse(
            "wms?bbox=" + bbox + "&styles=&layers=" + layers + "&Format=image/png8" + "&request=GetMap"
                    + "&width=550" + "&height=250" + "&srs=EPSG:4326&transparent=true");
    assertEquals("image/png; mode=8bit", response.getContentType());
    assertEquals("inline; filename=sf-states.png", response.getHeader("Content-Disposition"));

    InputStream is = getBinaryInputStream(response);
    BufferedImage bi = ImageIO.read(is);
    IndexColorModel cm = (IndexColorModel) bi.getColorModel();
    assertEquals(Transparency.TRANSLUCENT, cm.getTransparency());
}