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.yamj.core.service.file.FileStorageService.java
public void storeImage(String filename, StorageType type, BufferedImage bi, ImageFormat imageFormat, int quality) throws Exception { LOG.debug("Store {} {} image: {}", type, imageFormat, filename); String storageFileName = getStorageName(type, filename); File outputFile = new File(storageFileName); ImageWriter writer = null;// w ww . j a v a 2 s . c om FileImageOutputStream output = null; try { if (ImageFormat.PNG == imageFormat) { ImageIO.write(bi, "png", outputFile); } else { float jpegQuality = (float) quality / 100; BufferedImage bufImage = new BufferedImage(bi.getWidth(), bi.getHeight(), BufferedImage.TYPE_INT_RGB); bufImage.createGraphics().drawImage(bi, 0, 0, null, null); @SuppressWarnings("rawtypes") Iterator iter = ImageIO.getImageWritersByFormatName("jpeg"); writer = (ImageWriter) iter.next(); ImageWriteParam iwp = writer.getDefaultWriteParam(); iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); iwp.setCompressionQuality(jpegQuality); output = new FileImageOutputStream(outputFile); writer.setOutput(output); IIOImage image = new IIOImage(bufImage, null, null); writer.write(null, image, iwp); } } finally { if (writer != null) { writer.dispose(); } if (output != null) { try { output.close(); } catch (IOException ex) { LOG.trace("Failed to close stream: {}", ex.getMessage(), ex); } } } }
From source file:com.shending.support.CompressPic.java
/** * ?/*w ww .j a v a2s .c o m*/ * * @param srcFile * @param dstFile * @param widthRange * @param heightRange */ public static void cutSquare(String srcFile, String dstFile, int widthRange, int heightRange, int width, int height) { int x = 0; int y = 0; try { ImageInputStream iis = ImageIO.createImageInputStream(new File(srcFile)); Iterator<ImageReader> iterator = ImageIO.getImageReaders(iis); ImageReader reader = (ImageReader) iterator.next(); reader.setInput(iis, true); ImageReadParam param = reader.getDefaultReadParam(); int oldWidth = reader.getWidth(0); int oldHeight = reader.getHeight(0); int newWidth, newHeight; if (width <= oldWidth && height <= oldHeight) { newWidth = oldHeight * widthRange / heightRange; if (newWidth < oldWidth) { newHeight = oldHeight; x = (oldWidth - newWidth) / 2; } else { newWidth = oldWidth; newHeight = oldWidth * heightRange / widthRange; y = (oldHeight - newHeight) / 2; } Rectangle rectangle = new Rectangle(x, y, newWidth, newHeight); param.setSourceRegion(rectangle); BufferedImage bi = reader.read(0, param); BufferedImage tag = new BufferedImage((int) width, (int) height, BufferedImage.TYPE_INT_RGB); tag.getGraphics().drawImage(bi.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, null); File file = new File(dstFile); ImageIO.write(tag, reader.getFormatName(), file); } else { BufferedImage bi = reader.read(0, param); BufferedImage tag = new BufferedImage((int) width, (int) height, BufferedImage.TYPE_INT_RGB); Graphics2D g2d = tag.createGraphics(); g2d.setColor(Color.WHITE); g2d.fillRect(0, 0, tag.getWidth(), tag.getHeight()); g2d.drawImage(bi.getScaledInstance(bi.getWidth(), bi.getHeight(), Image.SCALE_SMOOTH), (width - bi.getWidth()) / 2, (height - bi.getHeight()) / 2, null); g2d.dispose(); File file = new File(dstFile); ImageIO.write(tag, reader.getFormatName(), file); } } catch (Exception e) { e.printStackTrace(); } }
From source file:com.piaoyou.util.ImageUtil.java
/** * @todo: xem lai ham nay, neu kich thuoc nho hon max thi ta luu truc tiep * inputStream xuong thumbnailFile luon * * This method create a thumbnail and reserve the ratio of the output image * NOTE: This method closes the inputStream after it have done its work. * * @param inputStream the stream of a jpeg file * @param outputStream the output stream * @param maxWidth the maximum width of the image * @param maxHeight the maximum height of the image * @throws IOException// w ww .j av a 2 s. co m * @throws BadInputException */ public static void createThumbnail(InputStream inputStream, OutputStream outputStream, int maxWidth, int maxHeight) throws IOException { if (inputStream == null) { throw new IllegalArgumentException("inputStream must not be null."); } if (outputStream == null) { throw new IllegalArgumentException("outputStream must not be null."); } //boolean useSun = false; if (maxWidth <= 0) { throw new IllegalArgumentException("maxWidth must >= 0"); } if (maxHeight <= 0) { throw new IllegalArgumentException("maxHeight must >= 0"); } try { //JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(inputStream); //BufferedImage srcImage = decoder.decodeAsBufferedImage(); byte[] srcByte = FileUtil.getBytes(inputStream); InputStream is = new ByteArrayInputStream(srcByte); //ImageIcon imageIcon = new ImageIcon(srcByte); //Image srcImage = imageIcon.getImage(); BufferedImage srcImage = ImageIO.read(is); if (srcImage == null) { throw new IOException("Cannot decode image. Please check your file again."); } int imgWidth = srcImage.getWidth(); int imgHeight = srcImage.getHeight(); // imgWidth or imgHeight could be -1, which is considered as an assertion AssertionUtil.doAssert((imgWidth > 0) && (imgHeight > 0), "Assertion: ImageUtil: cannot get the image size."); // Set the scale. AffineTransform tx = new AffineTransform(); if ((imgWidth > maxWidth) || (imgHeight > maxHeight)) { double scaleX = (double) maxWidth / imgWidth; double scaleY = (double) maxHeight / imgHeight; double scaleRatio = (scaleX < scaleY) ? scaleX : scaleY; imgWidth = (int) (imgWidth * scaleX); imgWidth = (imgWidth == 0) ? 1 : imgWidth; imgHeight = (int) (imgHeight * scaleY); imgHeight = (imgHeight == 0) ? 1 : imgHeight; // scale as needed tx.scale(scaleRatio, scaleRatio); } else {// we don't need any transform here, just save it to file and return outputStream.write(srcByte); return; } // create thumbnail image BufferedImage bufferedImage = new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_INT_RGB); Graphics2D g = bufferedImage.createGraphics(); boolean useTransform = false; if (useTransform) {// use transfrom to draw //log.trace("use transform"); g.drawImage(srcImage, tx, null); } else {// use java filter //log.trace("use filter"); Image scaleImage = getScaledInstance(srcImage, imgWidth, imgHeight); g.drawImage(scaleImage, 0, 0, null); } g.dispose();// free resource // write it to outputStream // JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(outputStream); // encoder.encode(bufferedImage); ImageIO.write(bufferedImage, "jpeg", outputStream); } catch (IOException e) { log.error("Error", e); throw e; } finally {// this finally is very important try { inputStream.close(); } catch (IOException e) { /* ignore */ e.printStackTrace(); } try { outputStream.close(); } catch (IOException e) {/* ignore */ e.printStackTrace(); } } }
From source file:com.netsteadfast.greenstep.bsc.command.KpiReportExcelCommand.java
private int putCharts(XSSFWorkbook wb, XSSFSheet sh, Context context) throws Exception { String pieBase64Content = SimpleUtils.getPNGBase64Content((String) context.get("pieCanvasToData")); String barBase64Content = SimpleUtils.getPNGBase64Content((String) context.get("barCanvasToData")); BufferedImage pieImage = SimpleUtils.decodeToImage(pieBase64Content); BufferedImage barImage = SimpleUtils.decodeToImage(barBase64Content); ByteArrayOutputStream pieBos = new ByteArrayOutputStream(); ImageIO.write(pieImage, "png", pieBos); pieBos.flush();//from www . ja va2 s .c om ByteArrayOutputStream barBos = new ByteArrayOutputStream(); ImageIO.write(barImage, "png", barBos); barBos.flush(); SimpleUtils.setCellPicture(wb, sh, pieBos.toByteArray(), 0, 0); SimpleUtils.setCellPicture(wb, sh, barBos.toByteArray(), 0, 6); return 25; }
From source file:org.drools.planner.benchmark.core.statistic.bestscore.BestScoreProblemStatistic.java
protected void writeGraphStatistic() { NumberAxis xAxis = new NumberAxis("Time spend"); xAxis.setNumberFormatOverride(new MillisecondsSpendNumberFormat()); NumberAxis yAxis = new NumberAxis("Score"); yAxis.setAutoRangeIncludesZero(false); XYPlot plot = new XYPlot(null, xAxis, yAxis, null); int seriesIndex = 0; for (SingleBenchmark singleBenchmark : problemBenchmark.getSingleBenchmarkList()) { BestScoreSingleStatistic singleStatistic = (BestScoreSingleStatistic) singleBenchmark .getSingleStatistic(problemStatisticType); XYSeries series = new XYSeries(singleBenchmark.getSolverBenchmark().getName()); for (BestScoreSingleStatisticPoint point : singleStatistic.getPointList()) { long timeMillisSpend = point.getTimeMillisSpend(); Score score = point.getScore(); Double scoreGraphValue = scoreDefinition.translateScoreToGraphValue(score); if (scoreGraphValue != null) { series.add(timeMillisSpend, scoreGraphValue); }// w w w . ja v a 2s. co m } XYSeriesCollection seriesCollection = new XYSeriesCollection(); seriesCollection.addSeries(series); plot.setDataset(seriesIndex, seriesCollection); XYItemRenderer renderer; // No direct lines between 2 points renderer = new XYStepRenderer(); if (singleStatistic.getPointList().size() <= 1) { // Workaround for https://sourceforge.net/tracker/?func=detail&aid=3387330&group_id=15494&atid=115494 renderer = new StandardXYItemRenderer(StandardXYItemRenderer.SHAPES); } plot.setRenderer(seriesIndex, renderer); seriesIndex++; } plot.setOrientation(PlotOrientation.VERTICAL); JFreeChart chart = new JFreeChart(problemBenchmark.getName() + " best score statistic", JFreeChart.DEFAULT_TITLE_FONT, plot, true); BufferedImage chartImage = chart.createBufferedImage(1024, 768); graphStatisticFile = new File(problemBenchmark.getProblemReportDirectory(), problemBenchmark.getName() + "BestScoreStatistic.png"); OutputStream out = null; try { out = new FileOutputStream(graphStatisticFile); ImageIO.write(chartImage, "png", out); } catch (IOException e) { throw new IllegalArgumentException("Problem writing graphStatisticFile: " + graphStatisticFile, e); } finally { IOUtils.closeQuietly(out); } }
From source file:org.iish.visualmets.controllers.ControllerResource.java
/** * Returns a thumbnail image//from w w w .j ava 2s.co m * * @param eadId ead ID * @param metsId mets ID * @param pageId show which page * @param width max. width of the thumbnail * @param height max. height of the thumbnail */ @RequestMapping(value = "/resource/thumbnail_image", method = RequestMethod.GET) public void getThumbnailImage( @RequestParam(value = "metsId", required = true) String metsId, @RequestParam(value = "eadId", required = false, defaultValue = "") String eadId, @RequestParam(value = "pageId", required = false, defaultValue = "1") int pageId, @RequestParam(value = "angle", required = false, defaultValue = "0") Integer angle, @RequestParam(value = "width", required = false, defaultValue = "160") float width, @RequestParam(value = "height", required = false, defaultValue = "160") float height, @RequestParam(value = "padding", required = false, defaultValue = "0") Integer padding, @RequestParam(value = "zoom", required = false, defaultValue = "100") Integer zoom, @RequestParam(value = "brightness", required = false, defaultValue = "0f") float brightness, @RequestParam(value = "contrast", required = false, defaultValue = "1f") float contrast, @RequestParam(value = "crop", required = false, defaultValue = "") String crop, @RequestParam(value = "callback", required = false) String callback, HttpServletResponse response) throws Exception, IOException { // @RequestParam(value = "eadId", required = true) String eadId, // DEZE ONDERDELEN MOETEN NOG GEMAAKT WORDEN // - left // - top // + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + // GET ORIGINAL SIZE IMAGE ImageItem imageInfo = getImageInfo(eadId, metsId, pageId, "thumbnail image"); BufferedImage img = cacheService.loadImage(imageInfo.getUrl()); // + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + // check min en max values for PADDING and ZOOM padding = checkMinMaxValue(padding, image_padding_min, image_padding_max); zoom = checkMinMaxValue(zoom, image_zoom_min, image_zoom_max); // RESCALE IMAGE double scaleWidth = width * zoom / 100; double scaleHeight = height * zoom / 100; img = imageTransformation.ScaleImage(img, (int) scaleWidth - (2 * padding), (int) scaleHeight - (2 * padding)); // + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + // BRIGHTNESS / CONTRAST // scale factor (contrast) (bv. 0 - zwart, 1 - default, 5 - heel licht) // offset (brightness) (bv. -100, -90, ..., -20, -10, 0, 10, 20, 90, 100) img = imageTransformation.ContrastBrightnessImage(img, contrast, brightness); // + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + // CROP IMAGE img = imageTransformation.CropImage(img, crop.trim()); // + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + // ROTATE IMAGE img = imageTransformation.RotateImage90DegreesStepsOnly(img, angle); // + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + // send to browser response.setContentType("image/jpeg"); ImageIO.write(img, "jpg", response.getOutputStream()); }
From source file:com.github.xmltopdf.JasperPdfGenerator.java
private void createDocument(List<String> templateNames, List<String> xmlFileNames, ByteArrayOutputStream os, DocType docType) {/*from w w w . jav a 2 s .c o m*/ List<JasperPrint> jasperPrints = new ArrayList<JasperPrint>(); InputStream fileIs = null; InputStream stringIs = null; if (!xmlFileNames.isEmpty()) { xmlTag = XMLDoc.from(MergeXml.merge(xmlFileNames), true); } try { for (String templateName : templateNames) { try { fileIs = new FileInputStream(templateNames.get(0)); String contents = applyVelocityTemplate(IOUtils.toString(fileIs, "UTF-8")); stringIs = IOUtils.toInputStream(contents, "UTF-8"); JasperReport jasperReport = JasperCompileManager.compileReport(stringIs); jasperPrints.add( JasperFillManager.fillReport(jasperReport, new HashMap(), new JREmptyDataSource())); } finally { IOUtils.closeQuietly(fileIs); IOUtils.closeQuietly(stringIs); } } JasperPrint jasperPrint = jasperPrints.get(0); for (int index = 1; index < jasperPrints.size(); index += 1) { List<JRPrintPage> pages = jasperPrints.get(index).getPages(); for (JRPrintPage page : pages) { jasperPrint.addPage(page); } } switch (docType) { case PDF: JasperExportManager.exportReportToPdfStream(jasperPrint, os); break; case RTF: JRRtfExporter rtfExporter = new JRRtfExporter(); rtfExporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint); rtfExporter.setParameter(JRExporterParameter.OUTPUT_STREAM, os); rtfExporter.setParameter(JRExporterParameter.CHARACTER_ENCODING, "UTF-8"); rtfExporter.exportReport(); break; case XLS: JRXlsExporter xlsExporter = new JRXlsExporter(); xlsExporter.setParameter(JRXlsExporterParameter.JASPER_PRINT, jasperPrint); xlsExporter.setParameter(JRXlsExporterParameter.OUTPUT_STREAM, os); xlsExporter.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET, Boolean.TRUE); // xlsExporter.setParameter(JRXlsExporterParameter.IS_AUTO_DETECT_CELL_TYPE, Boolean.TRUE); xlsExporter.setParameter(JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND, Boolean.FALSE); xlsExporter.setParameter(JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS, Boolean.TRUE); xlsExporter.exportReport(); break; case ODT: JROdtExporter odtExporter = new JROdtExporter(); odtExporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint); odtExporter.setParameter(JRExporterParameter.OUTPUT_STREAM, os); odtExporter.exportReport(); break; case PNG: BufferedImage pageImage = new BufferedImage((int) (jasperPrint.getPageWidth() * ZOOM_2X + 1), (int) (jasperPrint.getPageHeight() * ZOOM_2X + 1), BufferedImage.TYPE_INT_RGB); JRGraphics2DExporter exporter = new JRGraphics2DExporter(); exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint); exporter.setParameter(JRGraphics2DExporterParameter.GRAPHICS_2D, pageImage.getGraphics()); exporter.setParameter(JRGraphics2DExporterParameter.ZOOM_RATIO, ZOOM_2X); exporter.setParameter(JRExporterParameter.PAGE_INDEX, Integer.valueOf(0)); exporter.exportReport(); ImageIO.write(pageImage, "png", os); break; case HTML: JRHtmlExporter htmlExporter = new JRHtmlExporter(); htmlExporter.setParameter(JRHtmlExporterParameter.JASPER_PRINT, jasperPrint); htmlExporter.setParameter(JRHtmlExporterParameter.OUTPUT_STREAM, os); htmlExporter.setParameter(JRHtmlExporterParameter.IMAGES_URI, "img/"); htmlExporter.setParameter(JRHtmlExporterParameter.IMAGES_DIR, new java.io.File("img")); htmlExporter.setParameter(JRHtmlExporterParameter.IS_OUTPUT_IMAGES_TO_DIR, Boolean.TRUE); htmlExporter.setParameter(JRHtmlExporterParameter.ZOOM_RATIO, ZOOM_2X); htmlExporter.exportReport(); break; case DOCX: JRDocxExporter docxExporter = new JRDocxExporter(); docxExporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint); docxExporter.setParameter(JRExporterParameter.OUTPUT_STREAM, os); docxExporter.exportReport(); break; default: break; } } catch (Exception ex) { LOG.error(this, ex, ex.getMessage()); } finally { IOUtils.closeQuietly(os); } }
From source file:com.whty.transform.common.utils.TransformUtils.java
public static void pdfToPNG(String pdfPath, String pngPath) { PdfDecoder decode_pdf = new PdfDecoder(true); try {/* w ww . j ava 2s . c o m*/ decode_pdf.openPdfFile(pdfPath); BufferedImage img = decode_pdf.getPageAsImage(pageNumber); ImageIO.write(img, "png", new File(pngPath)); decode_pdf.closePdfFile(); } catch (PdfException e) { LOGGER.error(e.getMessage(), e); } catch (IOException e) { LOGGER.error(e.getMessage(), e); } }
From source file:edu.cornell.mannlib.vitro.webapp.controller.freemarker.ImageUploadThumbnailer.java
private byte[] encodeAsJpeg(BufferedImage image) throws IOException { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); ImageIO.write(image, "JPG", bytes); return bytes.toByteArray(); }
From source file:de.ailis.wlandsuite.WebExtract.java
/** * Extracts the sprites./*from w w w . j a v a 2s.c o m*/ * * @param sourceDirectory * The input directory * @param targetDirectory * The output directory * @throws IOException * When file operation fails. */ private void extractSprites(final File sourceDirectory, final File targetDirectory) throws IOException { // Extract tilesets final File imagesDirectory = new File(targetDirectory, "images"); imagesDirectory.mkdirs(); String filename = "ic0_9.wlf"; log.info("Reading " + filename); final Sprites sprites; InputStream stream = new FileInputStream(new File(sourceDirectory, filename)); try { sprites = Sprites.read(stream); } finally { stream.close(); } filename = "masks.wlf"; log.info("Reading " + filename); final Masks masks; stream = new FileInputStream(new File(sourceDirectory, filename)); try { masks = Masks.read(stream, 10); } finally { stream.close(); } final int scale = this.scaleFilter.getScaleFactor(); final BufferedImage out; final int outType = this.scaleFilter.getImageType(); if (outType == -1) out = new TransparentEgaImage(10 * 16 * scale, 16 * scale); else out = new BufferedImage(10 * 16 * scale, 16 * scale, BufferedImage.TYPE_INT_ARGB); log.info("Writing sprites"); for (int i = 0; i < 10; i++) { final BufferedImage sprite = this.scaleFilter.scale(sprites.getSprites().get(i)); final BufferedImage mask = this.scaleFilter.scale(masks.getMasks().get(i)); for (int x = 0; x < 16 * scale; x++) { for (int y = 0; y < 16 * scale; y++) { if (mask.getRGB(x, y) == Color.BLACK.getRGB()) out.setRGB(x + i * 16 * scale, y, sprite.getRGB(x, y)); } } } ImageIO.write(out, "png", new File(imagesDirectory, "sprites.png")); }