Example usage for javax.imageio ImageIO write

List of usage examples for javax.imageio ImageIO write

Introduction

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

Prototype

public static boolean write(RenderedImage im, String formatName, OutputStream output) throws IOException 

Source Link

Document

Writes an image using an arbitrary ImageWriter that supports the given format to an OutputStream .

Usage

From source file:net.rptools.assets.supplier.AbstractURIAssetSupplier.java

/**
 * Handle output stream and notify the asset upon completion. <b>This closes
 * the stream.</b>/*w w w  .  ja va  2s  .c om*/
 * @param id id of asset
 * @param obj asset itself
 * @param listener listener to inform upon completion
 * @param stream output stream to write to. Will be closed.
 * @throws IOException I/O problems
 */
@ThreadPolicy(ThreadPolicy.ThreadId.ANY)
protected void handleOutputStream(final String id, final Asset obj, final AssetListener listener,
        final OutputStream stream) throws IOException {
    try (final OutputStream outputStream = new OutputStreamInterceptor(getComponent().getFramework(), id, -1L,
            stream, listener, getNotifyInterval())) {
        switch (obj.getType()) {
        case IMAGE:
            final Image img = (Image) obj.getMain();
            ImageIO.write(SwingFXUtils.fromFXImage(img, null), "PNG", outputStream);
            break;
        case TEXT:
            final String txt = (String) obj.getMain();
            outputStream.write(txt.getBytes(StandardCharsets.UTF_8));
            break;
        default: // This should not happen. Messing with the constants, renders assets non-writable
            break;
        }
    }
    if (listener != null) {
        listener.notify(id, obj);
    }
}

From source file:UserInterface.GarbageCollectorRole.GarbageCollectorWorkAreaJPanel.java

public static void SaveScreenShot(Component component, String filename) throws Exception {
    BufferedImage img = getScreenShot(component);
    ImageIO.write(img, "png", new File(filename));
}

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

/**
 * Save an image to a specified file./*ww w . ja va2 s  .com*/
 */
private static void saveImage(BufferedImage image, File file) throws Exception {
    String filename = file.getName();
    int pos = filename.lastIndexOf('.');
    if (pos == -1 || (pos + 1) >= filename.length()) {
        throw new Exception("Unknown image type " + filename);
    }
    String imageType = filename.substring(pos + 1);
    File imageFile = new File(file.getParent(), filename);
    FileOutputStream fos = null;
    try {
        fos = new FileOutputStream(imageFile);
        ImageIO.write(image, imageType, fos);
    } finally {
        if (fos != null) {
            try {
                fos.close();
            } catch (Exception e) {
            }
        }
    }
}

From source file:fr.ign.cogit.simplu3d.rjmcmc.generic.visitor.FilmVisitor.java

/**
 * Permet d'enregistrer une image  partir de l'cran Ne fonctionne qu'avec
 * l'IHM actuel (Offset ncessaire) Ne prends pas compte de l'existance d'un
 * fichier de mme nom//from  w  w w .  j av a2  s .  c  om
 * 
 * @param path
 *            le dossier dans lequel l'impr ecran sera supprime
 * @param fileName
 *            le nom du fichier
 * @return indique si la capture s'est effectue avec succs
 */
