Example usage for javax.imageio ImageIO read

List of usage examples for javax.imageio ImageIO read

Introduction

In this page you can find the example usage for javax.imageio ImageIO read.

Prototype

public static BufferedImage read(ImageInputStream stream) throws IOException 

Source Link

Document

Returns a BufferedImage as the result of decoding a supplied ImageInputStream with an ImageReader chosen automatically from among those currently registered.

Usage

From source file:com.shending.support.CompressPic.java

public String compressPic() {
    try {//  w  ww  . ja v  a 2s .co  m
        // ?
        file = new File(inputDir);
        //System.out.println(inputDir + inputFileName);
        if (!file.exists()) {
            //throw new Exception("?");
        }
        Image img = ImageIO.read(file);
        // ??
        if (img.getWidth(null) == -1) {
            System.out.println(" can't read,retry!" + "<BR>");
            return "no";
        } else {
            int newWidth;
            int newHeight;
            // ?
            if (this.proportion == true) {
                // ?
                double rate1 = ((double) img.getWidth(null)) / (double) outputWidth + 0.1;
                double rate2 = ((double) img.getHeight(null)) / (double) outputHeight + 0.1;
                // ?
                double rate = rate1 > rate2 ? rate1 : rate2;
                newWidth = (int) (((double) img.getWidth(null)) / rate);
                newHeight = (int) (((double) img.getHeight(null)) / rate);
            } else {
                newWidth = outputWidth; // 
                newHeight = outputHeight; // 
            }
            BufferedImage tag = new BufferedImage((int) newWidth, (int) newHeight, BufferedImage.TYPE_INT_RGB);

            /*
             * Image.SCALE_SMOOTH  ?  ?? 
             */
            tag.getGraphics().drawImage(img.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH), 0, 0,
                    null);
            File f = new File(outputDir);
            if (!f.exists()) {
                f.mkdirs();
            }
            FileOutputStream out = new FileOutputStream(outputDir + outputFileName);
            // JPEGImageEncoder??
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
            encoder.encode(tag);
            out.close();
        }
    } catch (IOException ex) {
        ex.printStackTrace();
    }
    return "ok";
}

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

protected String detectTemplateForImage(File anImageFile, CandidateImageFile scannableFile, boolean quickCheck)
        throws UnreadableFileException {
    // Set default response if no template is found.
    String result = PositionTemplate.TEMPLATE_NO_COMPONENT_PARTS;

    // Read the image file, if possible, otherwise throw exception.
    if (!anImageFile.canRead()) {
        throw new UnreadableFileException("Unable to read " + anImageFile.getName());
    }//www.  ja va2s.  c  o m

    BufferedImage image = null;
    try {
        image = ImageIO.read(anImageFile);
    } catch (IOException e) {
        throw new UnreadableFileException("IOException trying to read " + anImageFile.getName());
    }

    // iterate through templates and check until the first template where a barcode is found
    List<String> templates = PositionTemplate.getTemplateIds();
    ListIterator<String> i = templates.listIterator();
    boolean found = false;
    while (i.hasNext() && !found) {
        try {
            // get the next template from the list
            PositionTemplate template = new PositionTemplate((String) i.next());
            log.debug("Testing template: " + template.getTemplateId());
            if (template.getTemplateId().equals(PositionTemplate.TEMPLATE_NO_COMPONENT_PARTS)) {
                // skip, this is the default result if no other is found.
            } else {
                if (image.getWidth() == template.getImageSize().getWidth()) {
                    // Check to see if the barcode is in the part of the template
                    // defined by getBarcodeULPosition and getBarcodeSize.
                    String text;
                    if (scannableFile == null) {
                        text = CandidateImageFile.getBarcodeTextFromImage(image, template, quickCheck);
                    } else {
                        text = scannableFile.getBarcodeText(template);
                    }
                    log.debug("Found:[" + text + "] ");
                    if (text.length() > 0) {
                        // a barcode was scanned 
                        // Check to see if it matches the expected pattern.
                        // Use the configured barcode matcher.
                        if (Singleton.getSingletonInstance().getBarcodeMatcher().matchesPattern(text)) {
                            found = true;
                            log.debug("Match to:" + template.getTemplateId());
                            result = template.getTemplateId();
                        }
                    }
                } else {
                    log.debug("Skipping as template " + template.getTemplateId()
                            + " is not same size as image. ");
                }
            }
        } catch (NoSuchTemplateException e) {
            // Ending up here means a serious error in PositionTemplate
            // as the list of position templates returned by getTemplates() includes
            // an entry that isn't recognized as a valid template.  
            log.fatal(
                    "Fatal error.  PositionTemplate.getTemplates() includes an item that isn't a valid template.");
            log.trace(e);
            ImageCaptureApp.exit(ImageCaptureApp.EXIT_ERROR);
        }
    }
    return result;
}

From source file:ImageSorter.java

