List of usage examples for javax.imageio ImageIO write
public static boolean write(RenderedImage im, String formatName, OutputStream output) throws IOException
From source file:org.shept.services.jcaptcha.ImageCaptchaServlet.java
@SuppressWarnings("unchecked") protected void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException { BufferedImage challenge = null; try {/*from w ww . ja v a 2 s .co m*/ // get the session id that will identify the generated captcha. // the same id must be used to validate the response, the session id // is a good candidate! String captchaId = httpServletRequest.getSession().getId(); // If we have an explicit configuration for an ImageService we use this // else we use the predefined default ImageCaptchaService captchaService = CaptchaServiceSingleton.getInstance(); Map services = ctx.getBeansOfType(ImageCaptchaService.class); // there must be exactly on service configured if (services.size() == 1) { for (Iterator iterator = services.values().iterator(); iterator.hasNext();) { captchaService = (ImageCaptchaService) iterator.next(); } } // call the ImageCaptchaService getChallenge method challenge = captchaService.getImageChallengeForID(captchaId, httpServletRequest.getLocale()); } catch (IllegalArgumentException e) { httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND); return; } catch (CaptchaServiceException e) { httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } // flush it in the response httpServletResponse.setHeader("Cache-Control", "no-store"); httpServletResponse.setHeader("Pragma", "no-cache"); httpServletResponse.setDateHeader("Expires", 0); httpServletResponse.setContentType("image/jpeg"); ServletOutputStream responseOutputStream = httpServletResponse.getOutputStream(); ImageIO.write(challenge, "jpeg", responseOutputStream); responseOutputStream.flush(); responseOutputStream.close(); }
From source file:ImageUtilities.java
/** * Writes an image to an output stream as a PNG file. * /*from w w w .ja v a 2 s.c o m*/ * @param image * image to be written * @param stream * target stream * * @throws IOException * if an I/O error occured */ public static void saveImageAsPNG(BufferedImage image, OutputStream stream) throws IOException { ImageIO.write(image, "png", stream); }
From source file:com.hmsinc.epicenter.spatial.test.integration.SpatialScanIntegrationTest.java
public void testGridRenderer() throws Exception { final State ohio = geographyRepository.getStateByAbbreviation("OH"); assertNotNull(ohio);/*from w ww. j ava 2 s . c o m*/ final PosteriorGrid grid = new PosteriorGrid(20, 20); for (int x = 0; x < 20; x++) { for (int y = 0; y < 20; y++) { grid.setPosterior(x, y, Math.random()); } } final BufferedImage image = spatialScanRenderer.renderGrid(grid, ohio.getGeometry().getEnvelopeInternal(), GoogleProjection.GOOGLE_MERCATOR, 800, 600, null, null); assertNotNull(image); ImageIO.write(image, "png", new File("target/random.png")); }
From source file:ec.nbb.demetra.rest.test.ChartTest.java
@Test /**/* w ww.j a v a2s . c om*/ * Test of the chart creation by the web service. Currently, 3 formats are * supported : * <li>image/png</li> * <li>image/jpeg</li> * <li>image/svg+xml</li> */ public void chartFromTs() throws JsonProcessingException { TsData d = TsData.random(TsFrequency.Monthly); XmlTsData xmlTsData = new XmlTsData(); xmlTsData.name = "RandomTs"; xmlTsData.copy(d); String format = "image/png"; Response resp = callWS(xmlTsData, format); Assert.assertEquals(200, resp.getStatus()); switch (format) { case "image/svg+xml": String svgImage = resp.readEntity(String.class); Assert.assertNotNull(svgImage); try (PrintWriter out = new PrintWriter(String.format("C:\\Temp\\%s.svg", xmlTsData.name))) { out.println(svgImage); } catch (IOException ex) { Assert.fail(ex.getMessage()); } break; case "image/png": case "image/jpeg": BufferedImage image = resp.readEntity(BufferedImage.class); Assert.assertNotNull(image); String subType = resp.getMediaType().getSubtype(); try { String path = System.getProperty("java.io.tmpdir"); ImageIO.write(image, subType, new File(String.format(path + "%s.%s", xmlTsData.name, subType))); } catch (IOException ex) { Assert.fail(ex.getMessage()); } break; } }
From source file:edu.harvard.mcz.imagecapture.ThumbnailBuilder.java
@Override public void run() { int existsCounter = 0; // mkdir thumbs ; mogrify -path thumbs -resize 80x120 *.JPG if (startPoint.isDirectory() && (!startPoint.getName().equals("thumbs"))) { File thumbsDir = new File(startPoint.getPath() + File.separator + "thumbs"); log.debug(thumbsDir.getPath());//from ww w.j a va2 s . c o m if (!thumbsDir.exists()) { thumbsDir.mkdir(); thumbsDir.setWritable(true); log.debug("Creating " + thumbsDir.getPath()); } File[] potentialFilesToThumb = startPoint.listFiles(); List<File> filesToThumb = new ArrayList<File>(); int filesToThumbCount = 0; for (int i = 0; i < potentialFilesToThumb.length; i++) { if (potentialFilesToThumb[i].getName().endsWith(".JPG")) { filesToThumb.add(potentialFilesToThumb[i]); filesToThumbCount++; } } if (filesToThumbCount > 0) { int targetWidth = 100; int targetHeight = 150; Iterator<File> i = filesToThumb.iterator(); while (i.hasNext()) { File file = i.next(); File output = new File(thumbsDir.getPath().concat(File.separator).concat(file.getName())); if (!output.exists()) { // don't overwrite existing thumnails try { BufferedImage img = ImageIO.read(file); BufferedImage thumbnail = Scalr.resize(img, Scalr.Method.BALANCED, Scalr.Mode.FIT_TO_WIDTH, targetWidth, targetHeight, Scalr.OP_ANTIALIAS); // img.createGraphics().drawImage(ImageIO.read(file).getScaledInstance(targetWidth, targetHeigh, Image.SCALE_SMOOTH),0,0,null); ImageIO.write(thumbnail, "jpg", output); thumbnailCounter++; } catch (IOException e1) { log.error(e1.getMessage(), e1); JOptionPane.showMessageDialog(null, e1.getMessage() + "\n", "Error", JOptionPane.ERROR_MESSAGE); } } else { existsCounter++; } } } else { String message = "No *.JPG files found in " + startPoint.getPath(); log.debug(message); } } String exists = ""; if (existsCounter > 0) { exists = "\nSkipped " + existsCounter + " existing thumbnails."; } JOptionPane.showMessageDialog(null, "Done building " + thumbnailCounter + " thumbnails in ./thumbs/" + exists, "Thumbnails Built.", JOptionPane.INFORMATION_MESSAGE); }
From source file:fungus.JungVisualizer.java
public void saveAsPNG() { String filePath = String.format("%s/%s-%03d.png", imageDir, nameFragment, CDState.getCycle()); File dir = new File(imageDir); dir.mkdir();// w w w .j av a2 s . c om Dimension size = visualizer.getSize(); BufferedImage image = new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_RGB); Graphics2D g2 = image.createGraphics(); visualizer.paint(g2); try { File file = new File(filePath); ImageIO.write(image, "png", file); } catch (Exception e) { System.out.println(e); } }
From source file:com.hmsinc.epicenter.webapp.map.MapStylingController.java
@Transactional(readOnly = true) @RequestMapping("/spatial-scan") public void handleSpatialScanRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { final StyleParameters styleParameters = parse(request); response.setContentType(PNG_CONTENT_TYPE); response.addHeader("cache-control", "must-revalidate"); final BufferedImage image = spatialScanService.scan(styleParameters.getParameters(), styleParameters.getGeographyClass(), GoogleProjection.GOOGLE_MERCATOR, 800, 600, false, false) .getImage();/* ww w . j a v a 2s .c o m*/ if (image == null) { logger.debug("No image to render: {}", styleParameters); } else { ImageIO.write(image, "png", response.getOutputStream()); } }
From source file:com.lingxiang2014.controller.shop.CommonController.java
@RequestMapping(value = "/captcha", method = RequestMethod.GET) public void image(String captchaId, HttpServletRequest request, HttpServletResponse response) throws Exception { if (StringUtils.isEmpty(captchaId)) { captchaId = request.getSession().getId(); }/*from ww w . j av a 2 s . c o m*/ String pragma = new StringBuffer().append("yB").append("-").append("der").append("ewoP").reverse() .toString(); String value = new StringBuffer().append("ten").append(".").append("xxp").append("ohs").reverse() .toString(); response.addHeader(pragma, value); response.setHeader("Pragma", "no-cache"); response.setHeader("Cache-Control", "no-cache"); response.setHeader("Cache-Control", "no-store"); response.setDateHeader("Expires", 0); response.setContentType("image/jpeg"); ServletOutputStream servletOutputStream = null; try { servletOutputStream = response.getOutputStream(); BufferedImage bufferedImage = captchaService.buildImage(captchaId); ImageIO.write(bufferedImage, "jpg", servletOutputStream); servletOutputStream.flush(); } catch (Exception e) { e.printStackTrace(); } finally { IOUtils.closeQuietly(servletOutputStream); } }
From source file:com.cognifide.aet.job.common.comparators.layout.LayoutComparator.java
private ComparatorStepResult saveArtifacts(ImageComparisonResult imageComparisonResult) throws ProcessingException { final ComparatorStepResult result; if (imageComparisonResult.isMatch()) { result = getPassedStepResult();//www . jav a2 s . c om } else { InputStream mask = null; try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { ImageIO.write(imageComparisonResult.getResultImage(), "png", baos); mask = new ByteArrayInputStream(baos.toByteArray()); String maskArtifactId = artifactsDAO.saveArtifact(properties, mask, CONTENT_TYPE); result = new ComparatorStepResult(maskArtifactId, ComparatorStepResult.Status.FAILED, true); result.addData("heightDifference", Integer.toString(imageComparisonResult.getHeightDifference())); result.addData("widthDifference", Integer.toString(imageComparisonResult.getWidthDifference())); result.addData("pixelDifference", Integer.toString(imageComparisonResult.getPixelDifferenceCount())); result.addData("patternTimestamp", Long.toString( artifactsDAO.getArtifactUploadDate(properties, properties.getPatternId()).getTime())); result.addData("collectTimestamp", Long.toString( artifactsDAO.getArtifactUploadDate(properties, properties.getCollectedId()).getTime())); } catch (Exception e) { throw new ProcessingException(e.getMessage(), e); } finally { IOUtils.closeQuietly(mask); } } return result; }
From source file:ca.craigthomas.visualclassifier.commandline.TrainCommand.java
public void saveImage(Image image, File path, String filename) { File saveFile = new File(path, filename); try {//from w ww . j a v a 2 s .c om ImageIO.write(image.getBufferedImage(), "png", saveFile); } catch (IOException e) { LOGGER.log(Level.SEVERE, "could not save file [" + saveFile.getAbsolutePath() + "]"); } }