public boolean screenCapture(String path, String fileName, InterfaceMap3D iMap3D) {

    try {

        ChartPanel v = StatsVisitor.CHARTSINGLETON;

        int xSup = 0;
        int ySup = 0;

        boolean hasStats = (v != null);

        if (hasStats) {

            xSup = v.getSize().width;
            ySup = v.getSize().height;

        }

        int xSize = iMap3D.getSize().width + xSup;
        int ySize = Math.max(iMap3D.getSize().height, ySup);

        BufferedImage bufImage = new BufferedImage(xSize, ySize, BufferedImage.TYPE_INT_RGB);

        Graphics g = bufImage.createGraphics();

        g.setColor(Color.white);

        // g.drawRect(0, 0, xSize, ySize);

        g.fillRect(0, 0, xSize, ySize);

        iMap3D.getCanvas3D().paint(g);

        if (hasStats) {

            g.drawImage(v.getChart().createBufferedImage(xSup, ySup), iMap3D.getSize().width,
                    (ySize - ySup) / 2, null);

        }

        File fichier = new File(path, fileName);
        if (fichier.exists()) {
            System.out.println("Fail");
            return false;
        } else {
            ImageIO.write(bufImage, "jpg", fichier);
            return true;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return false;
}

From source file:com.ikon.module.common.CommonWorkflowModule.java

/**
 * Get Process Definition Image//from  w  w w  .  j  a v a  2 s .c om
 */
public static byte[] getProcessDefinitionImage(long processDefinitionId, String node) throws WorkflowException {
    log.debug("getProcessDefinitionImage({}, {})", new Object[] { processDefinitionId, node });
    JbpmContext jbpmContext = JBPMUtils.getConfig().createJbpmContext();
    byte[] image = null;

    try {
        GraphSession graphSession = jbpmContext.getGraphSession();
        org.jbpm.graph.def.ProcessDefinition pd = graphSession.getProcessDefinition(processDefinitionId);
        FileDefinition fileDef = pd.getFileDefinition();

        WorkflowUtils.DiagramInfo dInfo = WorkflowUtils.getDiagramInfo(fileDef.getInputStream("gpd.xml"));
        WorkflowUtils.DiagramNodeInfo dNodeInfo = dInfo.getNodeMap().get(node);
        BufferedImage img = ImageIO.read(fileDef.getInputStream("processimage.jpg"));

        // Obtain all nodes Y and X
        List<Integer> ordenadas = new ArrayList<Integer>();
        List<Integer> abcisas = new ArrayList<Integer>();

        for (WorkflowUtils.DiagramNodeInfo nodeInfo : dInfo.getNodeMap().values()) {
            ordenadas.add(nodeInfo.getY());
            abcisas.add(nodeInfo.getX());
        }

        // Calculate minimal Y
        Collections.sort(ordenadas);
        int fixOrd = ordenadas.get(0) < 0 ? ordenadas.get(0) : 0;

        // Calculate minimal X
        Collections.sort(abcisas);
        int fixAbs = abcisas.get(0) < 0 ? abcisas.get(0) : 0;

        if (dNodeInfo != null) {
            // Select node
            log.debug("DiagramNodeInfo: {}", dNodeInfo);
            Graphics g = img.getGraphics();
            Graphics2D g2d = (Graphics2D) g;
            g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.25F));
            g2d.setColor(Color.blue);
            g2d.fillRect(dNodeInfo.getX() - fixAbs, dNodeInfo.getY() - fixOrd, dNodeInfo.getWidth(),
                    dNodeInfo.getHeight());
            g.dispose();
        }

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(img, "jpg", baos);
        image = baos.toByteArray();
        baos.flush();
        baos.close();
    } catch (JbpmException e) {
        throw new WorkflowException(e.getMessage(), e);
    } catch (IOException e) {
        throw new WorkflowException(e.getMessage(), e);
    } finally {
        jbpmContext.close();
    }

    log.debug("getProcessDefinitionImage: {}", image);
    return image;
}

From source file:com.mycollab.mobile.ui.MobileAttachmentUtils.java

public static void saveContentsToRepo(String attachmentPath, Map<String, File> fileStores) {
    if (MapUtils.isNotEmpty(fileStores)) {
        ResourceService resourceService = AppContextUtil.getSpringBean(ResourceService.class);
        for (Map.Entry<String, File> entry : fileStores.entrySet()) {
            try {
                String fileExt = "";
                String fileName = entry.getKey();
                File file = entry.getValue();
                int index = fileName.lastIndexOf(".");
                if (index > 0) {
                    fileExt = fileName.substring(index + 1, fileName.length());
                }/*from   w  w w .  j av a2  s  .  c o m*/

                if ("jpg".equalsIgnoreCase(fileExt) || "png".equalsIgnoreCase(fileExt)) {
                    try {
                        BufferedImage bufferedImage = ImageIO.read(file);

                        int imgHeight = bufferedImage.getHeight();
                        int imgWidth = bufferedImage.getWidth();

                        BufferedImage scaledImage;

                        float scale;
                        float destWidth = 974;
                        float destHeight = 718;

                        float scaleX = Math.min(destHeight / imgHeight, 1);
                        float scaleY = Math.min(destWidth / imgWidth, 1);
                        scale = Math.min(scaleX, scaleY);
                        scaledImage = ImageUtil.scaleImage(bufferedImage, scale);

                        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
                        ImageIO.write(scaledImage, fileExt, outStream);

                        resourceService.saveContent(constructContent(fileName, attachmentPath),
                                UserUIContext.getUsername(), new ByteArrayInputStream(outStream.toByteArray()),
                                MyCollabUI.getAccountId());
                    } catch (IOException e) {
                        LOG.error("Error in upload file", e);
                        resourceService.saveContent(constructContent(fileName, attachmentPath),
                                UserUIContext.getUsername(), new FileInputStream(fileStores.get(fileName)),
                                MyCollabUI.getAccountId());
                    }
                } else {
                    resourceService.saveContent(constructContent(fileName, attachmentPath),
                            UserUIContext.getUsername(), new FileInputStream(file), MyCollabUI.getAccountId());
                }

            } catch (FileNotFoundException e) {
                LOG.error("Error when attach content in UI", e);
            }
        }
    }
}

