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:com.openkm.util.ImageUtils.java

/**
 * crop//from  w  w w . j  a v a 2  s  . c o  m
 */
public static byte[] crop(byte[] img, int x, int y, int width, int height) throws RuntimeException {
    log.debug("crop({}, {}, {}, {}, {})", new Object[] { img.length, x, y, width, height });
    ByteArrayInputStream bais = new ByteArrayInputStream(img);
    byte[] imageInByte;

    try {
        BufferedImage image = ImageIO.read(bais);
        BufferedImage croppedImage = image.getSubimage(x, y, width, height);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(croppedImage, "png", baos);
        baos.flush();
        imageInByte = baos.toByteArray();
        IOUtils.closeQuietly(baos);
    } catch (IOException e) {
        log.error(e.getMessage());
        throw new RuntimeException("IOException: " + e.getMessage(), e);
    } finally {
        IOUtils.closeQuietly(bais);
    }

    log.debug("crop: {}", imageInByte.length);
    return imageInByte;
}

From source file:com.tdclighthouse.prototype.servlets.JLatexServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String latexExpression = req.getParameter(LATEX_PARAM);
    latexExpression = StringEscapeUtils.unescapeXml(latexExpression);

    if (latexExpression != null && !"".equals(latexExpression)) {
        BufferedImage image = generateImage(latexExpression);
        resp.setContentType(MIME_TYPE);//  w  w w .ja v a  2 s  .  c o m
        ImageIO.write(image, IMAGE_TYPE, resp.getOutputStream());
    } else {
        resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
    }
}

From source file:com.salesforce.pixelcaptcha.demo.LandingController.java

private String convertBufferedImageToPngBase64(BufferedImage bi) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {/*from w w w  .  j a  v a 2 s.  co m*/
        ImageIO.write(bi, "png", baos);
    } catch (IOException e) {
        System.out.println(e);
    }
    String encoded = Base64.getEncoder().encodeToString(baos.toByteArray());
    return encoded;
}

From source file:com.sms.server.controller.ImageController.java

