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:de.dakror.virtualhub.server.ServerFrame.java

public ServerFrame() {
    super("VirtualHub Server (" + UniVersion.prettyVersion() + ")");
    setSize(800, 600);//from www .  j a v a 2  s .c  o m
    setMinimumSize(new Dimension(800, 600));
    try {
        setIconImage(ImageIO.read(getClass().getResource("/img/icon.png")));
    } catch (IOException e) {
        e.printStackTrace();
    }

    init();

    setLocationRelativeTo(null);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setVisible(true);
}

From source file:com.actelion.research.orbit.imageAnalysis.utils.ImageUtils.java

/**
 * Converts image file into a BufferedImage
 *
 * @param inputFile/* w  w  w  .java 2s .  c  o m*/
 * @return
 * @throws IOException
 */
public static BufferedImage convertImageFileToBI(String inputFile) throws IOException {

    BufferedImage bi = null;

    try {
        ImageIO.setUseCache(false);
        bi = ImageIO.read(new File(inputFile));
    } catch (javax.imageio.IIOException e) // in case tiff format is not recognized, try to resolve exception using ImagePlus (ImageJ) methods
    {
        if (inputFile.endsWith(".tif") || inputFile.endsWith(".tiff")) {
            ImagePlus ip = new ImagePlus(inputFile); // :TODO validate if tiff to be read is truly 16 bit :: otherwise there could be a scaling issue occurring afterwards
            bi = ((ShortProcessor) ip.getProcessor().convertToShort(false)).get16BitBufferedImage();
        } else {
            throw e;
        }
    }

    return bi;
}

From source file:com.formkiq.core.util.Strings.java

/**
 * Converts Base64 String to byte[] image.
 * @param base64String {@link String}/*from ww w .j  a  v a  2 s  .c  o m*/
 * @return {@link Pair}
 * @throws IOException IOException
 */
public static Pair<byte[], String> base64StringToImg(final String base64String) throws IOException {

    int headerLen = BASE64_IMAGE_HEADER.length();

    if (base64String.startsWith(BASE64_IMAGE_HEADER) && base64String.length() > headerLen) {

        int semicolon = base64String.indexOf(";");
        int comma = base64String.indexOf(",", semicolon);

        String formatName = base64String.substring(headerLen, semicolon);
        int pos = formatName.lastIndexOf("/");
        if (pos != -1) {
            formatName = formatName.substring(pos + 1);
        }

        String base64Image = base64String.substring(comma + 1);

        BufferedImage img = ImageIO
                .read(new ByteArrayInputStream(java.util.Base64.getDecoder().decode(base64Image)));

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(img, formatName, baos);
        byte[] bytes = baos.toByteArray();
        return Pair.of(bytes, formatName);
    }

    throw new IllegalArgumentException("Invalid Image base64 String");
}

From source file:eu.novait.imagerenamer.model.ImageFile.java

