Example usage for java.awt.image BufferedImage getSubimage

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

Introduction

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

Prototype

public BufferedImage getSubimage(int x, int y, int w, int h) 

Source Link

Document

Returns a subimage defined by a specified rectangular region.

Usage

From source file:com.occamlab.te.parsers.ImageParser.java

private static void processBufferedImage(BufferedImage buffimage, String formatName, NodeList nodes)
        throws Exception {
    HashMap<Object, Object> bandMap = new HashMap<Object, Object>();

    for (int i = 0; i < nodes.getLength(); i++) {
        Node node = nodes.item(i);
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            if (node.getLocalName().equals("subimage")) {
                Element e = (Element) node;
                int x = Integer.parseInt(e.getAttribute("x"));
                int y = Integer.parseInt(e.getAttribute("y"));
                int w = Integer.parseInt(e.getAttribute("width"));
                int h = Integer.parseInt(e.getAttribute("height"));
                processBufferedImage(buffimage.getSubimage(x, y, w, h), formatName, e.getChildNodes());
            } else if (node.getLocalName().equals("checksum")) {
                CRC32 checksum = new CRC32();
                Raster raster = buffimage.getRaster();
                DataBufferByte buffer;
                if (node.getParentNode().getLocalName().equals("subimage")) {
                    WritableRaster outRaster = raster.createCompatibleWritableRaster();
                    buffimage.copyData(outRaster);
                    buffer = (DataBufferByte) outRaster.getDataBuffer();
                } else {
                    buffer = (DataBufferByte) raster.getDataBuffer();
                }/*from   ww w .ja v  a  2s.c  o  m*/
                int numbanks = buffer.getNumBanks();
                for (int j = 0; j < numbanks; j++) {
                    checksum.update(buffer.getData(j));
                }
                Document doc = node.getOwnerDocument();
                node.appendChild(doc.createTextNode(Long.toString(checksum.getValue())));
            } else if (node.getLocalName().equals("count")) {
                String band = ((Element) node).getAttribute("bands");
                String sample = ((Element) node).getAttribute("sample");
                if (sample.equals("all")) {
                    bandMap.put(band, null);
                } else {
                    HashMap<Object, Object> sampleMap = (HashMap<Object, Object>) bandMap.get(band);
                    if (sampleMap == null) {
                        if (!bandMap.containsKey(band)) {
                            sampleMap = new HashMap<Object, Object>();
                            bandMap.put(band, sampleMap);
                        }
                    }
                    sampleMap.put(Integer.decode(sample), new Integer(0));
                }
            } else if (node.getLocalName().equals("transparentNodata")) { // 2011-08-24
                                                                          // PwD
                String transparentNodata = checkTransparentNodata(buffimage, node);
                node.setTextContent(transparentNodata);
            }
        }
    }

    Iterator bandIt = bandMap.keySet().iterator();
    while (bandIt.hasNext()) {
        String band_str = (String) bandIt.next();
        int band_indexes[];
        if (buffimage.getType() == BufferedImage.TYPE_BYTE_BINARY
                || buffimage.getType() == BufferedImage.TYPE_BYTE_GRAY) {
            band_indexes = new int[1];
            band_indexes[0] = 0;
        } else {
            band_indexes = new int[band_str.length()];
            for (int i = 0; i < band_str.length(); i++) {
                if (band_str.charAt(i) == 'A')
                    band_indexes[i] = 3;
                if (band_str.charAt(i) == 'B')
                    band_indexes[i] = 2;
                if (band_str.charAt(i) == 'G')
                    band_indexes[i] = 1;
                if (band_str.charAt(i) == 'R')
                    band_indexes[i] = 0;
            }
        }

        Raster raster = buffimage.getRaster();
        java.util.HashMap sampleMap = (java.util.HashMap) bandMap.get(band_str);
        boolean addall = (sampleMap == null);
        if (sampleMap == null) {
            sampleMap = new java.util.HashMap();
            bandMap.put(band_str, sampleMap);
        }

        int minx = raster.getMinX();
        int maxx = minx + raster.getWidth();
        int miny = raster.getMinY();
        int maxy = miny + raster.getHeight();
        int bands[][] = new int[band_indexes.length][raster.getWidth()];

        for (int y = miny; y < maxy; y++) {
            for (int i = 0; i < band_indexes.length; i++) {
                raster.getSamples(minx, y, maxx, 1, band_indexes[i], bands[i]);
            }
            for (int x = minx; x < maxx; x++) {
                int sample = 0;
                for (int i = 0; i < band_indexes.length; i++) {
                    sample |= bands[i][x] << ((band_indexes.length - i - 1) * 8);
                }

                Integer sampleObj = new Integer(sample);

                boolean add = addall;
                if (!addall) {
                    add = sampleMap.containsKey(sampleObj);
                }
                if (add) {
                    Integer count = (Integer) sampleMap.get(sampleObj);
                    if (count == null) {
                        count = new Integer(0);
                    }
                    count = new Integer(count.intValue() + 1);
                    sampleMap.put(sampleObj, count);
                }
            }
        }
    }

    Node node = nodes.item(0);
    while (node != null) {
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            if (node.getLocalName().equals("count")) {
                String band = ((Element) node).getAttribute("bands");
                String sample = ((Element) node).getAttribute("sample");
                HashMap sampleMap = (HashMap) bandMap.get(band);
                Document doc = node.getOwnerDocument();
                if (sample.equals("all")) {
                    Node parent = node.getParentNode();
                    Node prevSibling = node.getPreviousSibling();
                    Iterator sampleIt = sampleMap.keySet().iterator();
                    Element countnode = null;
                    int digits;
                    String prefix;
                    switch (buffimage.getType()) {
                    case BufferedImage.TYPE_BYTE_BINARY:
                        digits = 1;
                        prefix = "";
                        break;
                    case BufferedImage.TYPE_BYTE_GRAY:
                        digits = 2;
                        prefix = "0x";
                        break;
                    default:
                        prefix = "0x";
                        digits = band.length() * 2;
                    }
                    while (sampleIt.hasNext()) {
                        countnode = doc.createElementNS(node.getNamespaceURI(), "count");
                        Integer sampleInt = (Integer) sampleIt.next();
                        Integer count = (Integer) sampleMap.get(sampleInt);
                        if (band.length() > 0) {
                            countnode.setAttribute("bands", band);
                        }
                        countnode.setAttribute("sample", prefix + HexString(sampleInt.intValue(), digits));
                        Node textnode = doc.createTextNode(count.toString());
                        countnode.appendChild(textnode);
                        parent.insertBefore(countnode, node);
                        if (sampleIt.hasNext()) {
                            if (prevSibling != null && prevSibling.getNodeType() == Node.TEXT_NODE) {
                                parent.insertBefore(prevSibling.cloneNode(false), node);
                            }
                        }
                    }
                    parent.removeChild(node);
                    node = countnode;
                } else {
                    Integer count = (Integer) sampleMap.get(Integer.decode(sample));
                    if (count == null)
                        count = new Integer(0);
                    Node textnode = doc.createTextNode(count.toString());
                    node.appendChild(textnode);
                }
            }
        }
        node = node.getNextSibling();
    }
}

