List of usage examples for java.awt RenderingHints KEY_ANTIALIASING
Key KEY_ANTIALIASING
To view the source code for java.awt RenderingHints KEY_ANTIALIASING.
Click Source Link
From source file:dcstore.web.ImagesWeb.java
private void resizeImage(String inPath, int w, int h, String outPath) { try {/*from w w w. j a va2s . com*/ BufferedImage originalImage = ImageIO.read(new File(inPath)); int ow, oh; ow = originalImage.getWidth(); oh = originalImage.getHeight(); double ratio = (double) ow / (double) oh; int type = originalImage.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : originalImage.getType(); int ch = (int) Math.round(w / ratio); BufferedImage resizedImage = new BufferedImage(w, h, type); Graphics2D g = resizedImage.createGraphics(); g.setComposite(AlphaComposite.Src); g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g.setColor(Color.white); g.fillRect(0, 0, w, h); g.drawImage(originalImage, 0, (int) (((float) h - (float) ch) / 2), w, ch, null); g.dispose(); ImageIO.write(resizedImage, "jpg", new File(outPath)); } catch (Exception e) { FacesContext.getCurrentInstance().addMessage("", new FacesMessage("Error while resizeing image: " + e.getMessage())); } }
From source file:org.polymap.service.geoserver.spring.PipelineMapProducer.java
public void writeTo(final OutputStream out) throws ServiceException, IOException { Timer timer = new Timer(); // single layer? -> request ENCODED_IMAGE if (mapContext.getLayerCount() == 1) { MapLayer mapLayer = mapContext.getLayers()[0]; ILayer layer = loader.findLayer(mapLayer); try {//from ww w . ja va2s . com Pipeline pipeline = loader.getOrCreatePipeline(layer, LayerUseCase.ENCODED_IMAGE); ProcessorRequest request = prepareProcessorRequest(); pipeline.process(request, new ResponseHandler() { public void handle(ProcessorResponse pipeResponse) throws Exception { HttpServletResponse response = GeoServerWms.response.get(); if (pipeResponse == EncodedImageResponse.NOT_MODIFIED) { log.info("Response: 304!"); response.setStatus(304); } else { long lastModified = ((EncodedImageResponse) pipeResponse).getLastModified(); // allow caches and browser clients to cache for 1h //response.setHeader( "Cache-Control", "public,max-age=3600" ); if (lastModified > 0) { response.setHeader("Cache-Control", "no-cache,must-revalidate"); response.setDateHeader("Last-Modified", lastModified); } else { response.setHeader("Cache-Control", "no-cache,must-revalidate"); response.setDateHeader("Expires", 0); } byte[] chunk = ((EncodedImageResponse) pipeResponse).getChunk(); int len = ((EncodedImageResponse) pipeResponse).getChunkSize(); out.write(chunk, 0, len); } } }); log.debug(" flushing response stream. (" + timer.elapsedTime() + "ms)"); out.flush(); } catch (IOException e) { throw e; } catch (Exception e) { throw new IOException(e); } } // multiple layers -> render into one image else { List<Job> jobs = new ArrayList(); final Map<MapLayer, Image> images = new HashMap(); // run jobs for all layers for (final MapLayer mapLayer : mapContext.getLayers()) { final ILayer layer = loader.findLayer(mapLayer); // job UIJob job = new UIJob(getClass().getSimpleName() + ": " + layer.getLabel()) { protected void runWithException(IProgressMonitor monitor) throws Exception { try { // XXX this excludes Cache304 (which support EncodedImageResponse only) Pipeline pipeline = loader.getOrCreatePipeline(layer, LayerUseCase.IMAGE); GetMapRequest targetRequest = prepareProcessorRequest(); pipeline.process(targetRequest, new ResponseHandler() { public void handle(ProcessorResponse pipeResponse) throws Exception { Image layerImage = ((ImageResponse) pipeResponse).getImage(); images.put(mapLayer, layerImage); } }); } catch (Exception e) { // XXX put a special image in the map log.warn("", e); images.put(mapLayer, null); throw e; } } }; job.schedule(); jobs.add(job); } // join jobs for (Job job : jobs) { try { job.join(); } catch (InterruptedException e) { // XXX put a special image in the map log.warn("", e); } } // put images together (MapContext order) Graphics2D g = null; try { // result image BufferedImage result = ImageUtils.createImage(mapContext.getMapWidth(), mapContext.getMapHeight(), null, true); g = result.createGraphics(); // rendering hints RenderingHints hints = new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); hints.add(new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)); hints.add(new RenderingHints(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON)); g.setRenderingHints(hints); for (MapLayer mapLayer : mapContext.getLayers()) { Image layerImage = images.get(mapLayer); // load image data // new javax.swing.ImageIcon( image ).getImage(); ILayer layer = loader.findLayer(mapLayer); int rule = AlphaComposite.SRC_OVER; float alpha = ((float) layer.getOpacity()) / 100; g.setComposite(AlphaComposite.getInstance(rule, alpha)); g.drawImage(layerImage, 0, 0, null); } encodeImage(result, out); } finally { if (g != null) { g.dispose(); } } } }
From source file:com.ctsim.dmi.MainFrame.java
private void initGraphics() { g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); if (App.isTurnOn) { g2.drawImage(speedoDial, 100, 50, this); t2 = Calendar.getInstance(); if (t2.getTimeInMillis() - t1.getTimeInMillis() > 300) { isFlashOn = !isFlashOn;/*from w w w .j av a2 s . c om*/ t1 = Calendar.getInstance(); } drawBrake(); drawTargetDestance(); drawPin(); drawATOStatus(); drawAtenna(); drawATPStatus(); drawDoorIndicator(); drawCeillingSpeed(); drawDoorStatus(); drawScroll(); drawSkipStop(); drawID(); drawButtons(); drawTime(); drawColorBar(); g2.setColor(Color.GRAY); g2.setFont(new Font("Loma", Font.PLAIN, 12)); g2.drawString("(" + x + ", " + y + ")", 20, 20); //operationLoop(); } }
From source file:au.org.ala.biocache.web.MapController.java
@Deprecated @RequestMapping(value = "/occurrences/wms", method = RequestMethod.GET) public void pointsWmsImage(SpatialSearchRequestParams requestParams, @RequestParam(value = "colourby", required = false, defaultValue = "0") Integer colourby, @RequestParam(value = "width", required = false, defaultValue = "256") Integer widthObj, @RequestParam(value = "height", required = false, defaultValue = "256") Integer heightObj, @RequestParam(value = "zoom", required = false, defaultValue = "0") Integer zoomLevel, @RequestParam(value = "symsize", required = false, defaultValue = "4") Integer symsize, @RequestParam(value = "symbol", required = false, defaultValue = "circle") String symbol, @RequestParam(value = "bbox", required = false, defaultValue = "110,-45,157,-9") String bboxString, @RequestParam(value = "type", required = false, defaultValue = "normal") String type, @RequestParam(value = "outline", required = true, defaultValue = "false") boolean outlinePoints, @RequestParam(value = "outlineColour", required = true, defaultValue = "0x000000") String outlineColour, HttpServletResponse response) throws Exception { // size of the circles int size = symsize.intValue(); int width = widthObj.intValue(); int height = heightObj.intValue(); requestParams.setStart(0);//from ww w . j a va2 s. c o m requestParams.setPageSize(Integer.MAX_VALUE); String query = requestParams.getQ(); String[] filterQuery = requestParams.getFq(); if (StringUtils.isBlank(query) && StringUtils.isBlank(requestParams.getFormattedQuery())) { displayBlankImage(width, height, false, response); return; } // let's force it to PNG's for now response.setContentType("image/png"); // Convert array to list so we append more values onto it ArrayList<String> fqList = null; if (filterQuery != null) { fqList = new ArrayList<String>(Arrays.asList(filterQuery)); } else { fqList = new ArrayList<String>(); } // the bounding box double[] bbox = new double[4]; int i; i = 0; for (String s : bboxString.split(",")) { try { bbox[i] = Double.parseDouble(s); i++; } catch (Exception e) { logger.error(e.getMessage(), e); } } double pixelWidth = (bbox[2] - bbox[0]) / width; double pixelHeight = (bbox[3] - bbox[1]) / height; bbox[0] += pixelWidth / 2; bbox[2] -= pixelWidth / 2; bbox[1] += pixelHeight / 2; bbox[3] -= pixelHeight / 2; //offset for points bounding box by size double xoffset = (bbox[2] - bbox[0]) / (double) width * (size * 2); double yoffset = (bbox[3] - bbox[1]) / (double) height * (size * 2); //adjust offset for pixel height/width xoffset += pixelWidth; yoffset += pixelHeight; double[] bbox2 = new double[4]; bbox2[0] = convertMetersToLng(bbox[0] - xoffset); bbox2[1] = convertMetersToLat(bbox[1] - yoffset); bbox2[2] = convertMetersToLng(bbox[2] + xoffset); bbox2[3] = convertMetersToLat(bbox[3] + yoffset); bbox[0] = convertMetersToLng(bbox[0]); bbox[1] = convertMetersToLat(bbox[1]); bbox[2] = convertMetersToLng(bbox[2]); bbox[3] = convertMetersToLat(bbox[3]); double[] pbbox = new double[4]; //pixel bounding box pbbox[0] = convertLngToPixel(bbox[0]); pbbox[1] = convertLatToPixel(bbox[1]); pbbox[2] = convertLngToPixel(bbox[2]); pbbox[3] = convertLatToPixel(bbox[3]); String bboxString2 = bbox2[0] + "," + bbox2[1] + "," + bbox2[2] + "," + bbox2[3]; bboxToQuery(bboxString2, fqList); PointType pointType = getPointTypeForZoomLevel(zoomLevel); String[] newFilterQuery = (String[]) fqList.toArray(new String[fqList.size()]); // convert back to array requestParams.setFq(newFilterQuery); List<OccurrencePoint> points = searchDAO.getFacetPoints(requestParams, pointType); logger.debug("Points search for " + pointType.getLabel() + " - found: " + points.size()); if (points.size() == 0) { displayBlankImage(width, height, false, response); return; } BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); Graphics2D g = (Graphics2D) img.getGraphics(); g.setColor(Color.RED); int x, y; int pointWidth = size * 2; double width_mult = (width / (pbbox[2] - pbbox[0])); double height_mult = (height / (pbbox[1] - pbbox[3])); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); Color oColour = Color.decode(outlineColour); for (i = 0; i < points.size(); i++) { OccurrencePoint pt = points.get(i); float lng = pt.getCoordinates().get(0).floatValue(); float lat = pt.getCoordinates().get(1).floatValue(); x = (int) ((convertLngToPixel(lng) - pbbox[0]) * width_mult); y = (int) ((convertLatToPixel(lat) - pbbox[3]) * height_mult); if (colourby != null) { int colour = 0xFF000000 | colourby.intValue(); Color c = new Color(colour); g.setPaint(c); } else { g.setPaint(Color.blue); } // g.fillOval(x - (size / 2), y - (size / 2), pointWidth, pointWidth); Shape shp = getShape(symbol, x - (size / 2), y - (size / 2), pointWidth, pointWidth); g.draw(shp); g.fill(shp); if (outlinePoints) { g.setPaint(oColour); g.drawOval(x - (size / 2), y - (size / 2), pointWidth, pointWidth); } } g.dispose(); try { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ImageIO.write(img, "png", outputStream); ServletOutputStream outStream = response.getOutputStream(); outStream.write(outputStream.toByteArray()); outStream.flush(); outStream.close(); } catch (Exception e) { logger.error("Unable to write image", e); } }
From source file:org.polymap.core.data.image.RasterRenderProcessor.java
protected Image getMap(Set<ILayer> layers, int width, int height, ReferencedEnvelope bbox) { // mapContext synchronized (this) { // check style objects boolean needsNewContext = false; // create mapContext if (mapContext == null || needsNewContext) { // sort z-priority TreeMap<String, ILayer> sortedLayers = new TreeMap(); for (ILayer layer : layers) { String uniqueOrderKey = String.valueOf(layer.getOrderKey()) + layer.id(); sortedLayers.put(uniqueOrderKey, layer); }//from w w w . j a v a 2s. c om // add to mapContext mapContext = new DefaultMapContext(bbox.getCoordinateReferenceSystem()); for (ILayer layer : sortedLayers.values()) { try { IGeoResource res = layer.getGeoResource(); if (res == null) { throw new IllegalStateException("Unable to find geo resource of layer: " + layer); } AbstractRasterService service = (AbstractRasterService) res.service(null); log.debug(" service: " + service); log.debug(" CRS: " + layer.getCRS()); AbstractGridCoverage2DReader reader = service.getReader(layer.getCRS(), null); Style style = createRGBStyle(reader); if (style == null) { log.warn("Error creating RGB style, trying greyscale..."); style = createGreyscaleStyle(1); } mapContext.addLayer(reader, style); styles.put(layer, style); } catch (IOException e) { log.warn(e); // FIXME set layer status and statusMessage } } } else { } } // render BufferedImage result = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR); final Graphics2D g = result.createGraphics(); try { StreamingRenderer renderer = new StreamingRenderer(); // error handler renderer.addRenderListener(new RenderListener() { public void featureRenderer(SimpleFeature feature) { } public void errorOccurred(Exception e) { log.error("Renderer error: ", e); drawErrorMsg(g, "Fehler bei der Darstellung.", e); } }); // rendering hints RenderingHints hints = new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); hints.add(new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)); hints.add(new RenderingHints(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON)); renderer.setJava2DHints(hints); // g.setRenderingHints( hints ); // render params Map rendererParams = new HashMap(); rendererParams.put("optimizedDataLoadingEnabled", Boolean.TRUE); renderer.setRendererHints(rendererParams); renderer.setContext(mapContext); Rectangle paintArea = new Rectangle(width, height); renderer.paint(g, paintArea, bbox); return result; } catch (Throwable e) { log.error("Renderer error: ", e); drawErrorMsg(g, null, e); return result; } finally { if (g != null) { g.dispose(); } } }
From source file:org.apache.pdflens.views.pagesview.PageDrawer.java
/** * Fill the path.//from ww w. j a v a2s.c o m * * @param windingRule The winding rule this path will use. * * @throws IOException If there is an IO error while filling the path. */ public void fillPath(int windingRule) throws IOException { graphics.setColor(getGraphicsState().getNonStrokingColor().getJavaColor()); getLinePath().setWindingRule(windingRule); graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); graphics.setClip(getGraphicsState().getCurrentClippingPath()); graphics.fill(getLinePath()); getLinePath().reset(); }
From source file:org.apache.jetspeed.security.mfa.impl.CaptchaImageResource.java
/** * Renders this image/*from w w w . ja v a 2 s . c o m*/ * * @return The image data */ private final byte[] render() throws IOException { Graphics2D gfx = (Graphics2D) this.image.getGraphics(); if (config.isFontAntialiasing()) gfx.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); int curWidth = config.getTextMarginLeft(); FontRenderContext ctx = new FontRenderContext(null, config.isFontAntialiasing(), false); for (int i = 0; i < charAttsList.size(); i++) { CharAttributes cf = (CharAttributes) charAttsList.get(i); TextLayout text = new TextLayout(cf.getChar() + "", getFont(cf.getName()), ctx); //gfx.getFontRenderContext()); AffineTransform textAt = new AffineTransform(); textAt.translate(curWidth, this.height - cf.getRise()); if (cf.getRotation() != 0) { textAt.rotate(cf.getRotation()); } if (cf.getShearX() > 0.0) textAt.shear(cf.getShearX(), cf.getShearY()); Shape shape = text.getOutline(textAt); curWidth += shape.getBounds().getWidth() + config.getTextSpacing(); if (config.isUseImageBackground()) gfx.setColor(Color.BLACK); else gfx.setXORMode(Color.BLACK); gfx.fill(shape); } if (config.isEffectsNoise()) { noiseEffects(gfx, image); } if (config.isUseTimestamp()) { if (config.isEffectsNoise()) gfx.setColor(Color.WHITE); else gfx.setColor(Color.BLACK); TimeZone tz = TimeZone.getTimeZone(config.getTimestampTZ()); Calendar cal = new GregorianCalendar(tz); SimpleDateFormat formatter; if (config.isUseTimestamp24hr()) formatter = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss z"); else formatter = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a, z"); formatter.setTimeZone(tz); Font font = gfx.getFont(); Font newFont = new Font(font.getName(), font.getStyle(), config.getTimestampFontSize()); gfx.setFont(newFont); gfx.drawString(formatter.format(cal.getTime()), config.getTextMarginLeft() * 4, this.height - 1); } return toImageData(image); }
From source file:net.fenyo.gnetwatch.GUI.BasicComponent.java
/** * Creates a backing store./* w w w . ja v a 2 s . c om*/ * @param none. * @return void. */ private void newBackingElts() { dimension = getSize(); backing_store = createImage(dimension.width, dimension.height); backing_g = (Graphics2D) backing_store.getGraphics(); backing_g.setBackground(Color.BLACK); backing_g.setColor(Color.WHITE); backing_g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); backing_g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); }
From source file:com.github.lucapino.sheetmaker.renderer.JavaTemplateRenderer.java
private ImagePanel drawTemplate(Element drawImageTemplateElement) throws Exception { // OutputImageSettings logger.info("reading ImageDrawTemlate attributes..."); Element outputImageSettingsElement = drawImageTemplateElement.getChild(OUTPUT_IMAGE_SETTINGS); String colorDepth = outputImageSettingsElement.getAttributeValue("ColorDepth"); String imageForat = outputImageSettingsElement.getAttributeValue("ImageFormat"); String jpegCompressionLevel = outputImageSettingsElement.getAttributeValue("JpegCompressionLevel"); String dpi = outputImageSettingsElement.getAttributeValue("Dpi"); logger.info("Reading Canvas attributes..."); // Canvas//from w w w .j a v a 2 s. c o m Element canvasElement = drawImageTemplateElement.getChild(CANVAS); String autoSize = canvasElement.getAttributeValue("AutoSize"); String centerElements = canvasElement.getAttributeValue("CenterElements"); int width = Integer.valueOf(canvasElement.getAttributeValue("Width")); int height = Integer.valueOf(canvasElement.getAttributeValue("Height")); String fill = canvasElement.getAttributeValue("Fill"); // create image of specified dimensions logger.info("Creating working image..."); BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); Graphics2D g2 = image.createGraphics(); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); // Elements logger.info("Processing elements..."); Element elementsElement = drawImageTemplateElement.getChild("Elements"); for (Element element : elementsElement.getChildren()) { switch (element.getName()) { case "ImageElement": processImageElement(g2, element); break; case "TextElement": processTextElement(g2, element); break; } } return new ImagePanel(image); }
From source file:org.esa.snap.graphbuilder.rcp.dialogs.support.GraphPanel.java
/** * Paints the panel component/*from w ww . j av a2 s .c o m*/ * * @param g The Graphics */ @Override protected void paintComponent(java.awt.Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D) g; g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); DrawGraph(g2, graphEx.GetGraphNodes()); }