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 BufferedImage[] split2RGB(BufferedImage img) {

    //--------------------v2.0--------------------------------------
    int w, h, r, g, b, pixel;

    if (img.getType() == BufferedImage.TYPE_INT_RGB) {
        w = img.getWidth();/*from  w  w  w.j  a  v a 2  s . c o  m*/
        h = img.getHeight();
        BufferedImage[] out = new BufferedImage[3];
        WritableRaster[] rasters = new WritableRaster[3];
        for (int i = 0; i < 3; i++) {
            out[i] = new BufferedImage(w, h, BufferedImage.TYPE_BYTE_GRAY);
            rasters[i] = out[i].getRaster();
        }

        ColorModel cm = img.getColorModel();
        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);

                rasters[0].setSample(x, y, 0, r);
                rasters[1].setSample(x, y, 0, g);
                rasters[2].setSample(x, y, 0, b);
            }
        }
        return out;
    } else {
        return null;
    }
}

From source file:org.jtrfp.trcl.core.ResourceManager.java

private BufferedImage[] getSpecialRAWImage(String name, Color[] palette, int upscalePowerOfTwo)
        throws IllegalAccessException, FileLoadException, IOException {
    RAWFile dat = getRAW(name);/*  w  ww  .j a v a 2  s .  c  o m*/
    dat.setPalette(palette);
    BufferedImage[] segs = dat.asSegments(upscalePowerOfTwo);
    for (BufferedImage seg : segs) {
        Graphics g = seg.getGraphics();
        BufferedImage scaled = new BufferedImage(seg.getColorModel(), seg.copyData(null),
                seg.isAlphaPremultiplied(), null);
        g.drawImage(
                scaled.getScaledInstance(seg.getWidth() - 2, seg.getHeight() - 2, Image.SCALE_AREA_AVERAGING),
                1, 1, seg.getWidth() - 2, seg.getHeight() - 2, null);
        g.dispose();
    }
    return segs;
}

From source file:org.sbs.util.ImageCompress.java

/**
 * ?//from  w  w w.j a v a 2  s . c o m
 * 
 * @param source
 * @param targetW
 * @param targetH
 * @return
 */
public BufferedImage resize(BufferedImage source, int targetW, int targetH) {
    // targetWtargetH
    int desH = 0;
    int type = source.getType();
    BufferedImage target = null;
    double sx = (double) targetW / source.getWidth();
    double sy = sx;
    desH = (int) (sx * source.getHeight());
    if (desH < targetH) {
        desH = targetH;
        sy = (double) 61 / source.getHeight();
    }
    if (type == BufferedImage.TYPE_CUSTOM) { // handmade
        ColorModel cm = source.getColorModel();
        WritableRaster raster = cm.createCompatibleWritableRaster(targetW, desH);
        boolean alphaPremultiplied = cm.isAlphaPremultiplied();
        target = new BufferedImage(cm, raster, alphaPremultiplied, null);
    } else
        target = new BufferedImage(targetW, desH, type);
    Graphics2D g = target.createGraphics();
    // smoother than exlax:
    g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
    g.drawRenderedImage(source, AffineTransform.getScaleInstance(sx, sy));
    g.dispose();
    return target;
}

From source file:org.apache.carbondata.sdk.file.ImageTest.java