From source file:algorithm.ImageImageFrameExpanding.java

/**
 * Returns the image in which the restoration metadata is embedded. This
 * image is appended at the end of the encapsulated data image.
 * //from w  ww . jav a2  s. c  om
 * The restoration metadata image contains the restoration metadata file,
 * which was embedded with the lsb steganography algorithm and has to be
 * restored afterwards.
 * 
 * @param encapsulatedData
 * @return image with embedded restoration data
 * @throws IOException
 */
protected File restoreRestorationMetadataImage(File encapsulatedData) {
    try {
        BufferedImage encapsulatedImage = ImageIO.read(encapsulatedData);
        if (encapsulatedImage.getHeight() < METADATA_HEIGHT) {
            return null;
        }
        BufferedImage restorationMetadataBuffered = encapsulatedImage.getSubimage(0,
                encapsulatedImage.getHeight() - METADATA_HEIGHT, encapsulatedImage.getWidth(), METADATA_HEIGHT);
        File embeddedRestorationMetadata = new File("tmpRestorationMetadata.png");
        tmpFiles.add(embeddedRestorationMetadata);
        writeImage(embeddedRestorationMetadata, restorationMetadataBuffered);
        return embeddedRestorationMetadata;
    } catch (IOException e) {
        return null;
    }
}

