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:hudson.model.LoadStatisticsTest.java

public void testGraph() throws IOException {
    LoadStatistics ls = new LoadStatistics(0, 0) {
        public int computeIdleExecutors() {
            throw new UnsupportedOperationException();
        }/*  w ww  .j a  v a2 s  .c  o m*/

        public int computeTotalExecutors() {
            throw new UnsupportedOperationException();
        }

        public int computeQueueLength() {
            throw new UnsupportedOperationException();
        }
    };

    for (int i = 0; i < 50; i++) {
        ls.totalExecutors.update(4);
        ls.busyExecutors.update(3);
        ls.queueLength.update(3);
    }

    for (int i = 0; i < 50; i++) {
        ls.totalExecutors.update(0);
        ls.busyExecutors.update(0);
        ls.queueLength.update(1);
    }

    JFreeChart chart = ls.createTrendChart(TimeScale.SEC10).createChart();
    BufferedImage image = chart.createBufferedImage(400, 200);

    File tempFile = File.createTempFile("chart-", "png");
    FileOutputStream os = new FileOutputStream(tempFile);
    try {
        ImageIO.write(image, "PNG", os);
    } finally {
        IOUtils.closeQuietly(os);
        tempFile.delete();
    }
}

From source file:com.google.code.jcaptcha4struts2.core.actions.JCaptchaImageAction.java