public void binaryToCarbonWithHWD(String sourceImageFolder, String outputPath, String preDestPath,
        String sufAnnotation, final String sufImage, int numToWrite) throws Exception {
    int num = 1;//w  w w  .jav a2 s  . c  om
    Field[] fields = new Field[7];
    fields[0] = new Field("height", DataTypes.INT);
    fields[1] = new Field("width", DataTypes.INT);
    fields[2] = new Field("depth", DataTypes.INT);
    fields[3] = new Field("binaryName", DataTypes.STRING);
    fields[4] = new Field("binary", DataTypes.BINARY);
    fields[5] = new Field("labelName", DataTypes.STRING);
    fields[6] = new Field("labelContent", DataTypes.STRING);

    byte[] originBinary = null;

    // read and write image data
    for (int j = 0; j < num; j++) {

        Object[] files = listFiles(sourceImageFolder, sufImage).toArray();

        int index = 0;

        if (null != files) {
            CarbonWriter writer = CarbonWriter.builder().outputPath(outputPath).withCsvInput(new Schema(fields))
                    .withBlockSize(256).writtenBy("SDKS3Example").withPageSizeInMb(1).build();

            for (int i = 0; i < files.length; i++) {
                if (0 == index % numToWrite) {
                    writer.close();
                    writer = CarbonWriter.builder().outputPath(outputPath).withCsvInput(new Schema(fields))
                            .withBlockSize(256).writtenBy("SDKS3Example").withPageSizeInMb(1).build();
                }
                index++;

                // read image and encode to Hex
                File file = new File((String) files[i]);
                System.out.println(file.getCanonicalPath());
                BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
                int depth = 0;
                boolean isGray;
                boolean hasAlpha;
                BufferedImage bufferedImage = null;
                try {
                    bufferedImage = ImageIO.read(file);
                    isGray = bufferedImage.getColorModel().getColorSpace().getType() == ColorSpace.TYPE_GRAY;
                    hasAlpha = bufferedImage.getColorModel().hasAlpha();

                    if (isGray) {
                        depth = 1;
                    } else if (hasAlpha) {
                        depth = 4;
                    } else {
                        depth = 3;
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                    System.out.println(i);
                    ImageInputStream stream = new FileImageInputStream(new File(file.getCanonicalPath()));
                    Iterator<ImageReader> iter = ImageIO.getImageReaders(stream);

                    Exception lastException = null;
                    while (iter.hasNext()) {
                        ImageReader reader = null;
                        try {
                            reader = (ImageReader) iter.next();
                            ImageReadParam param = reader.getDefaultReadParam();
                            reader.setInput(stream, true, true);
                            Iterator<ImageTypeSpecifier> imageTypes = reader.getImageTypes(0);

                            while (imageTypes.hasNext()) {
                                ImageTypeSpecifier imageTypeSpecifier = imageTypes.next();
                                System.out
                                        .println(imageTypeSpecifier.getColorModel().getColorSpace().getType());
                                int bufferedImageType = imageTypeSpecifier.getBufferedImageType();
                                if (bufferedImageType == BufferedImage.TYPE_BYTE_GRAY) {
                                    param.setDestinationType(imageTypeSpecifier);
                                    break;
                                }
                            }
                            bufferedImage = reader.read(0, param);
                            isGray = bufferedImage.getColorModel().getColorSpace()
                                    .getType() == ColorSpace.TYPE_GRAY;
                            hasAlpha = bufferedImage.getColorModel().hasAlpha();

                            if (isGray) {
                                depth = 1;
                            } else if (hasAlpha) {
                                depth = 4;
                            } else {
                                depth = 3;
                            }
                            if (null != bufferedImage)
                                break;
                        } catch (Exception e2) {
                            lastException = e2;
                        } finally {
                            if (null != reader)
                                reader.dispose();
                        }
                    }
                    // If you don't have an image at the end of all readers
                    if (null == bufferedImage) {
                        if (null != lastException) {
                            throw lastException;
                        }
                    }
                } finally {
                    originBinary = new byte[bis.available()];
                    while ((bis.read(originBinary)) != -1) {
                    }

                    String txtFileName = file.getCanonicalPath().split(sufImage)[0] + sufAnnotation;
                    BufferedInputStream txtBis = new BufferedInputStream(new FileInputStream(txtFileName));
                    String txtValue = null;
                    byte[] txtBinary = null;
                    txtBinary = new byte[txtBis.available()];
                    while ((txtBis.read(txtBinary)) != -1) {
                        txtValue = new String(txtBinary, "UTF-8");
                    }
                    // write data
                    writer.write(new Object[] { bufferedImage.getHeight(), bufferedImage.getWidth(), depth,
                            file.getCanonicalPath(), originBinary, txtFileName, txtValue.replace("\n", "") });
                    bis.close();
                }
            }
            writer.close();
        }
    }

    CarbonReader reader = CarbonReader.builder(outputPath).build();

    System.out.println("\nData:");
    int i = 0;
    while (i < 20 && reader.hasNext()) {
        Object[] row = (Object[]) reader.readNextRow();

        byte[] outputBinary = (byte[]) row[1];
        System.out.println(row[2] + " " + row[3] + " " + row[4] + " " + row[5] + " image size:"
                + outputBinary.length + " " + row[0]);

        // save image, user can compare the save image and original image
        String destString = preDestPath + i + sufImage;
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destString));
        bos.write(outputBinary);
        bos.close();
        i++;
    }
    System.out.println("\nFinished");
    reader.close();
}

From source file:ImageOpByRomain.java

/**
 * {@inheritDoc}//  ww  w  .  j a v a 2 s  . co  m
 */
public BufferedImage createCompatibleDestImage(BufferedImage src, ColorModel destCM) {
    if (destCM == null) {
        destCM = src.getColorModel();
    }

    return new BufferedImage(destCM, destCM.createCompatibleWritableRaster(src.getWidth(), src.getHeight()),
            destCM.isAlphaPremultiplied(), null);
}

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

private static BufferedImage PaletteToARGB(BufferedImage src) {
    IndexColorModel icm = (IndexColorModel) src.getColorModel();
    int bands = icm.hasAlpha() ? 4 : 3;

    byte[][] data = new byte[bands][icm.getMapSize()];
    if (icm.hasAlpha())
        icm.getAlphas(data[3]);//ww  w  .j av a  2s  . c  o  m
    icm.getReds(data[0]);
    icm.getGreens(data[1]);
    icm.getBlues(data[2]);
    LookupTableJAI rtable = new LookupTableJAI(data);
    return JAI.create("lookup", src, rtable).getAsBufferedImage();
}

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