@RequestMapping(value = "/{id}/cover/{scale}", method = RequestMethod.GET, produces = "image/jpeg")
@ResponseBody//from   ww  w  . j  a  va  2  s  .  c om
public ResponseEntity getCoverArt(@PathVariable("id") Long id, @PathVariable("scale") Integer scale) {
    MediaElement mediaElement;
    BufferedImage image;

    // Get corresponding media element
    mediaElement = mediaDao.getMediaElementByID(id);

    if (mediaElement == null) {
        return new ResponseEntity<>(HttpStatus.NOT_FOUND);
    }

    // Get scaled cover art
    image = imageService.getCoverArt(mediaElement, scale);

    // Check if we were able to retrieve a cover
    if (image == null) {
        return new ResponseEntity<>(HttpStatus.NOT_FOUND);
    }

    // Convert image to bytes to send
    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(image, "jpg", baos);
        byte[] imageBytes = baos.toByteArray();

        // Return cover art if found
        return new ResponseEntity(imageBytes, HttpStatus.OK);

    } catch (IOException ex) {
        return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

From source file:problematica.Graficos.java

/**
 * //from  ww  w.j  a  v  a2 s . c  om
 * @param cantCigarros
 */

public static void createGrafico(ArrayList<ArrayList<String>> datos, String nombreArchivo) {

    XYSeries series = new XYSeries("Linea de consumo");
    //como su nombre lo indica el primer valor sera asignado al eje X
    //y el segundo al eje Y

    series.add(0, 0);

    for (int i = 0; i < datos.size(); i++) {

        series.add((i + 1), Integer.parseInt(datos.get(i).get(0)));

    }

    //se crea un objeto XYDataset requerido mas adelante por el metodo que grafica
    XYDataset juegoDatos = new XYSeriesCollection(series);

    /*aqui se hace la instancia de la nueva grafica invocando al metodo de ChartFactory
    que nos dibujara una grafica de lineas este metodo como casi todos los demas
    recibe los siguientes argumentos:
            
    tipo              valor
    String            nombre de la grafica , aparecera en la parte superior centro
    String            tutulo del eje X
    String            titulo del eje Y
    XYDataset         el conjunto de datos X y Y del tipo XYDataset (aqui cambian el parametro
                      dependiendo del tipo de grafica que se quiere pueden ver todos los parametros
                      en la documentacion aqui <a href="http://www.jfree.org/jfreechart/api/javadoc/index.html
    " title="http://www.jfree.org/jfreechart/api/javadoc/index.html
    ">http://www.jfree.org/jfreechart/api/javadoc/index.html
    </a>                              iremos notando los cambios mas adelante..
     PlotOrientation  la orientacion del grafico puede ser PlotOrientation.VERTICAL o PlotOrientation.HORIZONTAL
     boolean                  muestra u oculta leyendas     
     boolean                  muestra u oculta tooltips
     boolean                  muestra u oculta urls (esta opcion aun no la entiendo del todo)
            
    generalmente solo necesitaremos cambiar los primeros 3 parametros lo demas puede quedarse asi
            
    */
    JFreeChart chart = ChartFactory.createXYLineChart("Grafico de consumo", "dias", "cantidad cigarrillos",
            juegoDatos, PlotOrientation.VERTICAL, true, false, true // Show legend
    );
    //donde guardaremos la imagen?? pues en un bufer jeje
    BufferedImage image = chart.createBufferedImage(500, 500);

    try {
        ImageIO.write(image, "jpg", new File("c:/users/public/nms/grafico/" + nombreArchivo + ".jpg"));
    } catch (IOException e) {
        System.out.println("Error de escritura");
    }

}

From source file:at.ac.tuwien.dsg.utility.DesignChart.java

public void chart(LinkedList<String> xValue, LinkedList<String> yValue) throws Exception {

    XYSeries series = new XYSeries("Sensory Data");
    final JFreeChart chart;

    //data assignment in the chart
    {//from  w  w  w  .ja  v  a2s  . c o  m
        for (int i = 0; i < xValue.size(); i++) {
            series.add(Double.parseDouble(xValue.get(i)), Double.parseDouble(yValue.get(i)));
        }

        final XYSeriesCollection data = new XYSeriesCollection(series);
        chart = ChartFactory.createXYLineChart("Graph Visualization", "collection_time", "collection_data",
                data, PlotOrientation.VERTICAL, true, true, false);
    }

    //design the plot of the chart
    {
        XYPlot xyPlot = chart.getXYPlot();
        NumberAxis xAxis = (NumberAxis) xyPlot.getDomainAxis();
        NumberAxis yAxis = (NumberAxis) xyPlot.getRangeAxis();

        xAxis.setRange(20, 120);
        xAxis.setTickUnit(new NumberTickUnit(15));
        yAxis.setRange(947, 950);
        yAxis.setTickUnit(new NumberTickUnit(0.5));
    }

    //generation of the image  
    {
        try {

            BufferedImage img = chart.createBufferedImage(300, 200);
            //File outputfile = new File("./example/Sample.png");
            File outputfile = new File(
                    "/Users/dsg/Documents/phd/Big Demo/CloudLyra/Utils/JBPMEngine/example/Sample.png");
            ImageIO.write(img, "png", outputfile);

        } catch (Exception e) {
            System.out.println("exception occured in tomcat: " + e);
        }
    }

}

From source file:BluemixUtils.java

public static void retriveFaces(ClassifierUnit unit) throws IOException {
    //curl -X POST -F "images_file=@prez.jpg" "https://gateway-a.watsonplatform.net/visual-recognition/api/v3/detect_faces?api_key={api-key}&version=2016-05-20"
    File facesDir = new File(unit.getFolderWithImages() + "_faces");
    facesDir.mkdir();//from www  .j a  v  a 2  s  .co m
    for (File image : new File(unit.getFolderWithImages()).listFiles()) {
        try {
            String command = "D:/curl/curl -X POST -F \"images_file=@" + image.getAbsolutePath()
                    + "\" \"https://gateway-a.watsonplatform.net/visual-recognition/api/v3/detect_faces?api_key={02a6297b759128a71e59e1a97c682826398584b4}&version=2016-05-20\"";
            String res = executeCmdCommand(command);
            FaceDetection s = new Gson().fromJson(res, FaceDetection.class);
            System.out.println(s.getBluemixImages().get(0).getFaces());
            BufferedImage in = ImageIO.read(image);
            for (Face face : s.getBluemixImages().get(0).getFaces()) {
                FaceLocation faceLoc = face.getFaceLocation();
                BufferedImage newIm = in.getSubimage(faceLoc.getLeft(), faceLoc.getTop(), faceLoc.getWidth(),
                        faceLoc.getHeight());
                File outputfile = new File(facesDir + File.separator + image.getName());
                ImageIO.write(newIm, "jpg", outputfile);
            }
        } catch (Exception ex) {
            Logger.getLogger("KrilovUtils.class").fine(ex.getMessage());
        }
    }

}

From source file:UserInterface.EmployeeViewArea.ViewIssuesStatisticsJPanel.java

public static void saveToFile(JFreeChart chart, String aFileName, int width, int height, double quality)
        throws FileNotFoundException, IOException {
    BufferedImage img = draw(chart, width, height);

    FileOutputStream fos = new FileOutputStream(aFileName);
    ImageIO.write(img, "jpg", fos);
    fos.close();/*from  w w w  .j ava 2s  .  c o  m*/
}

From source file:brut.androlib.res.decoder.Res9patchStreamDecoder.java

@Override
public void decode(InputStream in, OutputStream out) throws AndrolibException {
    try {/*  ww  w. ja va2s .  c  o m*/
        byte[] data = IOUtils.toByteArray(in);

        BufferedImage im = ImageIO.read(new ByteArrayInputStream(data));
        int w = im.getWidth(), h = im.getHeight();

        ImageTypeSpecifier its = ImageTypeSpecifier.createFromRenderedImage(im);
        BufferedImage im2 = its.createBufferedImage(w + 2, h + 2);

        im2.getRaster().setRect(1, 1, im.getRaster());
        NinePatch np = getNinePatch(data);
        drawHLine(im2, h + 1, np.padLeft + 1, w - np.padRight);
        drawVLine(im2, w + 1, np.padTop + 1, h - np.padBottom);

        int[] xDivs = np.xDivs;
        for (int i = 0; i < xDivs.length; i += 2) {
            drawHLine(im2, 0, xDivs[i] + 1, xDivs[i + 1]);
        }

        int[] yDivs = np.yDivs;
        for (int i = 0; i < yDivs.length; i += 2) {
            drawVLine(im2, 0, yDivs[i] + 1, yDivs[i + 1]);
        }

        ImageIO.write(im2, "png", out);
    } catch (IOException ex) {
        throw new AndrolibException(ex);
    } catch (NullPointerException ex) {
        // In my case this was triggered because a .png file was
        // containing a html document instead of an image.
        // This could be more verbose and try to MIME ?
        throw new AndrolibException(ex);
    }
}

From source file:com.qmetry.qaf.automation.util.FileUtil.java

public static String saveImageFile(BufferedImage bImag, String prefix, String dir) throws Exception {
    File file = generateFile(prefix, ".png", dir);
    ImageIO.write(bImag, "png", file);
    return file.getName();
}