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:edu.harvard.mcz.imagecapture.TemplatePickerDialog.java

protected void init(ICImage image) {
    setBounds(100, 100, 450, 300);//  www .  j  a va2 s  .  c om
    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:be.ehb.restservermetdatabase.webservice.AchievementController.java

public String getImg(String url) {
    BufferedImage img = null;//w  w  w.j a v a  2s.  co  m
    File f = null;
    try {
        f = new File(url);
    } catch (NullPointerException e) {
        f = new File("unnamed.png");
    }
    try {
        img = ImageIO.read(f);
    } catch (IOException e) {
    }
    String imageString = null;
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    try {
        ImageIO.write(img, "png", bos);
        byte[] imageBytes = bos.toByteArray();
        imageString = new sun.misc.BASE64Encoder().encode(imageBytes);
        bos.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return imageString;
}

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

/**
 * This method initializes this// ww  w  .j av a  2s .c om
 * 
 */
private void initialize() {
    this.setSize(new Dimension(553, 323));
    this.setLayout(new BorderLayout());
    this.add(getJPanel(), BorderLayout.NORTH);
    this.add(getJScrollPane(), BorderLayout.CENTER);
    URL cursorFile = this.getClass()
            .getResource("/edu/harvard/mcz/imagecapture/resources/magnifying_glass.gif");
    try {
        log.debug(cursorFile.toString());
        Image zoomCursorImage = ImageIO.read(cursorFile);
        Point hotPoint = new Point(5, 5);
        zoomCursor = Toolkit.getDefaultToolkit().createCustomCursor(zoomCursorImage, hotPoint, "ZoomCursor");
    } catch (IOException e) {
        log.error("Unable to load ZoomCursor");
        zoomCursor = null;
    }
    jLabel.addMouseListener(this);

}

From source file:com.salesmanager.core.util.ProductImageUtil.java

public void uploadProductImages(File image, String imageName, String imageContentType, Product product,
        Map<String, String> moduleConfigMap) throws Exception {
    FileModule fh = (FileModule) SpringUtil.getBean("localfile");
    Configuration conf = PropertiesUtil.getConfiguration();
    Map<String, String> defaultConfigMap = getDefaultConfigMap();
    // Save the Large Image
    // get specifications
    int largeImageHeight = getValue("largeimageheight", moduleConfigMap, defaultConfigMap);
    int largeImageWidth = getValue("largeimagewidth", moduleConfigMap, defaultConfigMap);

    /** Original Image **/
    // get original image size
    BufferedImage originalImage = ImageIO.read(image);
    int width = originalImage.getWidth();
    int height = originalImage.getHeight();

    // original image
    StringBuffer imgName = new StringBuffer();
    imgName.append(product.getProductId()).append("-").append(imageName);
    // store renamed image in products_image column
    product.setProductImage(imgName.toString());

    // upload anyway
    fh.uploadFile(product.getMerchantId(), "core.product.image", image, imgName.toString(), imageContentType);

    /*** determine if image can be cropped ***/
    determineCropeable(width, largeImageWidth, height, largeImageHeight);

    product.setProductImageCrop(this.isCropeable());

    /*** determine crop area calculation baseline ***/
    this.determineBaseline(width, height);

    // Save the small Image
    int smallImageHeight = getValue("smallimageheight", moduleConfigMap, defaultConfigMap);
    int smallImageWidth = getValue("smallimagewidth", moduleConfigMap, defaultConfigMap);
    File resizedSmallImage = resizeImage(originalImage, smallImageWidth, smallImageHeight);
    StringBuffer smallImgName = new StringBuffer();
    smallImgName.append(conf.getString("core.product.image.small.prefix")).append("-")
            .append(imgName.toString());
    fh.uploadFile(product.getMerchantId(), "core.product.image", resizedSmallImage, smallImgName.toString(),
            imageContentType);//from   w  w w .  j ava  2  s . co  m
    resizedSmallImage.delete();

    // Save large Image
    int listingImageHeight = getValue("largeimageheight", moduleConfigMap, defaultConfigMap);
    int listingImageWidth = getValue("largeimagewidth", moduleConfigMap, defaultConfigMap);
    File resizedListingImage = resizeImage(originalImage, listingImageWidth, listingImageHeight);
    StringBuffer largeImgName = new StringBuffer();
    largeImgName.append(conf.getString("core.product.image.large.prefix")).append("-")
            .append(imgName.toString());

    fh.uploadFile(product.getMerchantId(), "core.product.image", resizedListingImage, largeImgName.toString(),
            imageContentType);
    resizedListingImage.delete();

    determineCropArea(width, largeImageWidth, height, largeImageHeight);

}

From source file:emily.command.fun.RedditCommand.java

@Override
public String execute(DiscordBot bot, String[] args, MessageChannel channel, User author,
        Message inputMessage) {/*www.  j  a  v a  2 s  . c  o  m*/
    String subReddit = "funny";
    if (args.length > 0) {
        subReddit = args[0];
    }
    List<Post> dailyTop = RedditScraper.getDailyTop(subReddit);
    if (dailyTop.size() == 0) {
        return Templates.command.reddit_sub_not_found.formatGuild(channel);
    }
    Random rng = new Random();
    Post post;
    do {
        int index = rng.nextInt(dailyTop.size());
        post = dailyTop.remove(index);
        if (post.data.is_self) {
            break;
        }
        if (whitelistedDomains.contains(post.data.domain)) {
            break;
        }
    } while (dailyTop.size() > 0);
    if (post.data.is_self) {
        return ":newspaper:\n" + post.data.getTitle() + "\n" + post.data.getSelftext();
    }
    if (post.data.url != null && post.data.url.length() > 20) {
        return post.data.title + "\n" + post.data.url;
    }
    ImagePreview preview = post.data.getPreview();
    if (preview != null && preview.images.size() > 0) {
        if (channel.getType().equals(ChannelType.TEXT) && !PermissionUtil.checkPermission((TextChannel) channel,
                ((TextChannel) channel).getGuild().getSelfMember(), Permission.MESSAGE_ATTACH_FILES)) {
            return Templates.permission_missing.formatGuild(channel, "MESSAGE_ATTACH_FILES");
        }
        for (Image image : preview.images) {
            try (InputStream in = new URL(StringEscapeUtils.unescapeHtml4(image.source.url)).openStream()) {
                File outputfile = new File("tmp_" + channel.getId() + ".jpg");
                ImageIO.write(ImageIO.read(in), "jpg", outputfile);
                bot.queue.add(
                        channel.sendFile(outputfile, new MessageBuilder().append(post.data.title).build()),
                        message -> outputfile.delete());
                return "";
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return Templates.command.reddit_nothing.formatGuild(channel);
}

From source file:org.jamwiki.utils.ImageUtil.java

/**
 * Given a file that corresponds to an existing image, return a
 * BufferedImage object./*from w  w  w.  jav  a  2  s.  com*/
 */
private static BufferedImage loadImage(File file) throws Exception {
    BufferedImage image = null;
    String key = file.getPath();
    Element cacheElement = WikiCache.retrieveFromCache(CACHE_IMAGES, key);
    if (cacheElement != null) {
        return (BufferedImage) cacheElement.getObjectValue();
    }
    FileInputStream fis = null;
    try {
        fis = new FileInputStream(file);
        image = ImageIO.read(fis);
        WikiCache.addToCache(CACHE_IMAGES, key, image);
        return image;
    } finally {
        if (fis != null) {
            try {
                fis.close();
            } catch (Exception e) {
            }
        }
    }
}

From source file:dotaSoundEditor.Helpers.PortraitFinder.java

private void buildAnnouncerPortraits(VPKArchive vpk) {

    BufferedImage image = null;// w w  w  . jav a  2 s  . c  o m
    for (VPKEntry entry : vpk.getEntriesForDir("resource/flash3/images/econ/announcer/")) {
        if (entry.getName().contains("large")) {
            continue; //don't grab the huge images, we won't use them.
        }

        File imageFile = new File(entry.getPath());

        try (FileChannel fc = FileUtils.openOutputStream(imageFile).getChannel()) {
            fc.write(entry.getData());
            image = ImageIO.read(imageFile);
            String announcer = entry.getName();
            portraitMap.put(announcer, image);
        } catch (IOException ex) {
            System.err.println("Can't write " + entry.getPath() + ": " + ex.getMessage());
        }
    }
}

From source file:com.orthancserver.OrthancConnection.java

public BufferedImage ReadImage(String uri) throws IOException {
    return ImageIO.read(OpenStream(uri));
}

From source file:com.opendesign.utils.ThumbnailManager.java

/**
 * ?? ?   //w w w. j  av a 2s. c o  m
 * ?  width ?  resize ?.
 * @param width
 * @param imageFile
 * @param suffix
 * @throws Exception
 */
private static void resizeNSaveThumbnail(double width, File imageFile, String suffix) throws Exception {

    BufferedImage originalImage = ImageIO.read(imageFile);
    double originalWidth = originalImage.getWidth();
    double originalHeight = originalImage.getHeight();

    double resizableWidth = originalWidth;
    double resizableHeight = originalHeight;

    String extension = imageFile.getName().substring(imageFile.getName().indexOf(".") + 1);
    String fileName = imageFile.getName().substring(0, imageFile.getName().indexOf("."));
    String target = imageFile.getAbsolutePath();
    target = target.substring(0, target.lastIndexOf(File.separator) + 1) + fileName + suffix + "." + extension;

    if (originalWidth > width) {
        resizableWidth = width;
        double ratio = (double) width / (double) originalImage.getWidth();
        resizableHeight = originalImage.getHeight() * ratio;

        Thumbnails.of(originalImage).size((int) resizableWidth, (int) resizableHeight).outputFormat(extension)
                .toFile(target);
    } else {
        CmnUtil.fileCopy(imageFile.getAbsolutePath(), target);
    }

}

From source file:com.alehuo.wepas2016projekti.service.InitService.java

/**
 * Pienent kuvan/*from   ww  w .  j  av a  2s .c  o m*/
 *
 * @param byteArray Kuvan data
 * @param type Kuvan tiedostotyyppi
 * @param widthHeight Leveys ja korkeus (Kuvat ovat nelin muotoisia)
 * @return Pienennetyn kuvan data
 */
public byte[] resizeImage(byte[] byteArray, String type, int widthHeight) {
    BufferedImage resized;
    try {
        resized = Scalr.resize(ImageIO.read(new ByteArrayInputStream(byteArray)), Scalr.Method.QUALITY,
                Scalr.Mode.FIT_TO_HEIGHT, widthHeight, widthHeight, Scalr.OP_ANTIALIAS);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(resized, type, baos);
        return baos.toByteArray();
    } catch (IOException ex) {
        return null;
    }
}