List of usage examples for java.awt FontMetrics getHeight
public int getHeight()
From source file:com.stanley.captioner.Transcriber.java
public void start() { // Create stream speech recognizer. StreamSpeechRecognizer recognizer = null; try {/*from w w w .j a v a 2s .c om*/ 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:edu.ku.brc.ui.dnd.SimpleGlassPane.java
@Override protected void paintComponent(Graphics graphics) { Graphics2D g = (Graphics2D) graphics; Rectangle rect = getInternalBounds(); int width = rect.width; int height = rect.height; if (useBGImage) { // Create a translucent intermediate image in which we can perform // the soft clipping GraphicsConfiguration gc = g.getDeviceConfiguration(); if (img == null || img.getWidth() != width || img.getHeight() != height) { img = gc.createCompatibleImage(width, height, Transparency.TRANSLUCENT); }//from w ww.j a va2 s . c om Graphics2D g2 = img.createGraphics(); // Clear the image so all pixels have zero alpha g2.setComposite(AlphaComposite.Clear); g2.fillRect(0, 0, width, height); g2.setComposite(AlphaComposite.Src); g2.setColor(new Color(0, 0, 0, 85)); g2.fillRect(0, 0, width, height); if (delegateRenderer != null) { delegateRenderer.render(g, g2, img); } g2.dispose(); // Copy our intermediate image to the screen g.drawImage(img, rect.x, rect.y, null); } super.paintComponent(graphics); if (StringUtils.isNotEmpty(text)) { Graphics2D g2 = (Graphics2D) graphics; g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.setColor(fillColor); g2.fillRect(margin.left, margin.top, rect.width, rect.height); g2.setFont(new Font((new JLabel()).getFont().getName(), Font.BOLD, pointSize)); FontMetrics fm = g2.getFontMetrics(); int tw = fm.stringWidth(text); int th = fm.getHeight(); int tx = (rect.width - tw) / 2; int ty = (rect.height - th) / 2; if (yPos != null) { ty = yPos; } int expand = 20; int arc = expand * 2; g2.setColor(new Color(0, 0, 0, 50)); int x = margin.left + tx - (expand / 2); int y = margin.top + ty - fm.getAscent() - (expand / 2); drawBGContainer(g2, true, x + 4, y + 6, tw + expand, th + expand, arc, arc); g2.setColor(new Color(255, 255, 255, 220)); drawBGContainer(g2, true, x, y, tw + expand, th + expand, arc, arc); g2.setColor(Color.DARK_GRAY); drawBGContainer(g2, false, x, y, tw + expand, th + expand, arc, arc); g2.setColor(textColor == null ? Color.BLACK : textColor); g2.drawString(text, tx, ty); } }
From source file:org.squidy.designer.zoom.impl.InformationShape.java
private void initPane() { // Add Zoomable Component new Thread(new Runnable() { public void run() { // ProgressIndicator indicator = new // ProgressIndicator(InformationShape.this); if (informationSource == null || "".equals(informationSource)) { return; }// w w w.j a va 2 s . c om try { if (informationSource.endsWith(".pdf")) { url = InformationShape.class.getResource(informationSource); } else if (informationSource.endsWith(".html")) { try { url = new URL(informationSource); } catch (Exception e) { url = InformationShape.class.getResource(informationSource); } } else { url = new URL(informationSource); } } catch (Exception e) { // do nothing } PNode cropNode; // PDF if (informationSource.endsWith(".pdf")) { if (LOG.isDebugEnabled()) { LOG.debug("Display information as PDF."); } cropNode = new PDFPane(url.getFile()); } // HTML else { if (LOG.isDebugEnabled()) { LOG.debug("Display information as HTML."); } if (informationSource.startsWith("http") || informationSource.endsWith(".html")) { XHTMLPanel xhtmlPanel = new XHTMLPanel(); try { xhtmlPanel.setDocument(url.toURI().toString()); } catch (URISyntaxException e) { // TODO Auto-generated catch block e.printStackTrace(); } xhtmlPanel.setPreferredSize(new Dimension(800, 800)); // xhtmlPanel.addPropertyChangeListener("preferredSize", new PropertyChangeListener() { // // public void propertyChange(PropertyChangeEvent evt) { // cropScroll.updateScroller(); // cropNode. // } // }); cropNode = JComponentWrapper.create(xhtmlPanel); } else { JEditorPane editorPane = new JEditorPane(); editorPane.setFont(internalFont.deriveFont(10f)); FontMetrics fm = editorPane.getFontMetrics(editorPane.getFont()); int editorWidth = 400; editorPane.setPreferredSize(new Dimension(editorWidth, FontUtils.getLineCount(informationSource, editorWidth) * fm.getHeight())); cropNode = JComponentWrapper.create(editorPane); editorPane.setEditable(false); editorPane.setText(informationSource); } // Prepare HTML Kit // HTMLParser editorKit = new HTMLParser(); // HTMLParserCallback callback = new // HTMLParserCallback(); // getComponentEditorPane().setEditorKit(editorKit); // //Open connection // InputStreamReader reader = new // InputStreamReader(url.openStream()); // //Start parse process // editorKit.getParser().parse(reader, callback, true); // Wait until parsing process has finished // try { // Thread.sleep(2000); // } // catch (InterruptedException e) { // if (LOG.isErrorEnabled()) { // LOG.error("Error in " + // InformationShape.class.getName() + ".", e); // } // } } cropScroll = new CropScroll(cropNode, new Dimension(1000, 700), 0.2); cropScroll.setOffset( getBoundsReference().getCenterX() - cropScroll.getBoundsReference().getCenterX(), 250); addChild(cropScroll); invalidateFullBounds(); invalidateLayout(); invalidatePaint(); // indicator.done(); } }).start(); }
From source file:edu.ku.brc.specify.ui.containers.ContainerTreeRenderer.java
@Override protected void paintComponent(Graphics g) { super.paintComponent(g); Dimension d = getSize();/*from w w w . ja v a 2s .com*/ //System.out.println("d: "+d+" "+g.getClipBounds()); Graphics2D g2d = (Graphics2D) g.create(); g2d.setRenderingHints(renderingHints); FontMetrics fm = g2d.getFontMetrics(); int imgY = img1 != null ? (d.height - 24) / 2 : 0; int imgY2 = img1 != null ? (d.height - 16) / 2 : 0; int txtY = ((d.height - fm.getHeight()) / 2) + fm.getAscent(); int x = 0; Color color = g2d.getColor(); if (img1 != null) { g2d.drawImage(img1.getImage(), x, imgY, null); x += img1.getIconWidth(); } int iconInx = 0; if (txt1 != null) { x += getIconTextGap(); g2d.setColor(getForeground()); g.drawString(txt1, x, txtY); x += fm.stringWidth(txt1); g2d.setColor(color); } if (isContainer) { //if (isSelected && isEditable) //{ // x += drawIcon(g2d, x, imgY2, delImgIcon, iconInx++); // Delete the container //} if (hasColObj) { if (img2 != null) { x += 1; x += iconSep; g2d.drawImage(img2.getImage(), x, imgY2, null); x += img2.getIconWidth(); } if (txt2 != null) { x += getIconTextGap(); g2d.setColor(getForeground()); g.drawString(txt2, x, txtY); x += fm.stringWidth(txt2); g2d.setColor(color); } if (isSelected) { x += iconSep; x += drawIcon(g2d, x, imgY2, viewImgIcon, iconInx++); if (isEditable) { x += drawIcon(g2d, x, imgY2, delImgIcon, iconInx++); } } } else if (isSelected) // No Col Obj { x += iconSep; x += drawIcon(g2d, x, imgY2, schImgIcon, iconInx++); x += drawIcon(g2d, x, imgY2, addImgIcon, iconInx++); } } else if (isSelected) { x += iconSep; x += drawIcon(g2d, x, imgY2, viewImgIcon, iconInx++); // View for Collection Object //if (!isViewMode) //{ // x += iconSep; // x += drawIcon(g2d, x, imgY2, delImgIcon, iconInx++); // Delete for Collection Object //} } g2d.dispose(); }
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//from w w w.jav a 2s .c o m 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:Main.java
public Component getListCellRendererComponent(final JList list, final Object value, final int index, final boolean isSelected, final boolean cellHasFocus) { return new JPanel() { public void paintComponent(Graphics g) { super.paintComponent(g); Font font = (Font) value; String text = font.getFamily(); FontMetrics fm = g.getFontMetrics(font); g.setColor(isSelected ? list.getSelectionBackground() : list.getBackground()); g.fillRect(0, 0, getWidth(), getHeight()); g.setColor(isSelected ? list.getSelectionForeground() : list.getForeground()); g.setFont(font);/*from w ww . java2 s. c om*/ g.drawString(text, 0, fm.getAscent()); } public Dimension getPreferredSize() { Font font = (Font) value; String text = font.getFamily(); Graphics g = getGraphics(); FontMetrics fm = g.getFontMetrics(font); return new Dimension(fm.stringWidth(text), fm.getHeight()); } }; }
From source file:edu.ku.brc.ui.ImageDisplay.java
@Override protected void paintComponent(Graphics g) { super.paintComponent(g); boolean doScale = true; int w = getWidth(); int h = getHeight(); Image dspImg = image;/*from ww w . ja v a 2s . c o m*/ boolean doDisplayImage = (image != null && (!isNoAttachment && status == kImageOK)) || isLoading; if (isLoading) { doDisplayImage = true; dspImg = IconManager.getImage("Loading").getImage(); } if (doDisplayImage && dspImg != null) { int imgW = dspImg.getWidth(null); int imgH = dspImg.getHeight(null); if (doScale && (imgW > w || imgH > h)) { double scaleW = 1.0; double scaleH = 1.0; double scale = 1.0; if (imgW > w) { scaleW = (double) w / imgW; } if (imgH > h) { scaleH = (double) h / imgH; } scale = Math.min(scaleW, scaleH); imgW = (int) (imgW * scale); imgH = (int) (imgH * scale); } int x = 0; int y = 0; if (imgW < w) { x = (w - imgW) / 2; } if (imgH < h) { y = (h - imgH) / 2; } g.drawImage(dspImg, x, y, imgW, imgH, null); } else if (doShowText) { GraphicsUtils.turnOnAntialiasedDrawing(g); String[] label = this.isNoAttachment ? (isFullImage ? noAttachmentStr : noThumnailStr) : loadingAttachmentStr; FontMetrics fm = g.getFontMetrics(); int spacing = 2; int yOffset = (h - (fm.getHeight() + spacing) * label.length) / 2; if (yOffset < 0) yOffset = 0; int y = yOffset + fm.getHeight(); for (String str : label) { g.drawString(str, (w - fm.stringWidth(str)) / 2, y); y += fm.getHeight() + 2; } } }
From source file:org.fcrepo.localservices.imagemanip.ImageManipulation.java
/** * Method automatically called by browser to handle image manipulations. * //ww w .j a v a 2s .c o m * @param req * Browser request to servlet res Response sent back to browser after * image manipulation * @throws IOException * If an input or output exception occurred ServletException If a * servlet exception occurred */ @Override public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { System.setProperty("java.awt.headless", "true"); // collect all possible parameters for servlet String url = req.getParameter("url"); String op = req.getParameter("op"); String newWidth = req.getParameter("newWidth"); String brightAmt = req.getParameter("brightAmt"); String zoomAmt = req.getParameter("zoomAmt"); String wmText = req.getParameter("wmText"); String cropX = req.getParameter("cropX"); String cropY = req.getParameter("cropY"); String cropWidth = req.getParameter("cropWidth"); String cropHeight = req.getParameter("cropHeight"); String convertTo = req.getParameter("convertTo"); if (convertTo != null) { convertTo = convertTo.toLowerCase(); } try { if (op == null) { throw new ServletException("op parameter not specified."); } String outputMimeType; // get the image via url and put it into the ImagePlus processor. BufferedImage img = getImage(url); // do watermarking stuff if (op.equals("watermark")) { if (wmText == null) { throw new ServletException("Must specify wmText."); } Graphics g = img.getGraphics(); int fontSize = img.getWidth() * 3 / 100; if (fontSize < 10) { fontSize = 10; } g.setFont(new Font("Lucida Sans", Font.BOLD, fontSize)); FontMetrics fm = g.getFontMetrics(); int stringWidth = (int) fm.getStringBounds(wmText, g).getWidth(); int x = img.getWidth() / 2 - stringWidth / 2; int y = img.getHeight() - fm.getHeight(); g.setColor(new Color(180, 180, 180)); g.fill3DRect(x - 10, y - fm.getHeight() - 4, stringWidth + 20, fm.getHeight() + 12, true); g.setColor(new Color(100, 100, 100)); g.drawString(wmText, x + 2, y + 2); g.setColor(new Color(240, 240, 240)); g.drawString(wmText, x, y); } ImageProcessor ip = new ImagePlus("temp", img).getProcessor(); // if the inputMimeType is image/gif, need to convert to RGB in any case if (inputMimeType.equals("image/gif")) { ip = ip.convertToRGB(); alreadyConvertedToRGB = true; } // causes scale() and resize() to do bilinear interpolation ip.setInterpolate(true); if (!op.equals("convert")) { if (op.equals("resize")) { ip = resize(ip, newWidth); } else if (op.equals("zoom")) { ip = zoom(ip, zoomAmt); } else if (op.equals("brightness")) { ip = brightness(ip, brightAmt); } else if (op.equals("watermark")) { // this is now taken care of beforehand (see above) } else if (op.equals("grayscale")) { ip = grayscale(ip); } else if (op.equals("crop")) { ip = crop(ip, cropX, cropY, cropWidth, cropHeight); } else { throw new ServletException("Invalid operation: " + op); } outputMimeType = inputMimeType; } else { if (convertTo == null) { throw new ServletException("Neither op nor convertTo was specified."); } if (convertTo.equals("jpg") || convertTo.equals("jpeg")) { outputMimeType = "image/jpeg"; } else if (convertTo.equals("gif")) { outputMimeType = "image/gif"; } else if (convertTo.equals("tiff")) { outputMimeType = "image/tiff"; } else if (convertTo.equals("bmp")) { outputMimeType = "image/bmp"; } else if (convertTo.equals("png")) { outputMimeType = "image/png"; } else { throw new ServletException("Invalid format: " + convertTo); } } res.setContentType(outputMimeType); BufferedOutputStream out = new BufferedOutputStream(res.getOutputStream()); outputImage(ip, out, outputMimeType); out.flush(); out.close(); } catch (Exception e) { e.printStackTrace(); res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getClass().getName() + ": " + e.getMessage()); } }
From source file:com.quinsoft.zeidon.objectbrowser.EntitySquare.java
private void paintCenteredText(Graphics2D graphics2, int y, String text, Color color) { Color prevColor = graphics2.getColor(); if (color != null) graphics2.setColor(color);/*from ww w .j a va2 s . co m*/ FontMetrics fm = graphics2.getFontMetrics(); String lines[] = text.split("\n"); // Adjust y if there is more than one line. y -= (lines.length - 1) * fm.getHeight() / 2; for (String line : lines) { int lth = fm.stringWidth(line); int mid = size.width / 2; graphics2.drawString(line, mid - lth / 2, y); y += fm.getHeight(); } if (color != null) graphics2.setColor(prevColor); }
From source file:savant.view.tracks.TrackRenderer.java
public void drawFeatureLabel(Graphics2D g2, String geneName, double startXPos, double y) { FontMetrics fm = g2.getFontMetrics(); double stringstartx = startXPos - fm.stringWidth(geneName) - 5; if (stringstartx <= 0) { Rectangle2D r = fm.getStringBounds(geneName, g2); int b = 2; Color textColor = g2.getColor(); g2.setColor(new Color(255, 255, 255, 200)); g2.fill(new RoundRectangle2D.Double(3.0, y - (fm.getHeight() - fm.getDescent()) - b, r.getWidth() + 2 * b, r.getHeight() + 2 * b, 8.0, 8.0)); g2.setColor(textColor);//from ww w . j a v a 2 s. c o m g2.drawString(geneName, 5.0F, (float) y); } else { g2.drawString(geneName, (float) stringstartx, (float) y); } }