/**
 * Action execution logic, which generates the Captcha Image Stream and sets the JPEG encoded
 * byte stream to captchaImage field./*  w w w  . j a v  a  2 s.  co  m*/
 * <p>
 * Subsequent to invocation of this method, the generated captcha is available through
 * {@link #getCaptchaImage()} method.
 * 
 * @return action forward string
 * 
 * @throws Exception
 */
public String execute() {

    ByteArrayOutputStream imageOut = new ByteArrayOutputStream();
    HttpServletRequest request = ServletActionContext.getRequest();

    // Captcha Id is the session ID
    String captchaId = request.getSession().getId();

    if (LOG.isDebugEnabled()) {
        LOG.debug("Generating Captcha Image for SessionID : " + captchaId);
    }

    // Generate Captcha Image
    BufferedImage image = getImageCaptchaService().getImageChallengeForID(captchaId, request.getLocale());

    // Encode to JPEG Stream
    try {
        ImageIO.write(image, IMAGE_FORMAT, imageOut);
    } catch (IOException e) {
        LOG.error("Unable to JPEG encode the Captcha Image due to IOException", e);
        throw new IllegalArgumentException("Unable to JPEG encode the Captcha Image", e);
    }

    // Get byte[] for image
    captchaImage = imageOut.toByteArray();

    return SUCCESS;
}

From source file:com.sishistorico.sv.SvEditarEleitor.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from  w  w w  .j  a  va  2  s  . com
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    request.setCharacterEncoding("UTF8");
    response.setContentType("text/html;charset=UTF-8");

    List<FileItem> items = null;
    byte[] foto = null;
    long vazio = 0;
    try {
        items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
        for (FileItem item : items) {
            if (!item.isFormField()) {
                vazio = item.getSize();
                System.out.println("tamanho/:::::::::::::::::::: " + vazio);
                InputStream imageInput = item.getInputStream();
                Image image = ImageIO.read(imageInput);
                BufferedImage thumb = Imagem.redimensionar(image, 400, 500);
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                ImageIO.write(thumb, "JPG", baos);
                baos.flush();
                foto = baos.toByteArray();
                baos.close();
            }
        }
        //dados do formulrio e metodos para salvar 
        DateFormat formatter;
        Date date;
        formatter = new SimpleDateFormat("dd/MM/yyyy");
        date = (Date) formatter.parse(items.get(1).getString());
        // fim do tratamento        
        Eleitor el = new Eleitor();
        Endereco end = new Endereco();
        el.setId(Integer.parseInt(items.get(19).getString("UTF-8").trim()));
        el.setNome(items.get(0).getString("UTF-8").trim());
        el.setData_nascimento(date);
        el.setCpf(items.get(2).getString("UTF-8").replaceAll("\\.|\\-|\\ ", "").trim());
        el.setRg(items.get(3).getString("UTF-8").replaceAll("\\.|\\-|\\ ", "").trim());
        el.setSus(items.get(4).getString("UTF-8").replaceAll("\\.|\\-|\\ ", "").trim());
        el.setEmail(items.get(5).getString("UTF-8"));
        el.setTelefone(items.get(6).getString("UTF-8").replaceAll("\\(|\\)|\\-|\\ ", "").trim());
        el.setWhats(items.get(7).getString("UTF-8").replaceAll("\\(|\\)|\\-|\\ ", "").trim());
        el.setObs(items.get(8).getString("UTF-8").trim());
        el.setReferencia_pessoal(items.get(9).getString("UTF-8").trim());

        end.setRua(items.get(11).getString("UTF-8").trim());
        end.setBairro(items.get(12).getString("UTF-8").trim());
        end.setN(items.get(13).getString("UTF-8").trim());
        end.setCidade(items.get(14).getString("UTF-8").trim());
        end.setCep(items.get(15).getString("UTF-8").trim());
        end.setLocalidade(Integer.parseInt(items.get(16).getString("UTF-8").trim()));
        el.setTipo(Integer.parseInt(items.get(17).getString("UTF-8").trim()));
        el.setPertence(Integer.parseInt(items.get(18).getString("UTF-8").trim()));

        el.setEnd(end);
        DaoEleitor daoEleitor = new DaoEleitor();
        DaoFoto daoFoto = new DaoFoto();
        int idretorno = daoEleitor.Eleitor_Editar(el);
        if (vazio > 1) {
            daoFoto.atualizarImagem(foto, idretorno);
        }
        response.sendRedirect("editar_eleitor.jsp?id=" + el.getId() + "&msgok=Editado com sucesso!");

    } catch (FileUploadException ex) {
        Logger.getLogger(SvEditarEleitor.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SQLException ex) {
        Logger.getLogger(SvEditarEleitor.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ClassNotFoundException ex) {
        Logger.getLogger(SvEditarEleitor.class.getName()).log(Level.SEVERE, null, ex);
    } catch (Exception ex) {
        Logger.getLogger(SvEditarEleitor.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:org.openmrs.module.complexdatadb.api.handler.ImageDBHandler.java

/**
 * @see org.openmrs.obs.ComplexObsHandler#saveObs(org.openmrs.Obs)
 */// w ww. j  ava2  s. co m
@Override
public Obs saveObs(Obs obs) throws APIException {

    // Get the buffered image from the ComplexData.
    BufferedImage img = null;

    Object data = obs.getComplexData().getData();
    if (data instanceof BufferedImage) {
        img = (BufferedImage) data;
    } else if (data instanceof InputStream) {
        try {
            img = ImageIO.read((InputStream) data);
            if (img == null) {
                throw new IllegalArgumentException("Invalid image file");
            }
        } catch (IOException e) {
            throw new APIException(
                    "Unable to convert complex data to a valid input stream and then read it into a buffered image",
                    e);
        }
    }

    if (img == null) {
        throw new APIException("Cannot save complex obs where obsId=" + obs.getObsId()
                + " because its ComplexData.getData() is null.");
    }

    try {

        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        String extension = getExtension(obs.getComplexData().getTitle());
        ImageIO.write(img, extension, baos);
        baos.flush();
        byte[] bImage = baos.toByteArray();
        baos.close();

        ComplexDataToDB image = new ComplexDataToDB();

        image.setData(bImage);

        Context.getService(ComplexDataToDBService.class).saveComplexDataToDB(image);

        // Set the Title and URI for the valueComplex
        obs.setValueComplex(extension + " image |" + image.getUuid());

        // Remove the ComlexData from the Obs
        obs.setComplexData(null);

    } catch (IOException ioe) {
        throw new APIException("Trying to write complex obs to the database. ", ioe);
    }

    return obs;
}

From source file:irille.pub.verify.RandomImageServlet.java

/**
 * ???,,?16,//w ww. j a  v  a 2s .  co  m
 * @param num   ??
 * @param out   ?
 * @throws IOException
 */
protected static void render(String num, boolean gif, OutputStream out) throws IOException {
    if (num.getBytes().length > 4)
        throw new IllegalArgumentException("The length of param num cannot exceed 4.");
    int width = 50;
    int height = 18;
    BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    Graphics2D g = (Graphics2D) bi.getGraphics();
    g.setColor(Color.WHITE);
    g.fillRect(0, 0, width, height);
    Font mFont = new Font("Tahoma", Font.BOLD | Font.ITALIC, 16);
    g.setFont(mFont);
    g.setColor(Color.BLACK);
    g.drawString(num, 2, 15);
    if (gif) {
        AnimatedGifEncoder e = new AnimatedGifEncoder();
        e.setTransparent(Color.WHITE);
        e.start(out);
        e.setDelay(0);
        e.addFrame(bi);
        e.finish();
    } else {
        ImageIO.write(bi, "png", out);
    }
}

From source file:net.librec.util.Systems.java

/**
 * Capture screen with the input string as file name
 *
 * @param fileName  a given file name/*from   ww w  .j  av a2 s  . com*/
 * @throws Exception if error occurs
 */
public static void captureScreen(String fileName) throws Exception {

    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    Rectangle screenRectangle = new Rectangle(screenSize);
    Robot robot = new Robot();
    BufferedImage image = robot.createScreenCapture(screenRectangle);

    File file = new File(fileName);
    ImageIO.write(image, "png", file);

    LOG.debug("A screenshot is captured to: " + file.getPath());
}

From source file:ImageUtil.java

public static ByteArrayOutputStream scale(ByteArrayInputStream bais, int width, int height) throws IOException {
    BufferedImage src = ImageIO.read(bais);
    BufferedImage dest = scale(src, width, height);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ImageIO.write(dest, "JPG", baos);
    return baos;/*from   w w  w.  j  a va 2s .  com*/
}

From source file:com.comcast.video.dawg.show.video.VideoSnapTest.java

@Test
public void testCaptureImage() throws IOException {
    String deviceId = "000000000001";

    final DawgVideoOutput mockDVO = EasyMock.createMock(DawgVideoOutput.class);
    EasyMock.expect(mockDVO.captureScreen()).andReturn(PC_IMG);
    VideoSnap videoSnap = new VideoSnap() {
        @Override//from  w w w  .j  av  a  2  s. c  o  m
        protected DawgVideoOutput createDawgVideoOutput(MetaStb stb) {
            return mockDVO;
        }
    };
    MetaStbCache stbCache = new MetaStbCache();
    MetaStb stb = new MetaStb();
    stbCache.putMetaStb(deviceId, stb);
    MockHttpSession session = new MockHttpSession();

    EasyMock.replay(mockDVO);
    String iid = videoSnap.captureImage(deviceId, session, stbCache);
    Assert.assertNotNull(iid);

    ByteArrayOutputStream bao = new ByteArrayOutputStream();
    ImageIO.write(PC_IMG, "jpg", bao);

    EasyMock.verify(mockDVO);

    UniqueIndexedCache<BufferedImage> imgCache = ClientCache.getClientCache(session).getImgCache();
    Assert.assertSame(imgCache.getItem(iid), PC_IMG, "Captured image is not matching with expected image");

}

From source file:com.liusoft.dlog4j.servlet.DLOG_RandomImageServlet.java

/**
 * ???,,?16,//from   w  w  w  . j  av  a2s . co m
 * @param num   ??
 * @param out   ?
 * @throws IOException
 */
protected static void render(String num, boolean gif, OutputStream out) throws IOException {
    if (num.getBytes().length > 4)
        throw new IllegalArgumentException("The length of param num cannot exceed 4.");
    int width = 40;
    int height = 15;
    BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    Graphics2D g = (Graphics2D) bi.getGraphics();
    g.setColor(Color.WHITE);
    g.fillRect(0, 0, width, height);
    Font mFont = new Font("Tahoma", Font.PLAIN, 14);
    g.setFont(mFont);
    g.setColor(Color.BLACK);
    g.drawString(num, 2, 13);
    if (gif) {
        AnimatedGifEncoder e = new AnimatedGifEncoder();
        e.setTransparent(Color.WHITE);
        e.start(out);
        e.setDelay(0);
        e.addFrame(bi);
        e.finish();
    } else {
        ImageIO.write(bi, "png", out);
    }
}

From source file:com.fun.util.TesseractUtil.java

/**
 * /*from   w w w. ja  v a  2 s . co  m*/
 *
 * @param imageFile
 * @param times
 * @param targetFile
 * @throws IOException
 */
private static void scaled(File imageFile, int times, File targetFile) throws IOException {
    BufferedImage image = ImageIO.read(imageFile);
    int targetWidth = image.getWidth() * times;
    int targetHeight = image.getHeight() * times;
    int type = (image.getTransparency() == Transparency.OPAQUE) ? BufferedImage.TYPE_INT_RGB
            : BufferedImage.TYPE_INT_ARGB;
    BufferedImage tmp = new BufferedImage(targetWidth, targetHeight, type);
    Graphics2D g2 = tmp.createGraphics();
    g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
    g2.drawImage(image, 0, 0, targetWidth, targetHeight, null);
    g2.dispose();
    ImageIO.write(tmp, "png", targetFile);
}