private void nextImage() {
    index++;/*  w  w  w. j a va2s. c om*/

    if (index >= inputs.length) {
        System.exit(0);
    }

    try {
        panel.image = ImageIO.read(inputs[index]);
        panel.repaint();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:net.malisis.ddb.DDBIcon.java

@Override
public boolean load(IResourceManager manager, ResourceLocation location) {
    // get mipmapping level
    int mipmapLevels = Minecraft.getMinecraft().gameSettings.mipmapLevels;
    boolean anisotropic = Minecraft.getMinecraft().gameSettings.anisotropicFiltering > 1.0F;

    try {//from  w  w w .java2 s .  co m
        InputStream stream = pack.getInputStream(path + ".png");
        if (stream == null) {
            DDB.log.error("Using missing texture, file not found : " + getIconName());
            return true;
        }

        BufferedImage[] textures = new BufferedImage[1 + mipmapLevels];
        textures[0] = ImageIO.read(stream);

        AnimationMetadataSection animMetadata = readAnimation();

        loadSprite(textures, animMetadata, anisotropic);
        return false;
    } catch (IOException e) {
        DDB.log.error("Using missing texture, unable to load " + getIconName(), e.getMessage());
        return true;
    }
}

From source file:eu.europa.esig.dss.pades.signature.visible.ImageFactory.java

public static InputStream create(final SignatureImageParameters imageParameters) throws IOException {

    SignatureImageTextParameters textParamaters = imageParameters.getTextParameters();

    if ((textParamaters != null) && StringUtils.isNotEmpty(textParamaters.getText())) {

        BufferedImage buffImg = ImageTextWriter.createTextImage(textParamaters.getText(),
                textParamaters.getFont(), textParamaters.getTextColor(), textParamaters.getBackgroundColor(),
                DPI);//ww w  .jav  a  2 s  . co m

        if (imageParameters.getImage() != null) {
            switch (textParamaters.getSignerNamePosition()) {
            case LEFT:
                buffImg = ImagesMerger.mergeOnRight(ImageIO.read(imageParameters.getImage()), buffImg,
                        textParamaters.getBackgroundColor());
                break;
            case RIGHT:
                buffImg = ImagesMerger.mergeOnRight(buffImg, ImageIO.read(imageParameters.getImage()),
                        textParamaters.getBackgroundColor());
                break;
            case TOP:
                buffImg = ImagesMerger.mergeOnTop(ImageIO.read(imageParameters.getImage()), buffImg,
                        textParamaters.getBackgroundColor());
                break;
            case BOTTOM:
                buffImg = ImagesMerger.mergeOnTop(buffImg, ImageIO.read(imageParameters.getImage()),
                        textParamaters.getBackgroundColor());
                break;
            default:
                break;
            }
        }
        return convertToInputStream(buffImg, DPI);
    } else {
        return new FileInputStream(imageParameters.getImage());
    }
}

From source file:WeatherWizard.java

private BufferedImage loadImage(String name) {
    String imgFileName = "images/weather-" + name + ".png";
    URL url = WeatherWizard.class.getResource(imgFileName);
    BufferedImage img = null;//from w  w  w . java2s. c o m
    try {
        img = ImageIO.read(url);
    } catch (Exception e) {
    }
    return img;
}

From source file:fr.mby.opa.picsimpl.service.BasicPictureService.java

@Override
public BinaryImage generateThumbnail(final Picture picture, final int width, final int height,
        final boolean keepScale, final String format) throws IOException {

    final BufferedImage originalImage = ImageIO.read(new ByteArrayInputStream(picture.getImage().getData()));

    return this.pictureFactory.buildThumbnail(originalImage, picture.getFilename(), width, height, format);
}

From source file:org.mcplissken.repository.models.content.Content.java

public void writeAsImage(File result) throws IOException {

    BufferedImage originalImage = ImageIO.read(result);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    ImageIO.write(originalImage, getExtension(), baos);

    baos.flush();//w w w  .j a v a  2 s .  co m

    byte[] imageInByte = baos.toByteArray();

    data = ByteBuffer.wrap(imageInByte);

    baos.close();
}

From source file:com.t3.image.ThumbnailManager.java

private BufferedImage getCachedThumbnail(File file) {

    File thumbnailFile = getThumbnailFile(file);

    if (!thumbnailFile.exists()) {
        return null;
    }// w  w w . ja va 2 s  .  com

    try {
        // Check that it hasn't changed on disk
        if (file.lastModified() > thumbnailFile.lastModified()) {
            return null;
        }

        // Get the thumbnail
        BufferedImage thumbnail = ImageIO.read(thumbnailFile);

        // Check that we have the size we want
        if (thumbnail.getWidth() != thumbnailSize.width && thumbnail.getHeight() != thumbnailSize.height) {
            return null;
        }

        return thumbnail;
    } catch (IOException ioe) {
        return null;
    }
}

From source file:com.igormaznitsa.sciareto.ui.editors.PictureViewer.java

@Override
public void loadContent(@Nullable final File file) throws IOException {
    BufferedImage loaded = null;//  ww w  .j  av  a 2s  .c o m
    if (file != null) {
        try {
            loaded = ImageIO.read(file);
        } catch (Exception ex) {
            LOGGER.error("Can't load image", ex);
            loaded = null;
        }
    }

    this.image = loaded;

    this.label.setHorizontalTextPosition(JLabel.CENTER);
    this.label.setVerticalTextPosition(JLabel.CENTER);
    this.label.setHorizontalAlignment(SwingConstants.CENTER);
    this.label.setVerticalAlignment(SwingConstants.CENTER);

    if (this.image == null) {
        this.label.setIcon(null);
        this.label.setText("Can't load image");
    } else {
        this.label.setIcon(new ImageIcon(this.image));
        this.label.setText("");
    }

    this.setViewportView(this.label);
    this.revalidate();
}