/**
 * This method returns true if the specified image has transparent pixels
 * @param image//w  ww .  j  av a  2s  . c  o m
 * @return
 */
public static boolean hasAlpha(java.awt.Image image) {
    // If buffered image, the color model is readily available
    if (image instanceof BufferedImage) {
        BufferedImage bimage = (BufferedImage) image;
        return bimage.getColorModel().hasAlpha();
    }

    // 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) {
    }

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

From source file:org.jahia.services.image.AbstractJava2DImageService.java

public boolean rotateImage(Image image, File outputFile, boolean clockwise) throws IOException {
    BufferedImage originalImage = ((BufferImage) image).getOriginalImage();

    BufferedImage dest = getDestImage(originalImage.getHeight(), originalImage.getWidth(), originalImage);
    // Paint source image into the destination, scaling as needed
    Graphics2D graphics2D = getGraphics2D(dest, OperationType.ROTATE);

    double angle = Math.toRadians(clockwise ? 90 : -90);
    double sin = Math.abs(Math.sin(angle)), cos = Math.abs(Math.cos(angle));
    int w = originalImage.getWidth(), h = originalImage.getHeight();
    int neww = (int) Math.floor(w * cos + h * sin), newh = (int) Math.floor(h * cos + w * sin);
    graphics2D.translate((neww - w) / 2, (newh - h) / 2);
    graphics2D.rotate(angle, w / (double) 2, h / (double) 2);
    graphics2D.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC));
    if (originalImage.getColorModel() instanceof IndexColorModel) {
        graphics2D.drawImage(originalImage, 0, 0, graphics2D.getBackground(), null);
    } else {//  w w  w  .  j  av a  2  s  .c  o m
        graphics2D.drawImage(originalImage, 0, 0, null);
    }

    // Save destination image
    saveImageToFile(dest, ((BufferImage) image).getMimeType(), outputFile);
    return true;
}

From source file:gov.lanl.adore.djatoka.plugin.ExtractPDF.java

public final ImageRecord getMetadata(BufferedImage bi) throws DjatokaException {
    if (bi == null)
        throw new DjatokaException("Image Does Not Exist");

    logger.debug("getMetadata(BufferedImage): " + bi.getWidth());
    try {/*from  w ww  . j  a  v a2s  .c  om*/
        ImageRecord r = new ImageRecord();

        r.setWidth(bi.getWidth());
        r.setHeight(bi.getHeight());

        r.setDWTLevels(DEFAULT_LEVELS);
        r.setLevels(DEFAULT_LEVELS);

        r.setBitDepth(bi.getColorModel().getPixelSize());
        r.setNumChannels(bi.getColorModel().getNumColorComponents());
        //r.setCompositingLayerCount(getNumberOfPages(r)); // 'bi' refers to just one page extracted from the PDF file.
        //logger.debug("r2: "+r.toString());

        //TODO

        return r;
    } catch (Exception e) {
        throw new DjatokaException(e);
    }
}

From source file:nl.b3p.imagetool.ImageTool.java

/**
 * Reads an image from an http input stream.
 *
 * @param method Apache HttpClient GetMethod object
 * @param mime String representing the mime type of the image.
 *
 * @return BufferedImage//  w  ww  . java 2 s  . c  o m
 *
 * @throws Exception
 */
// <editor-fold defaultstate="" desc="readImage(GetMethod method, String mime) method.">
public static BufferedImage readImage(InputStream is, String mime) 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);
        }
    }
    ImageReader ir = null;
    BufferedImage i = null;
    try {
        if (mime.indexOf(";") != -1) {
            mime = mime.substring(0, mime.indexOf(";"));
        }
        String mimeType = getMimeType(mime);

        /* TODO: Kijken waarom er geen mime type meer binnenkomt. Wellicht door de
         * HttpClient vernieuwing in kaartenbalie ? */
        if (mimeType == null) {
            mimeType = "image/png";
        }

        if (mimeType == null) {
            log.error("Response from server not understood (mime = " + mime + "): " + baos.toString());
            throw new Exception(
                    "Response from server not understood (mime = " + mime + "): " + baos.toString());
        }

        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!
        ImageInputStream stream = ImageIO.createImageInputStream(new ByteArrayInputStream(baos.toByteArray()));
        ir.setInput(stream, true);
        i = ir.read(0);
        //if image is a png, has no alpha and has a tRNS then make that color transparent.
        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;
            }
        }
    } finally {
        if (ir != null) {
            ir.dispose();
        }
    }
    return i;
}