List of usage examples for java.awt.image BufferedImage createGraphics
public Graphics2D createGraphics()
From source file:de.tuttas.restful.SchuelerManager.java
private BufferedImage createResizedCopy(Image originalImage, int scaledWidth, int scaledHeight, boolean preserveAlpha) { int imageType = preserveAlpha ? BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB; BufferedImage scaledBI = new BufferedImage(scaledWidth, scaledHeight, imageType); Graphics2D g = scaledBI.createGraphics(); if (preserveAlpha) { g.setComposite(AlphaComposite.Src); }/* w w w. j a v a2 s . c o m*/ g.drawImage(originalImage, 0, 0, scaledWidth, scaledHeight, null); g.dispose(); return scaledBI; }
From source file:info.magnolia.cms.taglibs.util.TextToImageTag.java
/** * Create an image file that is a scaled version of the original image * @param the original BufferedImage//w w w . ja v a2s. co m * @param the scale factor * @return the new BufferedImage */ private BufferedImage scaleImage(BufferedImage oriImgBuff, double scaleFactor) { // get the dimesnions of the original image int oriWidth = oriImgBuff.getWidth(); int oriHeight = oriImgBuff.getHeight(); // get the width and height of the new image int newWidth = new Double(oriWidth * scaleFactor).intValue(); int newHeight = new Double(oriHeight * scaleFactor).intValue(); // create the thumbnail as a buffered image Image newImg = oriImgBuff.getScaledInstance(newWidth, newHeight, Image.SCALE_AREA_AVERAGING); BufferedImage newImgBuff = new BufferedImage(newImg.getWidth(null), newImg.getHeight(null), BufferedImage.TYPE_INT_RGB); Graphics2D g = newImgBuff.createGraphics(); g.drawImage(newImg, 0, 0, null); g.dispose(); // return the newImgBuff return newImgBuff; }
From source file:it.lufraproini.cms.servlet.upload_user_img.java
private Boolean creaThumbnail(Immagine img, Map info) { String cartella_img = getServletContext().getInitParameter("system.image_directory"); String file_img = img.getFile().substring(img.getFile().indexOf("/")); String path_img = getServletContext().getRealPath(cartella_img); String cartella_thumb = getServletContext().getInitParameter("system.thumb_directory"); String path_thumb = getServletContext().getRealPath(cartella_thumb); int altezza_thumb = 250; int larghezza_thumb = 250; BufferedImage thumb = new BufferedImage(larghezza_thumb, altezza_thumb, BufferedImage.TYPE_INT_RGB); String file_thumb = info.get("digest") + "." + info.get("estensione"); try {/*from www . ja v a 2s. c om*/ if (ImageIO.read(new File(path_img + file_img)).getWidth() >= larghezza_thumb) { thumb.createGraphics().drawImage(ImageIO.read(new File(path_img + file_img)).getScaledInstance(-1, altezza_thumb, Image.SCALE_SMOOTH), 0, 0, null); } else { thumb.createGraphics().drawImage(ImageIO.read(new File(path_img + file_img)) .getScaledInstance(larghezza_thumb, altezza_thumb, Image.SCALE_SMOOTH), 0, 0, null); } ImageIO.write(thumb, info.get("estensione").toString(), new File(path_thumb + File.separatorChar + info.get("digest") + "." + info.get("estensione"))); } catch (IOException ex) { return false; } img.setThumb(cartella_thumb + File.separatorChar + file_thumb); return true; }
From source file:com.stanley.captioner.Transcriber.java
public void start() { // Create stream speech recognizer. StreamSpeechRecognizer recognizer = null; try {/* w w w .j ava2s . c o m*/ recognizer = new StreamSpeechRecognizer(config); } catch (IOException e) { System.out.println("Failed to create recognizer."); } // Open print writer for writing text output. PrintWriter writer = null; try { writer = new PrintWriter(textOut); } catch (FileNotFoundException e) { System.out.println("Failed to create print writer."); } // Open stream for first pass. InputStream stream = null; try { stream = new FileInputStream(audio); } catch (FileNotFoundException e) { System.out.println("Failed to stream file."); } // Initialize loop variables. SpeechResult result; int resultCount = 0; Stats stats = recognizer.createStats(1); // Start recognizer for first pass. recognizer.startRecognition(stream); System.out.println("First pass (stats collection) started."); // First pass loop to collect statistics for model adaptation. while ((result = recognizer.getResult()) != null) { try { stats.collect(result); } catch (Exception e) { System.out.println("Failed to collect stats."); } resultCount++; // Toggle for testing. if (quickTest && resultCount > 5) { break; } } // Close recognizer (end of first pass). recognizer.stopRecognition(); System.out.println("Stats collection stopped."); // Transform model using model adaptation. Transform transform = stats.createTransform(); recognizer.setTransform(transform); // Reopen stream for second pass. stream = null; try { stream = new FileInputStream(audio); } catch (FileNotFoundException e) { System.out.println("Failed to stream file."); } // Start recognizer for second pass. recognizer.startRecognition(stream); System.out.println("Second pass started."); // Create output text file header. writer.printf("%-20s", "WORD:"); writer.printf("%20s", "CONFIDENCE:"); writer.printf("%20s", "START TIME:"); writer.printf("%20s", "END_TIME:"); writer.println(); for (int i = 0; i < 80; i++) { writer.print("-"); } writer.println(); // Initialize loop variables. int wordCount = 0; String sentence = ""; int sentenceLength = 0; long sentenceStart = 0; long sentenceEnd = 0; ArrayList<Sentence> sentences = new ArrayList<>(); // Second pass loop to calculate sentences. RECOG: while ((result = recognizer.getResult()) != null) { for (WordResult wordResult : result.getWords()) { wordCount++; String word = wordResult.getWord().toString(); double confidence = wordResult.getConfidence(); long startTime = wordResult.getTimeFrame().getStart(); long endTime = wordResult.getTimeFrame().getEnd(); writer.printf("%-20s", word); writer.printf("%20.1f", confidence); writer.printf("%20d", startTime); writer.printf("%20d", endTime); writer.println(); if (sentenceLength + word.length() < 40) { // Add to current sentence. sentence += " " + word; sentenceLength += word.length(); sentenceEnd = endTime; } else { // End of current sentence, store and start a new one. sentences.add(new Sentence(sentence, sentenceStart, sentenceEnd)); sentenceStart = sentenceEnd; sentence = ""; sentenceLength = 0; } // Toggle for testing. if (quickTest && wordCount > 50) { break RECOG; } } } // Close print writer and recognizer (end of second pass). writer.close(); recognizer.stopRecognition(); System.out.println("Second pass stopped."); // Create folder for caption images. String imageDirPath = FilenameUtils.concat(textOut.getParent(), FilenameUtils.getBaseName(textOut.getAbsolutePath())); System.out.println(imageDirPath); File imageDir = new File(imageDirPath); if (!imageDir.exists()) { // Create the folder if it doesn't already exist. imageDir.mkdir(); } // Calculate video output path. String videoOutPath = FilenameUtils.concat(textOut.getParent(), FilenameUtils.getBaseName(textOut.getAbsolutePath()) + ".mp4"); System.out.println(videoOutPath); // Initialize a command string for overlaying the captions. String commandString = String.format("%s -y -loglevel quiet -i %s", new Converter().getFFmpegPath(), videoIn.getAbsolutePath()); System.out.println(commandString); // Initialize a complex filter for overlaying the captions. String filterString = "-filter_complex"; // Acquire a probe object for collecting video details. Converter converter = new Converter(); FFprobe ffprobe = null; try { ffprobe = new FFprobe(converter.getFFprobePath()); } catch (IOException e) { System.out.println("Failed to find ffprobe."); } // Probe the video for details. FFmpegProbeResult probeResult = null; try { probeResult = ffprobe.probe(videoIn.getAbsolutePath()); } catch (IOException e) { System.out.println("Failed to probe video file."); } // Get the width and height of the video. FFmpegStream videoStream = probeResult.getStreams().get(0); int videoWidth = videoStream.width; int videoHeight = videoStream.height; // Calculate the x and y coordinates of the captions. int captionX = (videoWidth / 2) - 220; int captionY = videoHeight - 25 - 10; // Loop over the sentences, generate captions, and build command string. int k = 0; for (Sentence s : sentences) { // Create caption image from sentence. BufferedImage bi = new BufferedImage(440, 50, BufferedImage.TYPE_INT_ARGB); Graphics2D g = bi.createGraphics(); g.setPaint(new Color(0, 0, 0, 128)); g.fillRect(0, 0, 440, 50); g.setPaint(new Color(255, 255, 255, 255)); g.setFont(new Font("Serif", Font.BOLD, 20)); FontMetrics fm = g.getFontMetrics(); int x = bi.getWidth() - fm.stringWidth(s.text) - 5; int y = fm.getHeight() - 5; g.drawString(s.text, x, y); g.dispose(); // Write the image to file for future reference. String suffix = String.format("caption-%03d.png", k); String imagePath = FilenameUtils.concat(imageDirPath, suffix); try { File imageFile = new File(imagePath); ImageIO.write(bi, "png", imageFile); } catch (IOException e) { System.out.println("Failed to write caption image to file."); } // Add the caption image path to the command string. commandString += " -i " + imagePath; // Add an entry to the complex filter with the caption timeframe. if (k == 0) { filterString += String.format(" \"[0:v][1:v] overlay=%d:%d:enable='between(t,%d,%d)'%s", captionX, captionY, s.startTime / 1000, s.endTime / 1000, (k == sentences.size() - 1) ? "\"" : " [tmp];"); } else { filterString += String.format(" [tmp][%d:v] overlay=%d:%d:enable='between(t,%d,%d)'%s", k + 1, captionX, captionY, s.startTime / 1000, s.endTime / 1000, (k == sentences.size() - 1) ? "\"" : " [tmp];"); } k++; } // Build final command string. String finalCommand = String.format("%s %s -codec:a copy %s", commandString, filterString, videoOutPath); System.out.println(finalCommand); // Attempt to run the final command string to embed the captions. try { Process p = Runtime.getRuntime().exec(finalCommand); try { if (p.waitFor() != 0) { // Embedding the captions failed. System.out.println("Image overlay failed."); } } catch (InterruptedException e) { // Embedding the captions was interrupted. System.out.println("Interrupted image overlay."); } } catch (IOException e) { // Command string failed to execute. System.out.println("Failed to execute image overlay."); } // Delete intermediate audio file. audio.delete(); System.out.println("........................CAPTIONING COMPLETE........................"); }
From source file:net.java.sip.communicator.impl.osdependent.jdic.SystrayServiceJdicImpl.java
private BufferedImage createOverlayImage(String text) { int size = 16; BufferedImage image = new BufferedImage(size, size, BufferedImage.TYPE_INT_ARGB); Graphics2D g = image.createGraphics(); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); //background// w w w . ja v a 2 s . com g.setPaint(new Color(0, 0, 0, 102)); g.fillRoundRect(0, 0, size, size, size, size); //filling int mainRadius = 14; g.setPaint(new Color(255, 98, 89)); g.fillRoundRect(size / 2 - mainRadius / 2, size / 2 - mainRadius / 2, mainRadius, mainRadius, size, size); //text Font font = g.getFont(); g.setFont(new Font(font.getName(), Font.BOLD, 9)); FontMetrics fontMetrics = g.getFontMetrics(); int textWidth = fontMetrics.stringWidth(text); g.setColor(Color.white); g.drawString(text, size / 2 - textWidth / 2, size / 2 - fontMetrics.getHeight() / 2 + fontMetrics.getAscent()); return image; }
From source file:org.nekorp.workflow.desktop.servicio.reporte.orden.servicio.OrdenServicioDataFactory.java
private String generaImagenCombustible(double porcentaje) { try {/*from w w w . jav a 2 s .c o m*/ int width = 186 * 3; int height = 15 * 3; IndicadorBarraGraphicsView view = new IndicadorBarraGraphicsView(); view.setWidthBar(width); view.setHeightBar(height); view.setPorcentaje(porcentaje); BufferedImage off_Image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics2D g2 = off_Image.createGraphics(); g2.setColor(Color.WHITE); g2.fillRect(0, 0, width, height); view.paint(g2); File file = new File("data/nivelCombustible.jpg"); saveJPG(off_Image, file); return file.getCanonicalPath(); } catch (IOException ex) { throw new RuntimeException(ex); } }
From source file:com.esri.ArcGISController.java
@RequestMapping(value = "/rest/services/InfoUSA/MapServer/export", method = { RequestMethod.GET, RequestMethod.POST })/*w ww . j a v a 2 s. c o m*/ public void doExport(@RequestParam("bbox") final String bbox, @RequestParam(value = "size", required = false) final String size, @RequestParam(value = "layerDefs", required = false) final String layerDefs, @RequestParam(value = "transparent", required = false) final String transparent, final HttpServletResponse response) throws IOException { double xmin = -1.0, ymin = -1.0, xmax = 1.0, ymax = 1.0; if (bbox != null && bbox.length() > 0) { final String[] tokens = m_patternComma.split(bbox); if (tokens.length == 4) { xmin = Double.parseDouble(tokens[0]); ymin = Double.parseDouble(tokens[1]); xmax = Double.parseDouble(tokens[2]); ymax = Double.parseDouble(tokens[3]); } else { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "bbox is not in the form xmin,ymin,xmax,ymax"); return; } } else { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "bbox is null or empty"); return; } final double xdel = xmax - xmin; final double ydel = ymax - ymin; int imageWidth = 400; int imageHeight = 400; if (size != null && size.length() > 0) { final String[] tokens = m_patternComma.split(size); if (tokens.length == 2) { imageWidth = Integer.parseInt(tokens[0], 10); imageHeight = Integer.parseInt(tokens[1], 10); } else { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "size is not in the form width,height"); return; } } String where = null; double lo = Double.NaN; double hi = Double.NaN; int[] ramp = null; if (layerDefs != null) { final String[] tokens = m_patternSemiColon.split(layerDefs); for (final String token : tokens) { final String[] keyval = m_patternEqual.split(token.substring(2)); if (keyval.length == 2) { final String key = keyval[0]; final String val = keyval[1]; if ("lo".equalsIgnoreCase(key)) { lo = "NaN".equalsIgnoreCase(val) ? Double.NaN : Double.parseDouble(val); } else if ("hi".equalsIgnoreCase(key)) { hi = "NaN".equalsIgnoreCase(val) ? Double.NaN : Double.parseDouble(val); } else if ("ramp".equalsIgnoreCase(key)) { ramp = parseRamp(val); } else if ("where".equalsIgnoreCase(key)) { where = val; } } } } if (ramp == null) { ramp = new int[] { 0xFFFFFF, 0x000000 }; } final Range range = new Range(); final Map<Long, Double> map = query(where, xmin, ymin, xmax, ymax, range); if (!Double.isNaN(lo)) { range.lo = lo; } if (!Double.isNaN(hi)) { range.hi = hi; } range.dd = range.hi - range.lo; final int typeIntRgb = "true".equalsIgnoreCase(transparent) ? BufferedImage.TYPE_INT_ARGB : BufferedImage.TYPE_INT_RGB; BufferedImage bufferedImage = new BufferedImage(imageWidth, imageHeight, typeIntRgb); final Graphics2D graphics = bufferedImage.createGraphics(); try { graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); graphics.setBackground(new Color(0, 0, 0, 0)); drawCells(graphics, imageWidth, imageHeight, xmin, ymin, xdel, ydel, range, ramp, map.entrySet()); } finally { graphics.dispose(); } // bufferedImage = m_op.filter(bufferedImage, null); final ByteArrayOutputStream baos = new ByteArrayOutputStream(10 * 1024); ImageIO.write(bufferedImage, "PNG", baos); response.setStatus(HttpServletResponse.SC_OK); response.setContentType("image/png"); response.setContentLength(baos.size()); baos.writeTo(response.getOutputStream()); response.getOutputStream().flush(); }
From source file:de.fhg.igd.mapviewer.server.wms.overlay.WMSTileOverlay.java
/** * @see AbstractTileOverlayPainter#repaintTile(int, int, int, int, * PixelConverter, int)//from www . jav a2 s. c om */ @Override public BufferedImage repaintTile(int posX, int posY, int width, int height, PixelConverter converter, int zoom) { // the first converter isn't regarded as a new converter because it's // always the empty map boolean isNewConverter = lastConverter != null && !converter.equals(lastConverter); lastConverter = converter; if (!converter.supportsBoundingBoxes()) { if (isNewConverter) { handleError(Messages.WMSTileOverlay_0 + configuration.getName() + Messages.WMSTileOverlay_1); } return null; } synchronized (this) { if (capabilities == null) { try { capabilities = WMSUtil.getCapabilities(configuration.getBaseUrl()); } catch (WMSCapabilitiesException e) { log.error("Error getting WMS capabilities"); //$NON-NLS-1$ } } } if (capabilities != null) { int mapEpsg = converter.getMapEpsg(); WMSBounds box; synchronized (this) { if (capabilities.getSupportedSRS().contains("EPSG:" + mapEpsg)) { //$NON-NLS-1$ // same SRS supported } else { // SRS not supported if (isNewConverter) { StringBuilder message = new StringBuilder(); message.append(Messages.WMSTileOverlay_2); message.append(configuration.getName()); message.append(Messages.WMSTileOverlay_3); boolean init = true; for (String srs : capabilities.getSupportedSRS()) { if (init) { init = false; } else { message.append(", "); //$NON-NLS-1$ } message.append(srs); } handleError(message.toString()); } return null; } box = WMSUtil.getBoundingBox(capabilities, mapEpsg); } String srs = box.getSRS(); if (srs.startsWith("EPSG:")) { //$NON-NLS-1$ // determine format String format = null; Iterator<String> itFormat = supportedFormats.iterator(); synchronized (this) { while (format == null && itFormat.hasNext()) { String supp = itFormat.next(); if (capabilities.getFormats().contains(supp)) { format = supp; } } } if (format == null) { // no compatible format return null; } try { // check if tile lies within the bounding box int epsg = Integer.parseInt(srs.substring(5)); GeoPosition topLeft = converter.pixelToGeo(new Point(posX, posY), zoom); GeoPosition bottomRight = converter.pixelToGeo(new Point(posX + width, posY + height), zoom); // WMS bounding box BoundingBox wms = new BoundingBox(box.getMinX(), box.getMinY(), -1, box.getMaxX(), box.getMaxY(), 1); GeoConverter geotools = GeotoolsConverter.getInstance(); GeoPosition bbTopLeft = geotools.convert(topLeft, epsg); GeoPosition bbBottomRight = geotools.convert(bottomRight, epsg); double minX = Math.min(bbTopLeft.getX(), bbBottomRight.getX()); double minY = Math.min(bbTopLeft.getY(), bbBottomRight.getY()); double maxX = Math.max(bbTopLeft.getX(), bbBottomRight.getX()); double maxY = Math.max(bbTopLeft.getY(), bbBottomRight.getY()); BoundingBox tile = new BoundingBox(minX, minY, -1, maxX, maxY, 1); // check if bounding box and tile overlap if (wms.intersectsOrCovers(tile) || tile.covers(wms)) { WMSBounds bounds; if (epsg == mapEpsg) { bounds = new WMSBounds(srs, minX, minY, maxX, maxY); } else { // determine bounds for request minX = Math.min(topLeft.getX(), bottomRight.getX()); minY = Math.min(topLeft.getY(), bottomRight.getY()); maxX = Math.max(topLeft.getX(), bottomRight.getX()); maxY = Math.max(topLeft.getY(), bottomRight.getY()); bounds = new WMSBounds("EPSG:" + mapEpsg, minX, minY, maxX, maxY); //$NON-NLS-1$ } URI uri; synchronized (this) { uri = WMSUtil.getMapURI(capabilities, configuration, width, height, bounds, null, format, true); } Proxy proxy = ProxyUtil.findProxy(uri); InputStream in = uri.toURL().openConnection(proxy).getInputStream(); BufferedImage image = GraphicsUtilities.loadCompatibleImage(in); // apply transparency to the image BufferedImage result = GraphicsUtilities.createCompatibleTranslucentImage(image.getWidth(), image.getHeight()); Graphics2D g = result.createGraphics(); try { AlphaComposite ac = AlphaComposite.getInstance(AlphaComposite.SRC, 0.5f); g.setComposite(ac); g.drawImage(image, 0, 0, null); } finally { g.dispose(); } return result; } } catch (Throwable e) { log.warn("Error painting WMS overlay", e); //$NON-NLS-1$ } } } return null; }
From source file:com.celements.photo.image.GenerateThumbnail.java
BufferedImage convertImageToBufferedImage(Image thumbImg, String watermark, String copyright, Color defaultBg) { BufferedImage thumb = new BufferedImage(thumbImg.getWidth(null), thumbImg.getHeight(null), BufferedImage.TYPE_INT_ARGB); Graphics2D g2d = thumb.createGraphics(); if (defaultBg != null) { g2d.setColor(defaultBg);//from w ww . j av a2 s . co m g2d.fillRect(0, 0, thumbImg.getWidth(null), thumbImg.getHeight(null)); } g2d.drawImage(thumbImg, 0, 0, null); if ((watermark != null) && (!watermark.equals(""))) { drawWatermark(watermark, g2d, thumb.getWidth(), thumb.getHeight()); } if ((copyright != null) && (!copyright.equals(""))) { drawCopyright(copyright, g2d, thumb.getWidth(), thumb.getHeight()); } mLogger.info("thumbDimensions: " + thumb.getHeight() + "x" + thumb.getWidth()); return thumb; }