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.loy.MainFrame.java

@SuppressWarnings("rawtypes")
public void init() {

    String src = "ee.png";
    try {//  w  ww.  j  a  v a2  s  .  c  o  m
        ClassPathResource classPathResource = new ClassPathResource(src);
        image = ImageIO.read(classPathResource.getURL());
        this.setIconImage(image);
    } catch (IOException e) {
    }

    menu = new JMenu("LOG CONSOLE");
    this.jmenuBar = new JMenuBar();
    this.jmenuBar.add(menu);

    panel = new JPanel(new BorderLayout());
    this.add(panel);

    ClassPathResource classPathResource = new ClassPathResource("application.yml");
    Yaml yaml = new Yaml();
    Map result = null;
    try {
        result = (Map) yaml.load(classPathResource.getInputStream());
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    String platformStr = result.get("platform").toString();
    String version = result.get("version").toString();
    String jvmOption = result.get("jvmOption").toString();
    @SuppressWarnings("unchecked")
    List<String> projects = (List<String>) result.get("projects");
    platform = Platform.valueOf(platformStr);
    final Runtime runtime = Runtime.getRuntime();
    File pidsForder = new File("./pids");
    if (!pidsForder.exists()) {
        pidsForder.mkdir();
    } else {
        File[] files = pidsForder.listFiles();
        if (files != null) {
            for (File f : files) {
                f.deleteOnExit();
                String pidStr = f.getName();
                try {
                    Long pid = new Long(pidStr);
                    if (Processes.isProcessRunning(platform, pid)) {
                        if (Platform.Windows == platform) {
                            Processes.tryKillProcess(null, platform, new NullProcessor(), pid);
                        } else {
                            Processes.killProcess(null, platform, new NullProcessor(), pid);
                        }

                    }
                } catch (Exception ex) {
                }
            }
        }
    }

    File currentForder = new File("");
    String rootPath = currentForder.getAbsolutePath();
    rootPath = rootPath.replace(File.separator + "build" + File.separator + "libs", "");
    rootPath = rootPath.replace(File.separator + "e-example-ms-start-w", "");

    for (String value : projects) {
        String path = value;
        String[] values = value.split("/");
        value = values[values.length - 1];
        String appName = value;
        value = rootPath + "/" + path + "/build/libs/" + value + "-" + version + ".jar";

        JMenuItem menuItem = new JMenuItem(appName);
        JTextArea textArea = new JTextArea();
        textArea.setVisible(true);
        textArea.setLineWrap(true);
        textArea.setWrapStyleWord(true);
        textArea.setAutoscrolls(true);
        JScrollPane scorll = new JScrollPane(textArea);
        this.textSreaMap.put(appName, scorll);
        EComposite ecomposite = new EComposite();
        ecomposite.setCommand(value);
        ecomposite.setTextArea(textArea);
        composites.put(appName, ecomposite);
        menuItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                Collection<JScrollPane> values = textSreaMap.values();
                for (JScrollPane t : values) {
                    t.setVisible(false);
                }
                String actions = e.getActionCommand();
                JScrollPane textArea = textSreaMap.get(actions);
                if (textArea != null) {
                    textArea.setVisible(true);
                    panel.removeAll();
                    panel.add(textArea);
                    panel.repaint();
                    panel.validate();
                    self.repaint();
                    self.validate();
                }
            }
        });
        menu.add(menuItem);
    }

    new Thread(new Runnable() {
        @Override
        public void run() {
            int size = composites.keySet().size();
            int index = 1;
            for (String appName : composites.keySet()) {
                EComposite composite = composites.get(appName);
                try {

                    Process process = runtime.exec(
                            "java " + jvmOption + " -Dfile.encoding=UTF-8 -jar " + composite.getCommand());
                    Long pid = Processes.processId(process);
                    pids.add(pid);
                    File pidsFile = new File("./pids", pid.toString());
                    pidsFile.createNewFile();

                    new WriteLogThread(process.getInputStream(), composite.getTextArea()).start();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                synchronized (lock) {
                    try {
                        if (index < size) {
                            lock.wait();
                        } else {
                            index++;
                        }

                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }).start();

}

From source file:org.shredzone.cilla.service.resource.ImageTools.java

/**
 * Analyzes the dimension of the given image {@link DataSource}.
 *
 * @param src//from w  w w. j a  v  a2 s .  c om
 *            {@link DataSource} to analyze
 * @return image dimensions
 */
public Dimension analyzeDimension(DataSource src) throws CillaServiceException {
    try {
        BufferedImage image = ImageIO.read(src.getInputStream());
        return (image != null ? new Dimension(image.getWidth(), image.getHeight()) : null);
    } catch (IOException ex) {
        throw new CillaServiceException(ex);
    }
}

From source file:com.tomtom.speedtools.json.ImageSerializer.java

@Nullable
private static BufferedImage readFromBytes(@Nonnull final byte[] bytes) throws IOException {
    assert bytes != null;
    try (InputStream is = new ByteArrayInputStream(bytes)) {
        return ImageIO.read(is);
    }/*w ww. j  a  va 2s . c  o m*/
}

From source file:no.dusken.aranea.service.StoreImageServiceImpl.java

public Image changeImage(File file, Image image) throws IOException {

    String hash = MD5.asHex(MD5.getHash(file));

    if (isBlank(hash)) {
        throw new IOException("Could not get hash from " + file.getAbsolutePath());
    }/*w w w .  j  a  v  a 2s. c  o m*/

    Image existingImage = imageService.getImageByHash(hash);
    if (existingImage != null) {
        log.info("Imported existing Image: {} from the user", existingImage.toString());
        file.delete();
        return existingImage;
    } else {
        image.setHash(hash);

        BufferedImage rendImage = ImageIO.read(file);
        image.setHeight(rendImage.getHeight());
        image.setWidth(rendImage.getWidth());
        image.setFileSize(file.length());
        FileUtils.copyFile(file, new File(imageDirectory + "/" + image.getUrl()));

        file.delete();
        log.debug("Imported Image: {} from {}", image.toString(), file.getAbsolutePath());

        return imageService.saveOrUpdate(image);
    }
}

From source file:eu.flatworld.worldexplorer.layer.bmng.BMNGHTTPProvider.java

@Override
public void run() {
    while (true) {
        while (getQueueSize() != 0) {
            Tile tile = peekTile();/*w w  w . ja va 2  s .c o  m*/
            synchronized (tile) {
                String s = String.format(BMNGLayer.HTTP_BASE, year, month, tile.getL(), tile.getX(),
                        tile.getY());
                LogX.log(Level.FINER, s);
                GetMethod gm = new GetMethod(s);
                gm.setRequestHeader("User-Agent", WorldExplorer.USER_AGENT);
                try {
                    int response = client.executeMethod(gm);
                    LogX.log(Level.FINEST, NAME + " " + response + " " + s);
                    if (response == HttpStatus.SC_OK) {
                        InputStream is = gm.getResponseBodyAsStream();
                        BufferedImage bi = ImageIO.read(is);
                        is.close();
                        if (bi != null) {
                            tile.setImage(bi);
                        }
                    }
                } catch (Exception ex) {
                    LogX.log(Level.FINER, "", ex);
                } finally {
                    gm.releaseConnection();
                }
                LogX.log(Level.FINEST, NAME + " dequeueing: " + tile);
                unqueueTile(tile);
            }
            firePropertyChange(P_DATAREADY, null, tile);
            Thread.yield();
        }
        firePropertyChange(P_IDLE, false, true);
        try {
            Thread.sleep(QUEUE_SLEEP_TIME);
        } catch (Exception ex) {
        }
        ;
    }
}

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

public void initCropImage(Product product, Map<String, String> moduleConfigMap) throws Exception {

    Configuration conf = PropertiesUtil.getConfiguration();
    //String folder = conf.getString("core.product.image.filefolder") 
    String folder = FileUtil.getProductFilePath() + "/" + product.getMerchantId() + "/";
    File image = new File(folder + product.getProductImage());

    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();

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

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

    determineCropArea(width, largeImageWidth, height, largeImageHeight);
}

From source file:edu.emory.library.tast.images.ThumbnailServlet.java

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    // location of images
    String baseUrl = AppConfig.getConfiguration().getString(AppConfig.IMAGES_URL);
    baseUrl = StringUtils.trimEnd(baseUrl, '/');

    // image name and size
    String imageFileName = request.getParameter("i");
    int thumbnailWidth = Integer.parseInt(request.getParameter("w"));
    int thumbnailHeight = Integer.parseInt(request.getParameter("h"));

    // image dir/* w  w  w  . j  a  v a 2  s  . com*/
    String imagesDir = AppConfig.getConfiguration().getString(AppConfig.IMAGES_DIRECTORY);

    // create the thumbnail name
    String thumbnailFileName = FilenameUtils.getBaseName(imageFileName) + "-" + thumbnailWidth + "x"
            + thumbnailHeight + ".png";

    // does it exist?
    File thumbnailFile = new File(imagesDir, thumbnailFileName);
    if (thumbnailFile.exists()) {
        response.sendRedirect(baseUrl + "/" + thumbnailFileName);
        return;
    }

    // read the image
    File imageFile = new File(imagesDir, imageFileName);
    BufferedImage image = ImageIO.read(imageFile);
    int imageWidth = image.getWidth();
    int imageHeight = image.getHeight();
    BufferedImage imageCopy = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_RGB);
    imageCopy.getGraphics().drawImage(image, 0, 0, imageWidth, imageHeight, 0, 0, imageWidth, imageHeight,
            null);

    // height is calculated automatically
    if (thumbnailHeight == 0)
        thumbnailHeight = (int) ((double) thumbnailWidth / (double) imageWidth * (double) imageHeight);

    // width is calculated automatically
    if (thumbnailWidth == 0)
        thumbnailWidth = (int) ((double) thumbnailHeight / (double) imageHeight * (double) imageWidth);

    // create an empty thumbnail
    BufferedImage thumbnail = new BufferedImage(thumbnailWidth, thumbnailHeight, BufferedImage.TYPE_INT_RGB);
    Graphics2D gr = thumbnail.createGraphics();
    gr.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
    gr.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);

    // determine the piece of the image which we want to clip
    int clipX1, clipX2, clipY1, clipY2;
    if (imageWidth * thumbnailHeight > thumbnailWidth * imageHeight) {

        int clipWidth = (int) Math
                .round(((double) thumbnailWidth / (double) thumbnailHeight) * (double) imageHeight);
        int imgCenterX = imageWidth / 2;
        clipX1 = imgCenterX - clipWidth / 2;
        clipX2 = imgCenterX + clipWidth / 2;
        clipY1 = 0;
        clipY2 = imageHeight;
    } else {
        int clipHeight = (int) Math
                .round(((double) thumbnailHeight / (double) thumbnailWidth) * (double) imageWidth);
        int imgCenterY = imageHeight / 2;
        clipX1 = 0;
        clipX2 = imageWidth;
        clipY1 = imgCenterY - clipHeight / 2;
        clipY2 = imgCenterY + clipHeight / 2;
    }

    // we filter the image first to get better results when shrinking
    if (2 * thumbnailWidth < clipX2 - clipX1 || 2 * thumbnailHeight < clipY2 - clipY1) {

        int kernelDimX = (clipX2 - clipX1) / (thumbnailWidth);
        int kernelDimY = (clipY2 - clipY1) / (thumbnailHeight);

        if (kernelDimX % 2 == 0)
            kernelDimX++;
        if (kernelDimY % 2 == 0)
            kernelDimY++;

        if (kernelDimX < kernelDimY)
            kernelDimX = kernelDimY;
        if (kernelDimY < kernelDimX)
            kernelDimY = kernelDimX;

        float[] blurKernel = new float[kernelDimX * kernelDimY];
        for (int i = 0; i < kernelDimX; i++)
            for (int j = 0; j < kernelDimY; j++)
                blurKernel[i * kernelDimX + j] = 1.0f / (float) (kernelDimX * kernelDimY);

        BufferedImageOp op = new ConvolveOp(new Kernel(kernelDimX, kernelDimY, blurKernel));
        imageCopy = op.filter(imageCopy, null);

    }

    // draw the thumbnail
    gr.drawImage(imageCopy, 0, 0, thumbnailWidth, thumbnailHeight, clipX1, clipY1, clipX2, clipY2, null);

    // and we are done
    gr.dispose();
    ImageIO.write(thumbnail, "png", thumbnailFile);

    // redirect to it
    response.sendRedirect(baseUrl + "/" + thumbnailFileName);

}

From source file:net.malisis.advert.advert.ClientAdvert.java

public void setTexture(byte[] data, long size) {
    try {//from  w w w.  j a  v  a2  s. c o m
        BufferedImage image = ImageIO.read(new ByteArrayInputStream(data));
        if (image == null) {
            setError("Could not read image.");
            return;
        }

        writeFile(data);
        texture = new GuiTexture(image, name);
        this.size = size;
        this.width = image.getWidth();
        this.height = image.getHeight();
    } catch (IOException e) {
        MalisisAdvert.log.error("Could not set the texture for {}", this, e);
        setError("Could not read image.");
    }
}

From source file:com.cisco.surf.jenkins.plugins.jenkow.tests.DiagramGeneration.DiagramTest.java

private void testImage(String path, String suffix) throws IOException {
    URL url = new URL(new WebClient().getContextPath() + path);
    System.out.println("url=" + url);

    BufferedImage img = ImageIO.read(url);
    File pf = new File("target/test-artifacts/" + getTestName() + "-" + suffix + ".png");
    pf.getParentFile().mkdirs();//  w  w w .  j  a v a2s.c o m
    ImageIO.write(img, "png", pf);

    // TODO 5: maybe I can find a more robust way to diff the images
    // Different platforms produce slightly different PNGs
    // So for now I'm just comparing the geometries :-(
    BufferedImage ref = ImageIO.read(new File(getResource("ref.png")));
    assertEquals("wrong geometry", getGeo(ref), getGeo(img));
    //        FileAssert.assertBinaryEquals("generated diagram file discrepancy: ",new File(getResource("ref.png")),pf);
}

From source file:com.liud.dailynote.ThumbnailatorTest.java

public void testYS6() throws IOException {
    String result = "src/main/resources/images/";
    // watermark ? 1.? 2.? 3.?
    Thumbnails.of(result + "sijili.jpg").scale(1.0f)
            .watermark(Positions.CENTER, ImageIO.read(new File(result + "warter.jpg")), 0.25f)
            .toFile(result + "image_warter.jpg");
}