From source file:com.mycompany.controllers.ClubController.java

private byte[] LogoConvertion(byte[] bytes) {
    int width = 200;
    int height = 200;
    ByteArrayInputStream in = new ByteArrayInputStream(bytes);
    try {/*from   w  w w  . ja  va  2  s .c om*/
        BufferedImage img = ImageIO.read(in);
        if (height == 0) {
            height = (width * img.getHeight()) / img.getWidth();
        }
        if (width == 0) {
            width = (height * img.getWidth()) / img.getHeight();
        }
        Image scaledImage = img.getScaledInstance(width, height, Image.SCALE_SMOOTH);
        BufferedImage imageBuff = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        imageBuff.getGraphics().drawImage(scaledImage, 0, 0, new Color(0, 0, 0), null);

        ByteArrayOutputStream buffer = new ByteArrayOutputStream();

        ImageIO.write(imageBuff, "jpg", buffer);

        bytes = buffer.toByteArray();
    } catch (IOException e) {
        log.error("File convertion error");
    }
    return bytes;
}

From source file:com.hygenics.imaging.ImageCleanup.java

public byte[] setBlackandWhite(byte[] ibytes) {
    ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_GRAY);
    ColorConvertOp op = new ColorConvertOp(cs, null);
    BufferedImage image = op.filter(BufferImage(ibytes), null);

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    // convert to jpeg for compression
    try {//ww  w.  j  a v a 2 s  . com
        // use apache to read to a buffered image with certain metadata and
        // then convert to a jpg
        ImageIO.write(image, "jpg", bos);
        return bos.toByteArray();

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return ibytes;
}

From source file:uk.co.petertribble.jkstat.gui.KstatBaseChartFrame.java

/**
 * Saves the current chart as an image in png format. The user can select
 * the filename, and is asked to confirm the overwrite of an existing file.
 *///from   w w  w.  j  a v a2s .  c o m
public void saveImage() {
    JFileChooser fc = new JFileChooser();
    if (fc.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
        File f = fc.getSelectedFile();
        if (f.exists()) {
            int ok = JOptionPane.showConfirmDialog(this,
                    KstatResources.getString("SAVEAS.OVERWRITE.TEXT") + " " + f.toString(),
                    KstatResources.getString("SAVEAS.CONFIRM.TEXT"), JOptionPane.YES_NO_OPTION);
            if (ok != JOptionPane.YES_OPTION) {
                return;
            }
        }
        BufferedImage bi = kbc.getChart().createBufferedImage(500, 300);
        try {
            ImageIO.write(bi, "png", f);
            /*
             * According to the API docs this should throw an IOException
             * on error, but this doesn't seem to be the case. As a result
             * it's necessary to catch exceptions more generally. Even this
             * doesn't work properly, but at least we manage to convey the
             * message to the user that the write failed, even if the
             * error itself isn't handled.
             */
        } catch (Exception ioe) {
            JOptionPane.showMessageDialog(this, ioe.toString(), KstatResources.getString("SAVEAS.ERROR.TEXT"),
                    JOptionPane.ERROR_MESSAGE);
        }
    }
}

From source file:edu.sdsc.scigraph.services.jersey.writers.ImageWriter.java

@Override
public void writeTo(Graph data, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType,
        MultivaluedMap<String, Object> headers, OutputStream out) throws IOException {
    Integer width = Integer.parseInt(Optional.fromNullable(request.getParameter("width")).or(DEFAULT_WIDTH));
    Integer height = Integer.parseInt(Optional.fromNullable(request.getParameter("height")).or(DEFAULT_HEIGHT));
    String layoutName = Optional.fromNullable(request.getParameter("layout")).or(DEFAULT_LAYOUT);

    GraphJung<Graph> graph = new GraphJung<Graph>(data);
    AbstractLayout<Vertex, Edge> layout = getLayout(graph, layoutName);
    layout.setSize(new Dimension(width, height));

    BasicVisualizationServer<Vertex, Edge> viz = new BasicVisualizationServer<>(layout);
    viz.setPreferredSize(new Dimension(width, height));
    viz.getRenderContext().setEdgeLabelTransformer(edgeLabelTransformer);
    viz.getRenderContext().setVertexLabelTransformer(vertexLabelTransformer);
    viz.getRenderContext().setVertexFillPaintTransformer(vertexColorTransformer);

    BufferedImage bi = renderImage(viz);
    String imageType = null;/*from   w w w.j  ava 2s  .  c  o  m*/
    if (mediaType.equals(CustomMediaTypes.IMAGE_JPEG_TYPE)) {
        imageType = "jpg";
    } else if (mediaType.equals(CustomMediaTypes.IMAGE_PNG_TYPE)) {
        imageType = "png";
    }
    ImageIO.write(bi, imageType, out);
}