private void createThumbnail() {
    try {/*from   www .  j  a va2  s  .  c  o  m*/
        BufferedImage tmp = ImageIO.read(this.filepath);
        int tmpW = tmp.getWidth();
        int tmpH = tmp.getHeight();
        double ratio = (double) tmpW / (double) tmpH;
        int w = 400;
        int h = (int) Math.round(w / ratio);
        BufferedImage bi = getCompatibleImage(w, h);
        Graphics2D g2d = bi.createGraphics();
        double xScale = (double) w / tmp.getWidth();
        double yScale = (double) h / tmp.getHeight();
        AffineTransform at = AffineTransform.getScaleInstance(xScale, yScale);
        g2d.drawRenderedImage(tmp, at);
        g2d.dispose();
        this.setThumbnail(bi);
    } catch (IOException ex) {
        Logger.getLogger(ImageFile.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:common.utils.ImageUtils.java

/**
 * resize input image to new dinesions(only smaller) and save it to file
 * @param file_stream input image for scaling
 * @param scale_factor desired value of width in result image
* @param rez writes resulting image to a file
* @throws IOException //from w  w w  .j  a  v  a2 s . c o  m
 */
public static void saveScaledImageWidth(InputStream file_stream, double scale_factor, File rez)
        throws IOException {
    //long time = System.nanoTime();
    BufferedImage image = ImageIO.read(file_stream);
    FileOutputStream fos = new FileOutputStream(rez);
    saveScaledImageWidth(image, scale_factor, fos);
    fos.close();
}

From source file:net.landora.video.infopanel.VideoInfoPanel.java

@Override
public void loadContext(MultiValueMap context) {
    Collection col = context.getCollection(VideoMetadata.class);

    VideoMetadata md = (VideoMetadata) UIUtils.select(col);

    byte[] data = md.getPosterImage();
    if (data == null) {
        lblPicture.setIcon(null);/*  www. j  a v a2s.com*/
    } else {
        try {
            Image img = ImageIO.read(new ByteArrayInputStream(data));
            lblPicture.setIcon(new ImageIcon(img));
        } catch (IOException ex) {
            lblPicture.setIcon(null);
            LoggerFactory.getLogger(getClass()).warn("Error loading image.", ex);
        }
    }

    Map<String, String> values = md.getAllInformation(false);

    StringBuilder buffer = new StringBuilder();
    buffer.append("<html>");

    Font font = lblPicture.getFont();
    buffer.append("<head>");
    buffer.append("<style type=\"text/css\">");

    buffer.append(" { margin-top: 0px; margin-bottom: 0px; margin-right: 0px; margin-left: 0px;  }");

    buffer.append("table { border-collapse:collapse; }");

    buffer.append(" td { ");
    buffer.append(" font-family: \"");
    buffer.append(font.getFamily());
    buffer.append("\"; font-size: ");
    buffer.append(font.getSize() - 2);
    buffer.append("px; ");

    buffer.append(" }\n");

    buffer.append(" td.label { ");
    buffer.append("text-align: right; ");
    buffer.append("font-weight:bold; ");
    buffer.append("white-space:nowrap; ");

    buffer.append(" font-family: \"");
    buffer.append(font.getFamily());
    buffer.append("\"; font-size: ");
    buffer.append(font.getSize() - 2);
    buffer.append("px; ");

    buffer.append("} ");
    buffer.append("</style>");
    buffer.append("</head>");
    buffer.append("<body>");
    buffer.append("<table>");
    boolean first = true;
    for (Map.Entry<String, String> entry : values.entrySet()) {
        buffer.append("<tr><td class=\"label\">");
        buffer.append(StringEscapeUtils.escapeHtml(entry.getKey()));
        buffer.append("</td><td>");
        buffer.append(StringEscapeUtils.escapeHtml(entry.getValue()));
        buffer.append("</td></tr>");
    }

    buffer.append("</table>");
    buffer.append("</body>");
    buffer.append("</html>");

    txtInfo.setContentType("text/html");
    txtInfo.setText(buffer.toString());
}

From source file:com.joliciel.jochre.boundaries.SplitCandidateFinderImplTest.java

@Test
public void testFindSplitCanidates(@NonStrict final JochrePage page) throws Exception {
    JochreServiceLocator locator = JochreServiceLocator.getInstance();

    GraphicsService graphicsService = locator.getGraphicsServiceLocator().getGraphicsService();
    BoundaryServiceInternal boundaryService = (BoundaryServiceInternal) locator.getBoundaryServiceLocator()
            .getBoundaryService();/*www  . j  ava2 s.com*/
    InputStream imageFileStream = getClass().getResourceAsStream("shape_370454.png");
    assertNotNull(imageFileStream);
    BufferedImage image = ImageIO.read(imageFileStream);

    JochreImage jochreImage = graphicsService.getSourceImage(page, "name", image);
    Shape shape = jochreImage.getShape(0, 0, jochreImage.getWidth() - 1, jochreImage.getHeight() - 1);

    SplitCandidateFinderImpl splitCandidateFinder = new SplitCandidateFinderImpl();
    splitCandidateFinder.setBoundaryServiceInternal(boundaryService);
    List<Split> splits = splitCandidateFinder.findSplitCandidates(shape);

    int[] trueSplitPositions = new int[] { 38, 59, 82 };
    boolean[] foundSplit = new boolean[] { false, false, false };
    for (Split splitCandidate : splits) {
        LOG.debug("Split candidate at " + splitCandidate.getPosition());
        for (int i = 0; i < trueSplitPositions.length; i++) {
            int truePos = trueSplitPositions[i];
            int distance = splitCandidate.getPosition() - truePos;
            if (distance < 0)
                distance = 0 - distance;
            if (distance < splitCandidateFinder.getMinDistanceBetweenSplits()) {
                foundSplit[i] = true;
                LOG.debug("Found split: " + truePos + ", distance " + distance);
            }
        }
    }

    for (int i = 0; i < trueSplitPositions.length; i++) {
        assertTrue("didn't find split " + trueSplitPositions[i], foundSplit[i]);
    }
}

From source file:cz.zcu.pia.social.network.backend.services.FileService.java

public void resizeImage(File file) throws IOException, IllegalArgumentException {
    //Scale the image
    String ext = FilenameUtils.getExtension(file.getName());

    BufferedImage resizedImage = Scalr.resize(ImageIO.read(file), Constants.PROFILE_IMAGE_SIZE);
    ImageIO.write(resizedImage, ext, new File(Constants.BASE_PATH_RESIZED + file.getName()));
    File resizedFile = new File(Constants.BASE_PATH_RESIZED + file.getName());
    if (securityHelper.getLogedInUser().getUserImageName() != null) {
        new File(Constants.BASE_PATH_RESIZED + securityHelper.getLogedInUser().getUserImageName()).delete();
    }/*from  ww  w .j  a  v  a2  s.  c o  m*/

    securityHelper.getLogedInUser().setUserImageName(resizedFile.getName());
    usersService.update(securityHelper.getLogedInUser());
    file.delete();
}

From source file:com.uwsoft.editor.proxy.ResolutionManager.java

public static BufferedImage imageResize(File file, float ratio) {
    BufferedImage destinationBufferedImage = null;
    try {/* www . java2s . c om*/
        BufferedImage sourceBufferedImage = ImageIO.read(file);
        if (ratio == 1.0) {
            return sourceBufferedImage;
        }
        // When image has to be resized smaller then 3 pixels we should leave it as is, as to ResampleOP limitations
        // But it should also trigger a warning dialog at the and of the import, to notify the user of non resized images.
        if (sourceBufferedImage.getWidth() * ratio < 3 || sourceBufferedImage.getHeight() * ratio < 3) {
            return null;
        }
        int newWidth = Math.max(3, Math.round(sourceBufferedImage.getWidth() * ratio));
        int newHeight = Math.max(3, Math.round(sourceBufferedImage.getHeight() * ratio));
        String name = file.getName();
        Integer[] patches = null;
        if (name.endsWith(EXTENSION_9PATCH)) {
            patches = NinePatchUtils.findPatches(sourceBufferedImage);
            sourceBufferedImage = NinePatchUtils.removePatches(sourceBufferedImage);

            newWidth = Math.round(sourceBufferedImage.getWidth() * ratio);
            newHeight = Math.round(sourceBufferedImage.getHeight() * ratio);
            System.out.println(sourceBufferedImage.getWidth());

            destinationBufferedImage = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_ARGB);
            Graphics2D g2 = destinationBufferedImage.createGraphics();
            g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                    RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
            g2.drawImage(sourceBufferedImage, 0, 0, newWidth, newHeight, null);
            g2.dispose();

        } else {
            // resize with bilinear filter
            ResampleOp resampleOp = new ResampleOp(newWidth, newHeight);
            destinationBufferedImage = resampleOp.filter(sourceBufferedImage, null);
        }

        if (patches != null) {
            destinationBufferedImage = NinePatchUtils.convertTo9Patch(destinationBufferedImage, patches, ratio);
        }

    } catch (IOException ignored) {

    }

    return destinationBufferedImage;
}

From source file:com.afis.jx.ckfinder.connector.utils.ImageUtils.java

/**
 * create thumb file./* w ww . j a v  a2 s.c  o  m*/
 *
 * @param orginFile origin image file.
 * @param file file to save thumb
 * @param conf connector configuration
 * @throws IOException when error occurs.
 */
public static void createThumb(final File orginFile, final File file, final IConfiguration conf)
        throws IOException {
    BufferedImage image = ImageIO.read(orginFile);
    if (image != null) {
        Dimension dimension = createThumbDimension(image, conf.getMaxThumbWidth(), conf.getMaxThumbHeight());
        FileUtils.createPath(file, true);
        if (image.getHeight() == dimension.height && image.getWidth() == dimension.width) {
            writeUntouchedImage(orginFile, file);
        } else {
            resizeImage(image, dimension.width, dimension.height, conf.getThumbsQuality(), file);
        }
    } else {
        if (conf.isDebugMode()) {
            throw new IOException("Wrong image file");
        }
    }

}