List of usage examples for java.awt RenderingHints KEY_TEXT_ANTIALIASING
Key KEY_TEXT_ANTIALIASING
To view the source code for java.awt RenderingHints KEY_TEXT_ANTIALIASING.
Click Source Link
From source file:Main.java
@Override public void paintComponent(Graphics gr) { Color c = gr.getColor();//w w w. jav a2 s . c o m setForeground(new Color(0, 0, 0, 0)); super.paintComponent(gr); setForeground(c); gr.setColor(c); Graphics2D g = (Graphics2D) gr; g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); double pw = this.getPreferredSize().width; double ph = this.getPreferredSize().height; double w = this.getSize().width; double h = this.getSize().height; g.setColor(this.getForeground()); AffineTransform stretch = AffineTransform.getScaleInstance(w / pw, h / ph); g.setTransform(stretch); g.drawString(getText(), 0, this.getFont().getSize()); }
From source file:Main.java
/** * Creates and returns image from the given text. * @param text input text/*from www .j a v a 2 s . co m*/ * @param font text font * @return image with input text */ public static BufferedImage createImageFromText(String text, Font font) { //You may want to change these setting, or make them parameters boolean isAntiAliased = true; boolean usesFractionalMetrics = false; FontRenderContext frc = new FontRenderContext(null, isAntiAliased, usesFractionalMetrics); TextLayout layout = new TextLayout(text, font, frc); Rectangle2D bounds = layout.getBounds(); int w = (int) Math.ceil(bounds.getWidth()); int h = (int) Math.ceil(bounds.getHeight()) + 2; BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); //for example; Graphics2D g = image.createGraphics(); g.setColor(Color.WHITE); g.fillRect(0, 0, w, h); g.setColor(Color.BLACK); g.setFont(font); Object antiAliased = isAntiAliased ? RenderingHints.VALUE_TEXT_ANTIALIAS_ON : RenderingHints.VALUE_TEXT_ANTIALIAS_OFF; g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, antiAliased); Object fractionalMetrics = usesFractionalMetrics ? RenderingHints.VALUE_FRACTIONALMETRICS_ON : RenderingHints.VALUE_FRACTIONALMETRICS_OFF; g.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, fractionalMetrics); g.drawString(text, (float) -bounds.getX(), (float) -bounds.getY()); g.dispose(); return image; }
From source file:TextQualityDemoVALUE_TEXT_ANTIALIAS_LCD_HBGR.java
public void paintComponent(Graphics g) { Dimension d = this.getSize(); BufferedImage backBuffer = (BufferedImage) this.createImage(d.width, d.height); Graphics2D g2 = backBuffer.createGraphics(); g2.setColor(Color.WHITE);// w w w.j av a 2 s . c o m g2.fillRect(0, 0, d.width, d.height); g2.setColor(Color.BLACK); g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, hintValue); g2.drawRect(0, 0, d.width - 1, d.height - 1); g2.drawString("abcdefghijklmnopqrstuvwxyz", 20, 40); g2.drawString("ABCDEFGHIJKLMNOPQRSTUVWXYZ", 20, 60); g2.drawString("1234567890-=!@#$%^&*()_+,./<>?", 20, 80); g.drawImage(backBuffer, 0, 0, this); }
From source file:com.us.servlet.AuthCode.java
protected void service(HttpServletRequest request, HttpServletResponse response) { final CodeAuth bean = AppHelper.CODE_AUTH; int width = NumberUtils.toInt(request.getParameter("width"), bean.getWidth()); int height = NumberUtils.toInt(request.getParameter("height"), bean.getHeight()); int x = width / (bean.getLength() + 1); int codeY = height - 4; int fontHeight = height - 2; BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR); Graphics2D graphics = image.createGraphics(); graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); if (StringUtil.hasText(request.getParameter("bgcolor"))) { graphics.setBackground(ColorHelper.hex2RGB(request.getParameter("bgcolor"))); }//from ww w .ja v a2s.c o m graphics.fillRect(0, 0, width, height); graphics.setFont(new Font(bean.getFont(), Font.BOLD, fontHeight)); graphics.drawRect(0, 0, width - 1, height - 1); // if (bean.isBreakLine()) { for (int i = 0; i < 15; i++) { int x1 = RandomUtils.nextInt(width); int y1 = RandomUtils.nextInt(height); int x2 = RandomUtils.nextInt(12); int y2 = RandomUtils.nextInt(12); graphics.drawLine(x1, y1, x + x2, y1 + y2); } } char[] CHARSET_AREA = null; if (bean.getType().charAt(0) == '1') { CHARSET_AREA = ArrayUtils.addAll(CHARSET_AREA, BIG_LETTERS); } if (bean.getType().charAt(1) == '1') { CHARSET_AREA = ArrayUtils.addAll(CHARSET_AREA, SMALL_LETTER); } if (bean.getType().charAt(2) == '1') { CHARSET_AREA = ArrayUtils.addAll(CHARSET_AREA, NUMBERS); } StringBuilder randomCode = new StringBuilder(); for (int i = 0; i < bean.getLength(); i++) { String rand = String.valueOf(CHARSET_AREA[RandomUtils.nextInt(CHARSET_AREA.length)]); graphics.setColor(ColorHelper.color(RandomUtils.nextInt(255), RandomUtils.nextInt(255), RandomUtils.nextInt(255))); graphics.drawString(rand, (i + 1) * x, codeY); randomCode.append(rand); } HttpSession session = request.getSession(); session.setAttribute(bean.getSessionKey(), randomCode.toString()); // ? response.setHeader("Pragma", "no-cache"); response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expires", 0); response.setContentType("image/png"); try { // Servlet? ServletOutputStream sos = response.getOutputStream(); ImageIO.write(image, "png", sos); sos.close(); } catch (Exception e) { e.printStackTrace(); } }
From source file:electroStaticUI.Save.java
/** * Save chart as SVG file.//w w w. j a v a2 s.c o m * Required libs: Apache Batik (batik-svggen.jar, batik-dom.jar, dom.jar). * * @param chart JFreeChart to save. * @param fileName Name of file to save chart in. * @param width Width of chart graphic. * @param height Height of chart graphic. * @return Final file name used. * @throws IOException if failed. * * To Do: Add a save/open method for saving a file native to this application. It should save the users current charge distribution * to be re-loaded at a later time. */ static public final String saveChartToSVG(final JFreeChart chart, String fileName, final int width, final int height) throws IOException { String result = null; if (chart != null) { if (fileName == null) { final String chartTitle = chart.getTitle().getText(); if (chartTitle != null) { fileName = chartTitle; } else { fileName = "chart"; } } result = fileName + ".svg"; final DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation(); final Document document = domImpl.createDocument(null, "svg", null); final SVGGraphics2D svgGenerator = new SVGGraphics2D(document); // svgGenerator.getGeneratorContext().setEmbeddedFontsOn(true); //embed fonts //set anti-aliasing bug fix for SVG generator: //setting rendering hints of svgGenerator doesn't help as it seems to use the rendering hints from the chart final boolean antiAlias = chart.getAntiAlias(); final RenderingHints rh = chart.getRenderingHints(); if (antiAlias) { rh.put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); rh.put(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF); //fix } else { rh.put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); rh.put(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); //fix } // svgGenerator.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); // svgGenerator.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF); // svgGenerator.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); // svgGenerator.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY); // svgGenerator.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); // svgGenerator.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY); chart.draw(svgGenerator, new Rectangle2D.Double(0, 0, width, height), new ChartRenderingInfo()); //undo anti-aliasing bugfix settings for chart to use correct settings: if (antiAlias) { rh.put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); rh.put(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); } else { rh.put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); rh.put(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF); } final boolean useCSS = true; Writer out = null; try { out = new OutputStreamWriter( new BufferedOutputStream(new FileOutputStream(new File(result), false)), "iso-8859-1"); //UTF-8 svgGenerator.stream(out, useCSS); } finally { svgGenerator.dispose(); IOUtils.closeQuietly(out); } } //else: input unavailable return result; }
From source file:be.fedict.eid.idp.sp.PhotoServlet.java
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { LOG.debug("doGet"); response.setContentType("image/jpg"); response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate, max-age=-1"); // http 1.1 response.setHeader("Pragma", "no-cache, no-store"); // http 1.0 response.setDateHeader("Expires", -1); ServletOutputStream out = response.getOutputStream(); HttpSession session = request.getSession(); byte[] photoData = (byte[]) session.getAttribute(PHOTO_SESSION_ATTRIBUTE); if (null != photoData) { BufferedImage photo = ImageIO.read(new ByteArrayInputStream(photoData)); if (null == photo) { /*/*from ww w . j a va2 s . c o m*/ * In this case we render a photo containing some error message. */ photo = new BufferedImage(140, 200, BufferedImage.TYPE_INT_RGB); Graphics2D graphics = (Graphics2D) photo.getGraphics(); RenderingHints renderingHints = new RenderingHints(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); graphics.setRenderingHints(renderingHints); graphics.setColor(Color.WHITE); graphics.fillRect(1, 1, 140 - 1 - 1, 200 - 1 - 1); graphics.setColor(Color.RED); graphics.setFont(new Font("Dialog", Font.BOLD, 20)); graphics.drawString("Photo Error", 0, 200 / 2); graphics.dispose(); ImageIO.write(photo, "jpg", out); } else { out.write(photoData); } } out.close(); }
From source file:be.fedict.eid.applet.service.PhotoServlet.java
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { LOG.debug("doGet"); response.setContentType("image/jpg"); response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate, max-age=-1"); // http 1.1 response.setHeader("Pragma", "no-cache, no-store"); // http 1.0 response.setDateHeader("Expires", -1); ServletOutputStream out = response.getOutputStream(); HttpSession session = request.getSession(); byte[] photoData = (byte[]) session.getAttribute(IdentityDataMessageHandler.PHOTO_SESSION_ATTRIBUTE); if (null != photoData) { BufferedImage photo = ImageIO.read(new ByteArrayInputStream(photoData)); if (null == photo) { /*//from w w w .j a va 2s .co m * In this case we render a photo containing some error message. */ photo = new BufferedImage(140, 200, BufferedImage.TYPE_INT_RGB); Graphics2D graphics = (Graphics2D) photo.getGraphics(); RenderingHints renderingHints = new RenderingHints(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); graphics.setRenderingHints(renderingHints); graphics.setColor(Color.WHITE); graphics.fillRect(1, 1, 140 - 1 - 1, 200 - 1 - 1); graphics.setColor(Color.RED); graphics.setFont(new Font("Dialog", Font.BOLD, 20)); graphics.drawString("Photo Error", 0, 200 / 2); graphics.dispose(); ImageIO.write(photo, "jpg", out); } else { out.write(photoData); } } out.close(); }
From source file:Utils.java
/** * Renders a paragraph of text (line breaks ignored) to an image (created and returned). * * @param font The font to use/* w ww.j av a 2s. co m*/ * @param textColor The color of the text * @param text The message * @param width The width the text should be limited to * @return An image with the text rendered into it */ public static BufferedImage renderTextToImage(Font font, Color textColor, String text, int width) { Hashtable map = new Hashtable(); map.put(TextAttribute.FONT, font); AttributedString attributedString = new AttributedString(text, map); AttributedCharacterIterator paragraph = attributedString.getIterator(); FontRenderContext frc = new FontRenderContext(null, false, false); int paragraphStart = paragraph.getBeginIndex(); int paragraphEnd = paragraph.getEndIndex(); LineBreakMeasurer lineMeasurer = new LineBreakMeasurer(paragraph, frc); float drawPosY = 0; //First time around, just determine the height while (lineMeasurer.getPosition() < paragraphEnd) { TextLayout layout = lineMeasurer.nextLayout(width); // Move it down drawPosY += layout.getAscent() + layout.getDescent() + layout.getLeading(); } BufferedImage image = createCompatibleImage(width, (int) drawPosY); Graphics2D graphics = (Graphics2D) image.getGraphics(); graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); drawPosY = 0; lineMeasurer.setPosition(paragraphStart); while (lineMeasurer.getPosition() < paragraphEnd) { TextLayout layout = lineMeasurer.nextLayout(width); // Move y-coordinate by the ascent of the layout. drawPosY += layout.getAscent(); /* Compute pen x position. If the paragraph is right-to-left, we want to align the TextLayouts to the right edge of the panel. */ float drawPosX; if (layout.isLeftToRight()) { drawPosX = 0; } else { drawPosX = width - layout.getAdvance(); } // Draw the TextLayout at (drawPosX, drawPosY). layout.draw(graphics, drawPosX, drawPosY); // Move y-coordinate in preparation for next layout. drawPosY += layout.getDescent() + layout.getLeading(); } graphics.dispose(); return image; }
From source file:org.jrecruiter.service.impl.DataServiceImpl.java
/** {@inheritDoc} */ @Transactional(readOnly = true, propagation = Propagation.SUPPORTS) public Image getGoogleMapImage(final BigDecimal latitude, final BigDecimal longitude, final Integer zoomLevel) { if (longitude == null) { throw new IllegalArgumentException("Longitude cannot be null."); }//from w ww .j a va 2 s . co m if (latitude == null) { throw new IllegalArgumentException("Latitude cannot be null."); } if (zoomLevel == null) { throw new IllegalArgumentException("ZoomLevel cannot be null."); } final URI url = GoogleMapsUtils.buildGoogleMapsStaticUrl(latitude, longitude, zoomLevel); BufferedImage img; try { URLConnection conn = url.toURL().openConnection(); img = ImageIO.read(conn.getInputStream()); } catch (UnknownHostException e) { LOGGER.error("Google static MAPS web service is not reachable (UnknownHostException).", e); img = new BufferedImage(GoogleMapsUtils.defaultWidth, 100, BufferedImage.TYPE_INT_RGB); final Graphics2D graphics = img.createGraphics(); final Map<Object, Object> renderingHints = CollectionUtils.getHashMap(); renderingHints.put(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); graphics.addRenderingHints(renderingHints); graphics.setBackground(Color.WHITE); graphics.setColor(Color.GRAY); graphics.clearRect(0, 0, GoogleMapsUtils.defaultWidth, 100); graphics.drawString("Not Available", 30, 30); } catch (IOException e) { throw new IllegalStateException(e); } return img; }
From source file:com.igormaznitsa.jhexed.swing.editor.ui.exporters.PNGImageExporter.java
public BufferedImage generateImage() throws IOException { final int DEFAULT_CELL_WIDTH = 48; final int DEFAULT_CELL_HEIGHT = 48; final int imgWidth = this.docOptions.getImage() == null ? DEFAULT_CELL_WIDTH * this.docOptions.getColumns() : Math.round(this.docOptions.getImage().getSVGWidth()); final int imgHeight = this.docOptions.getImage() == null ? DEFAULT_CELL_HEIGHT * this.docOptions.getRows() : Math.round(this.docOptions.getImage().getSVGHeight()); final BufferedImage result; if (exportData.isBackgroundImageExport() && this.docOptions.getImage() != null) { result = this.docOptions.getImage().rasterize(imgWidth, imgHeight, BufferedImage.TYPE_INT_ARGB); } else {/* ww w . j a va2 s . c om*/ result = new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_INT_ARGB); } final Graphics2D gfx = result.createGraphics(); gfx.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY); gfx.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); gfx.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); final HexEngine<Graphics2D> engine = new HexEngine<Graphics2D>(DEFAULT_CELL_WIDTH, DEFAULT_CELL_HEIGHT, this.docOptions.getHexOrientation()); final List<HexFieldLayer> reversedNormalizedStack = new ArrayList<HexFieldLayer>(); for (int i = this.exportData.getLayers().size() - 1; i >= 0; i--) { final LayerExportRecord rec = this.exportData.getLayers().get(i); if (rec.isAllowed()) { reversedNormalizedStack.add(rec.getLayer()); } } if (Thread.currentThread().isInterrupted()) return null; final HexFieldValue[] stackOfValues = new HexFieldValue[reversedNormalizedStack.size()]; engine.setModel(new HexEngineModel<HexFieldValue[]>() { @Override public int getColumnNumber() { return docOptions.getColumns(); } @Override public int getRowNumber() { return docOptions.getRows(); } @Override public HexFieldValue[] getValueAt(final int col, final int row) { Arrays.fill(stackOfValues, null); for (int index = 0; index < reversedNormalizedStack.size(); index++) { stackOfValues[index] = reversedNormalizedStack.get(index).getHexValueAtPos(col, row); } return stackOfValues; } @Override public HexFieldValue[] getValueAt(final HexPosition pos) { return this.getValueAt(pos.getColumn(), pos.getRow()); } @Override public void setValueAt(int col, int row, HexFieldValue[] value) { } @Override public void setValueAt(HexPosition pos, HexFieldValue[] value) { } @Override public boolean isPositionValid(final int col, final int row) { return col >= 0 && col < docOptions.getColumns() && row >= 0 && row < docOptions.getRows(); } @Override public boolean isPositionValid(final HexPosition pos) { return this.isPositionValid(pos.getColumn(), pos.getRow()); } @Override public void attachedToEngine(final HexEngine<?> engine) { } @Override public void detachedFromEngine(final HexEngine<?> engine) { } }); final HexRect2D visibleSize = engine.getVisibleSize(); final float xcoeff = (float) result.getWidth() / visibleSize.getWidth(); final float ycoeff = (float) result.getHeight() / visibleSize.getHeight(); engine.setScale(xcoeff, ycoeff); final Image[][] cachedIcons = new Image[this.exportData.getLayers().size()][]; engine.setRenderer(new ColorHexRender() { private final Stroke stroke = new BasicStroke(docOptions.getLineWidth()); @Override public Stroke getStroke() { return this.stroke; } @Override public Color getFillColor(HexEngineModel<?> model, int col, int row) { return null; } @Override public Color getBorderColor(HexEngineModel<?> model, int col, int row) { return exportData.isExportHexBorders() ? docOptions.getColor() : null; } @Override public void drawExtra(HexEngine<Graphics2D> engine, Graphics2D g, int col, int row, Color borderColor, Color fillColor) { } @Override public void drawUnderBorder(final HexEngine<Graphics2D> engine, final Graphics2D g, final int col, final int row, final Color borderColor, final Color fillColor) { final HexFieldValue[] stackValues = (HexFieldValue[]) engine.getModel().getValueAt(col, row); for (int i = 0; i < stackValues.length; i++) { final HexFieldValue valueToDraw = stackValues[i]; if (valueToDraw == null) { continue; } g.drawImage(cachedIcons[i][valueToDraw.getIndex()], 0, 0, null); } } }); final Path2D hexShape = ((ColorHexRender) engine.getRenderer()).getHexPath(); final int cellWidth = hexShape.getBounds().width; final int cellHeight = hexShape.getBounds().height; for (int layerIndex = 0; layerIndex < reversedNormalizedStack.size() && !Thread.currentThread().isInterrupted(); layerIndex++) { final HexFieldLayer theLayer = reversedNormalizedStack.get(layerIndex); final Image[] cacheLineForLayer = new Image[theLayer.getHexValuesNumber()]; for (int valueIndex = 1; valueIndex < theLayer.getHexValuesNumber(); valueIndex++) { cacheLineForLayer[valueIndex] = theLayer.getHexValueForIndex(valueIndex).makeIcon(cellWidth, cellHeight, hexShape, true); } cachedIcons[layerIndex] = cacheLineForLayer; } engine.drawWithThreadInterruptionCheck(gfx); if (Thread.currentThread().isInterrupted()) return null; if (this.exportData.isCellCommentariesExport()) { final Iterator<Entry<HexPosition, String>> iterator = this.cellComments.iterator(); gfx.setFont(new Font("Arial", Font.BOLD, 12)); while (iterator.hasNext() && !Thread.currentThread().isInterrupted()) { final Entry<HexPosition, String> item = iterator.next(); final HexPosition pos = item.getKey(); final String text = item.getValue(); final float x = engine.calculateX(pos.getColumn(), pos.getRow()); final float y = engine.calculateY(pos.getColumn(), pos.getRow()); final Rectangle2D textBounds = gfx.getFontMetrics().getStringBounds(text, gfx); final float dx = x - ((float) textBounds.getWidth() - engine.getCellWidth()) / 2; gfx.setColor(Color.BLACK); gfx.drawString(text, dx, y); gfx.setColor(Color.WHITE); gfx.drawString(text, dx - 2, y - 2); } } gfx.dispose(); return result; }