From source file:edu.harvard.mcz.imagecapture.TemplatePickerDialog.java

protected void init(ICImage image) {
    setBounds(100, 100, 450, 300);/*  ww w .  j a va 2  s  . c o  m*/
    StringBuffer title = new StringBuffer();
    title.append("Change Template");
    if (image != null) {
        title.append(" for ").append(image.getFilename());
    }
    this.setTitle(title.toString());
    getContentPane().setLayout(new BorderLayout());
    contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
    getContentPane().add(contentPanel, BorderLayout.CENTER);
    contentPanel.setLayout(new BorderLayout(0, 0));
    {
        lblTemplate = new JLabel("Template");
        lblTemplate.setHorizontalAlignment(SwingConstants.CENTER);
        contentPanel.add(lblTemplate, BorderLayout.NORTH);
    }
    {
        comboBoxTemplatePicker = new JComboBox<String>();
        comboBoxTemplatePicker.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                // TODO Auto-generated method stub
                PositionTemplate defaultTemplate;
                try {
                    defaultTemplate = new PositionTemplate((String) comboBoxTemplatePicker.getSelectedItem());

                    File fileToCheck = new File(ImageCaptureProperties
                            .assemblePathWithBase(imageToTemplate.getPath(), imageToTemplate.getFilename()));

                    BufferedImage imagefile = ImageIO.read(fileToCheck);

                    int x = defaultTemplate.getBarcodeULPosition().width;
                    int y = defaultTemplate.getBarcodeULPosition().height;
                    int w = defaultTemplate.getBarcodeSize().width;
                    int h = defaultTemplate.getBarcodeSize().height;
                    setBarcodeImage(imagefile.getSubimage(x, y, w, h));

                } catch (NullPointerException e1) {
                    log.error(e1.getMessage());
                } catch (NoSuchTemplateException e1) {
                    log.error(e1.getMessage());
                } catch (IOException e1) {
                    log.error(e1.getMessage());
                }
            }

        });
        contentPanel.add(comboBoxTemplatePicker, BorderLayout.SOUTH);
    }
    {
        JPanel panel = new JPanel();
        contentPanel.add(panel, BorderLayout.CENTER);
        panel.setLayout(new BorderLayout(0, 0));
        {
            lblFileName = new JLabel("FileName");
            panel.add(lblFileName, BorderLayout.NORTH);
        }
        {
            labelBarcodeImage = new JLabel("Catalog Number Barcode");
            labelBarcodeImage.setIcon(new ImageIcon(TemplatePickerDialog.class
                    .getResource("/edu/harvard/mcz/imagecapture/resources/gnome-mime-image.png")));
            panel.add(labelBarcodeImage, BorderLayout.CENTER);
        }
    }
    {
        JPanel buttonPane = new JPanel();
        buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
        getContentPane().add(buttonPane, BorderLayout.SOUTH);
        {
            JButton okButton = new JButton("OK");
            okButton.setActionCommand("OK");
            okButton.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    // TODO Auto-generated method stub
                    ICImageLifeCycle ils = new ICImageLifeCycle();
                    try {
                        String newTemplateID = (String) comboBoxTemplatePicker.getSelectedItem();
                        if (newTemplateID != null) {
                            imageToTemplate.setTemplateId(newTemplateID);
                            ils.attachDirty(imageToTemplate);
                            setVisible(false);
                        }
                    } catch (SaveFailedException e1) {
                        log.error(e1.getMessage(), e1);
                    }
                }

            });
            buttonPane.add(okButton);
            getRootPane().setDefaultButton(okButton);
        }
        {
            JButton cancelButton = new JButton("Cancel");
            cancelButton.setActionCommand("Cancel");
            cancelButton.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    setVisible(false);
                }

            });
            buttonPane.add(cancelButton);
        }
    }
    if (image != null) {
        try {
            boolean result = setupForImage(image);
        } catch (UnreadableFileException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

From source file:algorithm.ImageImageFrameExpanding.java

/**
 * Get the carrier image from the encapsulated data.
 * //from  www  . ja  v  a  2s. c  o m
 * @param encapsulatedImage
 * @param restorationMetadata
 * @return carrier image
 * @throws IOException
 */
protected RestoredFile restoreCarrier(File encapsulatedImage, Properties restorationMetadata)
        throws IOException {
    BufferedImage encapsulatedImageBuffered = ImageIO.read(encapsulatedImage);
    int carrierWidth = Integer.parseInt(restorationMetadata.getProperty("carrierWidth"));
    int carrierHeight = Integer.parseInt(restorationMetadata.getProperty("carrierHeight"));
    BufferedImage carrierBuffered = encapsulatedImageBuffered.getSubimage(0, 0, carrierWidth, carrierHeight);
    String originalCarrierPath = restorationMetadata.getProperty("carrierPath");
    RestoredFile carrier = new RestoredFile(RESTORED_DIRECTORY + Paths.get(originalCarrierPath).getFileName());
    writeImage(carrier, carrierBuffered);
    carrier.wasCarrier = true;
    carrier.wasPayload = false;
    carrier.checksumValid = false;
    carrier.originalFilePath = originalCarrierPath;
    carrier.algorithm = this;
    carrier.restorationNote = "It is not possible to get exactly the same checksum, because of internal lossless PNG compression mechanisms.";
    return carrier;
}

From source file:algorithm.ImageImageFrameExpanding.java

/**
 * Get the payload image, in which the payload file is embedded, from the
 * encapsulated data./*from  ww w  .  j  a  v  a2s  . c om*/
 * 
 * @param encapsulatedImage
 * @param restorationMetadata
 * @return payload image
 * @throws IOException
 */
protected RestoredFile restorePayload(File encapsulatedImage, Properties restorationMetadata)
        throws IOException {
    BufferedImage encapsulatedImageBuffered = ImageIO.read(encapsulatedImage);
    int payloadWidth = Integer.parseInt(restorationMetadata.getProperty("payloadWidth"));
    int payloadHeight = Integer.parseInt(restorationMetadata.getProperty("payloadHeight"));
    int carrierHeight = Integer.parseInt(restorationMetadata.getProperty("carrierHeight"));
    BufferedImage payloadBuffered = encapsulatedImageBuffered.getSubimage(0, carrierHeight, payloadWidth,
            payloadHeight);
    RestoredFile payload = new RestoredFile(
            RESTORED_DIRECTORY + Paths.get(restorationMetadata.getProperty("payloadPath")).getFileName());
    writeImage(payload, payloadBuffered);
    payload.wasPayload = true;
    payload.wasCarrier = false;
    // The restored file attributes are not important here,
    // as this is not the real payload (which is embedded in this payload
    // holding image)
    return payload;
}

From source file:javafx1.JavaFX1.java

public Image bildLaden() {
        Image zwischenBild = null;

        try {/* ww  w .  ja  v  a  2s  . c  o  m*/
            File input = new File("D:/_piCam/bild.jpg");
            //FileInputStream bi = ImageIO.read(input);
            BufferedImage bi = ImageIO.read(input);

            byte[] data = ((DataBufferByte) bi.getRaster().getDataBuffer()).getData();
            Mat mat = new Mat(bi.getHeight(), bi.getWidth(), CvType.CV_8UC3);
            mat.put(0, 0, data);

            Mat bild = new Mat(bi.getHeight(), bi.getWidth(), CvType.CV_8UC1);
            Imgproc.cvtColor(mat, bild, Imgproc.COLOR_BGR2GRAY);

            byte[] data1 = new byte[bild.rows() * bild.cols() * (int) (bild.elemSize())];
            bild.get(0, 0, data1);
            BufferedImage image1 = new BufferedImage(bild.cols(), bild.rows(), BufferedImage.TYPE_BYTE_GRAY);
            image1.getRaster().setDataElements(0, 0, bild.cols(), bild.rows(), data1);

            File ouptut = new File("D:/xml/grayscale2.jpg");
            //ImageIO.write(image1, "jpg", ouptut);
            BufferedImage gray = image1.getSubimage(0, 0, image1.getTileWidth(), image1.getHeight());
            zwischenBild = SwingFXUtils.toFXImage(gray, null);

        } catch (IOException ex) {
            System.out.println("Fehler beim Bild laden...");
        }
        return zwischenBild;
    }

From source file:edu.harvard.mcz.imagecapture.VerbatimCaptureDialog.java

protected void setValues() {
    lblBarcode.setText(specimen.getBarcode());
    lblCurrentid.setText(specimen.assembleScientificName());

    textFieldVerbLocality.setText(specimen.getVerbatimLocality());
    textFieldVerbDate.setText(specimen.getDateNos());
    textFieldVerbCollector.setText(specimen.getVerbatimCollector());
    textFieldVerbCollection.setText(specimen.getVerbatimCollection());
    textFieldVerbNumbers.setText(specimen.getVerbatimNumbers());
    textFieldVerbUnclassifiedText.setText(specimen.getVerbatimUnclassifiedText());

    comboBoxWorkflowStatus.setSelectedItem(specimen.getWorkFlowStatus());

    try {/*  w w w .ja v a2  s . c o m*/

        Iterator<ICImage> i = specimen.getICImages().iterator();
        ICImage image = null;
        boolean gotImg = false;
        while (i.hasNext() && !gotImg) {
            image = i.next();
            gotImg = true;
        }

        String path = image.getPath();
        if (path == null) {
            path = "";
        }
        File anImageFile = new File(ImageCaptureProperties.assemblePathWithBase(path, image.getFilename()));

        PositionTemplate defaultTemplate = PositionTemplate.findTemplateForImage(image);
        BufferedImage imagefile = ImageIO.read(anImageFile);
        int x = defaultTemplate.getLabelPosition().width;
        int y = defaultTemplate.getLabelPosition().height;
        int w = defaultTemplate.getLabelSize().width;
        int h = defaultTemplate.getLabelSize().height;
        setPinLabelImage(imagefile.getSubimage(x, y, w, h));
        fitPinLabels();
    } catch (ImageLoadException e) {
        log.error(e.getMessage(), e);
        System.out.println(e.getMessage());
    } catch (IOException e) {
        log.error(e.getMessage(), e);
        System.out.println(e.getMessage());
    }

    if (specimenControler != null) {
        btnNext.setEnabled(specimenControler.hasNextSpecimenInTable());
        btnPrevious.setEnabled(specimenControler.hasPreviousSpecimenInTable());
    } else {
        btnNext.setEnabled(false);
        btnPrevious.setEnabled(false);
    }

}

From source file:Implement.Service.TripperServiceImpl.java

@Override
public String cropAndSaveProviderImage(String data, int providerID, FileMeta imageMeta) throws IOException {
    JsonObject jsonObject = gson.fromJson(data, JsonObject.class);
    // get data from json
    int positionX = jsonObject.get("positionX").getAsInt();
    int positionY = jsonObject.get("positionY").getAsInt();
    int imageWidth = jsonObject.get("width").getAsInt();
    int imageHeight = jsonObject.get("height").getAsInt();
    int cropWidth = jsonObject.get("cropWidth").getAsInt();
    int cropHeight = jsonObject.get("cropHeight").getAsInt();

    // transform crop into current crop
    byte[] imageInByte = imageMeta.getBytes();
    InputStream in = new ByteArrayInputStream(imageInByte);
    BufferedImage bImageFromConvert = ImageIO.read(in);
    int currentImageWidth = bImageFromConvert.getWidth();
    int currentImageHeight = bImageFromConvert.getHeight();
    int newPositionX = currentImageWidth * positionX / imageWidth;
    int newPositionY = currentImageHeight * positionY / imageHeight;
    int widthRatio = currentImageWidth * cropWidth / imageWidth;
    int heightRatio = currentImageHeight * cropHeight / imageHeight;

    // then crop//  w w w . ja va  2s.co m
    BufferedImage croppedImage = bImageFromConvert.getSubimage(newPositionX, newPositionY, widthRatio,
            heightRatio);

    // get name to save
    String extension = FilenameUtils.getExtension(imageMeta.getFileName());
    String name = "tripper." + extension;

    String path = System.getProperty("catalina.base");
    File folderPackage = new File(path + "/webapps/Images/Tripper/" + providerID);
    if (!folderPackage.exists()) {
        folderPackage.mkdirs();
    }
    ImageIO.write(croppedImage, extension, new File(folderPackage, name));

    String image = "Images/Tripper/" + providerID + "/" + name;
    tripperDAO.updateTripperImage(providerID, image);
    return image;
}

From source file:web.diva.server.model.SomClustering.SomClustImgGenerator.java

public SplitedImg splitImage(BufferedImage img) {
    int imgHeight1 = (img.getHeight() / 4);

    BufferedImage bf1 = img.getSubimage(0, 0, img.getWidth(), imgHeight1);
    String str1 = this.generateEncodedImg(bf1);

    //     int imgHeight2 = img.getHeight()-imgHeight1;
    BufferedImage bf2 = img.getSubimage(0, imgHeight1, img.getWidth(), imgHeight1);
    String str2 = this.generateEncodedImg(bf2);

    BufferedImage bf3 = img.getSubimage(0, (2 * imgHeight1), img.getWidth(), imgHeight1);
    String str3 = this.generateEncodedImg(bf3);

    int imgHeight2 = img.getHeight() - (3 * imgHeight1);

    BufferedImage bf4 = img.getSubimage(0, (3 * imgHeight1), img.getWidth(), imgHeight2);
    String str4 = this.generateEncodedImg(bf4);

    SplitedImg si = new SplitedImg();
    si.setHeightFirst(imgHeight1);/*  w  w  w  .  j  av a 2 s  . co  m*/
    si.setHeightLast(imgHeight2);

    si.setImg1Url(str1);
    si.setImg2Url(str2);
    si.setImg3Url(str3);
    si.setImg4Url(str4);

    return si;

}

From source file:distribuidos.MyThread.java

private void difuminarTrozo(int x, int y, int w, int h) {
    preSC();/*from  www  .j a  va 2  s . c om*/
    BufferedImage original = null;
    BufferedImage nueva = null;
    try {
        original = ImageIO.read(new File(imagepath));
        nueva = ImageIO.read(new File(newimagepath));
    } catch (IOException ex) {
        Logger.getLogger(MyThread.class.getName()).log(Level.SEVERE, null, ex);
    }
    BufferedImage copia = new BufferedImage(original.getWidth(), original.getHeight(), TYPE_BYTE_INDEXED);
    float[] floats = { 0, 0.125f, 0, 0.125f, 0.5f, 0.125f, 0, 0.125f, 0, };
    BufferedImageOp op = new ConvolveOp(new Kernel(3, 3, floats));
    op.filter(original, copia);

    copia = copia.getSubimage(x, y, w, h);
    Graphics2D g2d = nueva.createGraphics();
    g2d.drawImage(copia, x, y, null);
    //g2d.drawImage(copia, x, y, w, h, null);
    File output = new File(newimagepath);
    try {
        ImageIO.write(nueva, "png", output);
    } catch (IOException ex) {
        Logger.getLogger(MyThread.class.getName()).log(Level.SEVERE, null, ex);
    }
    postSC();
}