Example usage for java.awt Graphics2D fillRect

List of usage examples for java.awt Graphics2D fillRect

Introduction

In this page you can find the example usage for java.awt Graphics2D fillRect.

Prototype

public abstract void fillRect(int x, int y, int width, int height);

Source Link

Document

Fills the specified rectangle.

Usage

From source file:org.apache.pdfbox.pdmodel.graphics.xobject.PDPixelMap.java

/**
 * Returns a {@link java.awt.image.BufferedImage} of the COSStream
 * set in the constructor or null if the COSStream could not be encoded.
 *
 * @return {@inheritDoc}/*  w  ww  .j av  a2  s  .  c  o m*/
 *
 * @throws IOException {@inheritDoc}
 */
public BufferedImage getRGBImage() throws IOException {
    if (image != null) {
        return image;
    }

    try {
        int width = getWidth();
        int height = getHeight();
        int bpc = getBitsPerComponent();

        byte[] array = getPDStream().getByteArray();
        if (array.length == 0) {
            LOG.error("Something went wrong ... the pixelmap doesn't contain any data.");
            return null;
        }
        // Get the ColorModel right
        PDColorSpace colorspace = getColorSpace();
        if (colorspace == null) {
            LOG.error("getColorSpace() returned NULL.  Predictor = " + getPredictor());
            return null;
        }

        ColorModel cm = null;
        if (colorspace instanceof PDIndexed) {
            PDIndexed csIndexed = (PDIndexed) colorspace;
            // the base color space uses 8 bit per component, as the indexed color values
            // of an indexed color space are always in a range from 0 to 255
            ColorModel baseColorModel = csIndexed.getBaseColorSpace().createColorModel(8);
            // number of possible color values in the target color space
            int numberOfColorValues = 1 << bpc;
            // number of indexed color values
            int highValue = csIndexed.getHighValue();
            // choose the correct size, sometimes there are more indexed values than needed
            // and sometimes there are fewer indexed value than possible
            int size = Math.min(numberOfColorValues - 1, highValue);
            byte[] index = csIndexed.getLookupData();
            boolean hasAlpha = baseColorModel.hasAlpha();
            COSBase maskArray = getMask();
            if (baseColorModel.getTransferType() != DataBuffer.TYPE_BYTE) {
                throw new IOException("Not implemented");
            }
            // the IndexColorModel uses RGB-based color values
            // which leads to 3 color components and a optional alpha channel
            int numberOfComponents = 3 + (hasAlpha ? 1 : 0);
            int buffersize = (size + 1) * numberOfComponents;
            byte[] colorValues = new byte[buffersize];
            byte[] inData = new byte[baseColorModel.getNumComponents()];
            int bufferIndex = 0;
            for (int i = 0; i <= size; i++) {
                System.arraycopy(index, i * inData.length, inData, 0, inData.length);
                // convert the indexed color values to RGB 
                colorValues[bufferIndex] = (byte) baseColorModel.getRed(inData);
                colorValues[bufferIndex + 1] = (byte) baseColorModel.getGreen(inData);
                colorValues[bufferIndex + 2] = (byte) baseColorModel.getBlue(inData);
                if (hasAlpha) {
                    colorValues[bufferIndex + 3] = (byte) baseColorModel.getAlpha(inData);
                }
                bufferIndex += numberOfComponents;
            }
            if (maskArray != null && maskArray instanceof COSArray) {
                cm = new IndexColorModel(bpc, size + 1, colorValues, 0, hasAlpha,
                        ((COSArray) maskArray).getInt(0));
            } else {
                cm = new IndexColorModel(bpc, size + 1, colorValues, 0, hasAlpha);
            }
        } else if (colorspace instanceof PDSeparation) {
            PDSeparation csSeparation = (PDSeparation) colorspace;
            int numberOfComponents = csSeparation.getAlternateColorSpace().getNumberOfComponents();
            PDFunction tintTransformFunc = csSeparation.getTintTransform();
            COSArray decode = getDecode();
            // we have to invert the tint-values,
            // if the Decode array exists and consists of (1,0)
            boolean invert = decode != null && decode.getInt(0) == 1;
            // TODO add interpolation for other decode values then 1,0
            int maxValue = (int) Math.pow(2, bpc) - 1;
            // destination array
            byte[] mappedData = new byte[width * height * numberOfComponents];
            int rowLength = width * numberOfComponents;
            float[] input = new float[1];
            for (int i = 0; i < height; i++) {
                int rowOffset = i * rowLength;
                for (int j = 0; j < width; j++) {
                    // scale tint values to a range of 0...1
                    int value = (array[i * width + j] + 256) % 256;
                    if (invert) {
                        input[0] = 1 - (value / maxValue);
                    } else {
                        input[0] = value / maxValue;
                    }
                    float[] mappedColor = tintTransformFunc.eval(input);
                    int columnOffset = j * numberOfComponents;
                    for (int k = 0; k < numberOfComponents; k++) {
                        // redo scaling for every single color value 
                        float mappedValue = mappedColor[k];
                        mappedData[rowOffset + columnOffset + k] = (byte) (mappedValue * maxValue);
                    }
                }
            }
            array = mappedData;
            cm = colorspace.createColorModel(bpc);
        } else if (bpc == 1) {
            byte[] map = null;
            if (colorspace instanceof PDDeviceGray) {
                COSArray decode = getDecode();
                // we have to invert the b/w-values,
                // if the Decode array exists and consists of (1,0)
                if (decode != null && decode.getInt(0) == 1) {
                    map = new byte[] { (byte) 0xff };
                } else {
                    map = new byte[] { (byte) 0x00, (byte) 0xff };
                }
            } else if (colorspace instanceof PDICCBased) {
                if (((PDICCBased) colorspace).getNumberOfComponents() == 1) {
                    map = new byte[] { (byte) 0xff };
                } else {
                    map = new byte[] { (byte) 0x00, (byte) 0xff };
                }
            } else {
                map = new byte[] { (byte) 0x00, (byte) 0xff };
            }
            cm = new IndexColorModel(bpc, map.length, map, map, map, Transparency.OPAQUE);
        } else {
            if (colorspace instanceof PDICCBased) {
                if (((PDICCBased) colorspace).getNumberOfComponents() == 1) {
                    byte[] map = new byte[] { (byte) 0xff };
                    cm = new IndexColorModel(bpc, 1, map, map, map, Transparency.OPAQUE);
                } else {
                    cm = colorspace.createColorModel(bpc);
                }
            } else {
                cm = colorspace.createColorModel(bpc);
            }
        }

        LOG.debug("ColorModel: " + cm.toString());
        WritableRaster raster = cm.createCompatibleWritableRaster(width, height);
        DataBufferByte buffer = (DataBufferByte) raster.getDataBuffer();
        byte[] bufferData = buffer.getData();

        System.arraycopy(array, 0, bufferData, 0,
                (array.length < bufferData.length ? array.length : bufferData.length));
        image = new BufferedImage(cm, raster, false, null);

        // If there is a 'soft mask' image then we use that as a transparency mask.
        PDXObjectImage smask = getSMaskImage();
        if (smask != null) {
            BufferedImage smaskBI = smask.getRGBImage();

            COSArray decodeArray = smask.getDecode();

            CompositeImage compositeImage = new CompositeImage(image, smaskBI);
            BufferedImage rgbImage = compositeImage.createMaskedImage(decodeArray);

            return rgbImage;
        } else if (getImageMask()) {
            BufferedImage stencilMask = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
            Graphics2D graphics = (Graphics2D) stencilMask.getGraphics();
            if (getStencilColor() != null) {
                graphics.setColor(getStencilColor().getJavaColor());
            } else {
                // this might happen when using ExractImages, see PDFBOX-1145
                LOG.debug("no stencil color for PixelMap found, using Color.BLACK instead.");
                graphics.setColor(Color.BLACK);
            }

            graphics.fillRect(0, 0, width, height);
            // assume default values ([0,1]) for the DecodeArray
            // TODO DecodeArray == [1,0]
            graphics.setComposite(AlphaComposite.DstIn);
            graphics.drawImage(image, null, 0, 0);
            return stencilMask;
        } else {
            // if there is no mask, use the unaltered image.
            return image;
        }
    } catch (Exception exception) {
        LOG.error(exception, exception);
        //A NULL return is caught in pagedrawer.Invoke.process() so don't re-throw.
        //Returning the NULL falls through to Phillip Koch's TODO section.
        return null;
    }
}

From source file:org.optaplanner.examples.rocktour.swingui.RockTourWorldPanel.java

public void resetPanel(RockTourSolution solution) {
    translator = new LatitudeLongitudeTranslator();
    RockBus bus = solution.getBus();//from  w w  w . j  a v a 2s.com
    translator.addCoordinates(bus.getStartLocation().getLatitude(), bus.getStartLocation().getLongitude());
    translator.addCoordinates(bus.getEndLocation().getLatitude(), bus.getEndLocation().getLongitude());
    for (RockShow show : solution.getShowList()) {
        translator.addCoordinates(show.getLocation().getLatitude(), show.getLocation().getLongitude());
    }

    Dimension size = getSize();
    double width = size.getWidth();
    double height = size.getHeight();
    translator.prepareFor(width, height);

    Graphics2D g = createCanvas(width, height);
    g.setFont(g.getFont().deriveFont((float) LOCATION_NAME_TEXT_SIZE));
    List<RockShow> showList = solution.getShowList();
    int maxAvailableDateSetSize = showList.stream().mapToInt(show -> show.getAvailableDateSet().size()).max()
            .orElse(-1);
    for (RockShow show : showList) {
        RockLocation location = show.getLocation();
        int x = translator.translateLongitudeToX(location.getLongitude());
        int y = translator.translateLatitudeToY(location.getLatitude());
        double percentage = (double) show.getAvailableDateSet().size() / maxAvailableDateSetSize;
        g.setColor(TangoColorFactory.buildPercentageColor(TangoColorFactory.PLUM_3, TangoColorFactory.PLUM_1,
                percentage));
        g.fillRect(x - 1, y - 1, 3, 3);
        if (location.getCityName() != null && showList.size() <= 500) {
            g.drawString(StringUtils.abbreviate(location.getCityName(), 20), x + 3, y - 3);
        }
        if (show.getDate() != null) {
            g.drawString(DAY_FORMATTER.format(show.getDate()), x + 3, y - 3 + LOCATION_NAME_TEXT_SIZE * 3 / 2);
        }
    }
    g.setColor(TangoColorFactory.ALUMINIUM_4);
    RockLocation busStartLocation = bus.getStartLocation();
    int domicileX = translator.translateLongitudeToX(busStartLocation.getLongitude());
    int domicileY = translator.translateLatitudeToY(busStartLocation.getLatitude());
    g.fillRect(domicileX - 2, domicileY - 2, 5, 5);
    if (busStartLocation.getCityName() != null && showList.size() <= 500) {
        g.drawString(busStartLocation.getCityName(), domicileX + 3, domicileY - 3);
    }
    Set<RockShow> needsBackToDomicileLineSet = new HashSet<>(showList);
    for (RockShow trailingShow : showList) {
        if (trailingShow.getPreviousStandstill() instanceof RockShow) {
            needsBackToDomicileLineSet.remove(trailingShow.getPreviousStandstill());
        }
    }
    g.setColor(TangoColorFactory.CHOCOLATE_1);
    for (RockShow show : showList) {
        if (show.getPreviousStandstill() != null) {
            RockLocation previousLocation = show.getPreviousStandstill().getDepartureLocation();
            RockLocation location = show.getLocation();
            translator.drawRoute(g, previousLocation.getLongitude(), previousLocation.getLatitude(),
                    location.getLongitude(), location.getLatitude(), true, false);
            // Back to bus line
            if (needsBackToDomicileLineSet.contains(show)) {
                translator.drawRoute(g, location.getLongitude(), location.getLatitude(),
                        busStartLocation.getLongitude(), busStartLocation.getLatitude(), true, true);
            }
        }
    }
    g.setFont(g.getFont().deriveFont((float) TEXT_SIZE));
    // Legend
    g.setColor(TangoColorFactory.ALUMINIUM_4);
    g.fillRect(5, (int) height - 17 - TEXT_SIZE, 5, 5);
    g.drawString("Bus start", 15, (int) height - 10 - TEXT_SIZE);
    g.setColor(TangoColorFactory.PLUM_2);
    g.fillRect(6, (int) height - 11, 3, 3);
    g.drawString("Show (darker means less available)", 15, (int) height - 5);
    repaint();
}

From source file:edu.ku.brc.specify.utilapps.ERDVisualizer.java

/**
 * /*from  w  w  w. j  av a2 s  .c  o m*/
 */
public void generate() {
    Rectangle rect = getPanel().getParent().getBounds();
    System.out.println("MAIN[" + rect + "]");
    if (rect.width == 0 || rect.height == 0) {
        return;
    }

    BufferedImage bufImage = new BufferedImage(rect.width, rect.height,
            (doPNG ? BufferedImage.TYPE_INT_ARGB : BufferedImage.TYPE_INT_RGB));
    Graphics2D g2 = bufImage.createGraphics();
    if (!doPNG) {
        g2.setColor(Color.WHITE);
        g2.fillRect(0, 0, rect.width, rect.height);
    }
    g2.setRenderingHints(createTextRenderingHints());
    g2.setFont(tblTracker.getFont());
    getPanel().getParent().paint(g2);

    g2.dispose();

    Component stop = getPanel().getParent();
    Point p = new Point(0, 0);
    calcLoc(p, getPanel().getMainTable(), stop);

    String name = StringUtils.substringAfterLast(getPanel().getMainTable().getClassName(), ".");
    DBTableInfo tblInfo = DBTableIdMgr.getInstance().getByShortClassName(name);
    String fName = schemaDir.getAbsolutePath() + File.separator + name;
    try {
        String origName = fName;
        int i = 1;
        while (pngNameHash.contains(fName)) {
            fName = origName + i;
        }
        pngNameHash.add(fName);

        File html = new File(fName + ".html");
        BufferedWriter output = new BufferedWriter(new FileWriter(html));

        int index = mapTemplate.indexOf(contentTag);
        String subContent = mapTemplate.substring(0, index);
        output.write(StringUtils.replace(subContent, "<!-- Title -->", tblInfo.getTitle()));

        File imgFile = new File(fName + (doPNG ? ".png" : ".jpg"));
        output.write("<map name=\"schema\" id=\"schema\">\n");

        Vector<ERDTable> nList = mainPanel.isRoot() ? tblTracker.getTreeAsList(mainPanel.getMainTable())
                : getPanel().getRelTables();
        for (ERDTable erdt : nList) {
            p = new Point(0, 0);
            calcLoc(p, erdt, stop);
            Dimension s = erdt.getSize();
            String linkname = StringUtils.substringAfterLast(erdt.getClassName(), ".");
            output.write("<area shape=\"rect\" coords=\"" + p.x + "," + p.y + "," + (p.x + s.width) + ","
                    + (p.y + s.height) + "\" href=\"" + linkname + ".html\"/>\n");
        }

        output.write("</map>\n");
        output.write("<img border=\"0\" usemap=\"#schema\" src=\"" + imgFile.getName() + "\"/>\n");

        output.write(mapTemplate.substring(index + contentTag.length() + 1, mapTemplate.length()));

        output.close();

        File oFile = new File(schemaDir + File.separator + imgFile.getName());
        System.out.println(oFile.getAbsolutePath());
        if (doPNG) {
            ImageIO.write(bufImage, "PNG", oFile);
        } else {
            writeJPEG(oFile, bufImage, 0.75f);
        }
        //ImageIO.write(bufImage, "JPG", new File(schemaDir + File.separator + imgFile.getName()+".jpg"));

    } catch (Exception e) {
        edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
        edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(ERDVisualizer.class, e);
        e.printStackTrace();
    }
}

From source file:com.igormaznitsa.mindmap.swing.panel.MindMapPanel.java

private static void drawErrorText(final Graphics2D gfx, final Dimension fullSize, final String error) {
    final Font font = new Font(Font.DIALOG, Font.BOLD, 24);
    final FontMetrics metrics = gfx.getFontMetrics(font);
    final Rectangle2D textBounds = metrics.getStringBounds(error, gfx);
    gfx.setFont(font);//from   w  ww  .java  2 s .  c  om
    gfx.setColor(Color.DARK_GRAY);
    gfx.fillRect(0, 0, fullSize.width, fullSize.height);
    final int x = (int) (fullSize.width - textBounds.getWidth()) / 2;
    final int y = (int) (fullSize.height - textBounds.getHeight()) / 2;
    gfx.setColor(Color.BLACK);
    gfx.drawString(error, x + 5, y + 5);
    gfx.setColor(Color.RED.brighter());
    gfx.drawString(error, x, y);
}

From source file:org.optaplanner.examples.tsp.swingui.TspWorldPanel.java

public void resetPanel(TravelingSalesmanTour travelingSalesmanTour) {
    translator = new LatitudeLongitudeTranslator();
    for (Location location : travelingSalesmanTour.getLocationList()) {
        translator.addCoordinates(location.getLatitude(), location.getLongitude());
    }// w  ww .  ja v  a2s.c  o m

    Dimension size = getSize();
    double width = size.getWidth();
    double height = size.getHeight();
    translator.prepareFor(width, height);

    Graphics2D g = createCanvas(width, height);
    String tourName = travelingSalesmanTour.getName();
    if (tourName.startsWith("europe")) {
        g.drawImage(europaBackground.getImage(), 0, 0, translator.getImageWidth(), translator.getImageHeight(),
                this);
    }
    g.setFont(g.getFont().deriveFont((float) LOCATION_NAME_TEXT_SIZE));
    g.setColor(TangoColorFactory.PLUM_2);
    List<Visit> visitList = travelingSalesmanTour.getVisitList();
    for (Visit visit : visitList) {
        Location location = visit.getLocation();
        int x = translator.translateLongitudeToX(location.getLongitude());
        int y = translator.translateLatitudeToY(location.getLatitude());
        g.fillRect(x - 1, y - 1, 3, 3);
        if (location.getName() != null && visitList.size() <= 500) {
            g.drawString(StringUtils.abbreviate(location.getName(), 20), x + 3, y - 3);
        }
    }
    g.setColor(TangoColorFactory.ALUMINIUM_4);
    Domicile domicile = travelingSalesmanTour.getDomicile();
    Location domicileLocation = domicile.getLocation();
    int domicileX = translator.translateLongitudeToX(domicileLocation.getLongitude());
    int domicileY = translator.translateLatitudeToY(domicileLocation.getLatitude());
    g.fillRect(domicileX - 2, domicileY - 2, 5, 5);
    if (domicileLocation.getName() != null && visitList.size() <= 500) {
        g.drawString(domicileLocation.getName(), domicileX + 3, domicileY - 3);
    }
    Set<Visit> needsBackToDomicileLineSet = new HashSet<Visit>(visitList);
    for (Visit trailingVisit : visitList) {
        if (trailingVisit.getPreviousStandstill() instanceof Visit) {
            needsBackToDomicileLineSet.remove(trailingVisit.getPreviousStandstill());
        }
    }
    g.setColor(TangoColorFactory.CHOCOLATE_1);
    for (Visit visit : visitList) {
        if (visit.getPreviousStandstill() != null) {
            Location previousLocation = visit.getPreviousStandstill().getLocation();
            Location location = visit.getLocation();
            translator.drawRoute(g, previousLocation.getLongitude(), previousLocation.getLatitude(),
                    location.getLongitude(), location.getLatitude(), location instanceof AirLocation, false);
            // Back to domicile line
            if (needsBackToDomicileLineSet.contains(visit)) {
                translator.drawRoute(g, location.getLongitude(), location.getLatitude(),
                        domicileLocation.getLongitude(), domicileLocation.getLatitude(),
                        location instanceof AirLocation, true);
            }
        }
    }
    // Drag
    if (dragSourceStandstill != null) {
        g.setColor(TangoColorFactory.CHOCOLATE_2);
        Location sourceLocation = dragSourceStandstill.getLocation();
        Location targetLocation = dragTargetStandstill.getLocation();
        translator.drawRoute(g, sourceLocation.getLongitude(), sourceLocation.getLatitude(),
                targetLocation.getLongitude(), targetLocation.getLatitude(),
                sourceLocation instanceof AirLocation, dragTargetStandstill instanceof Domicile);
    }
    // Legend
    g.setColor(TangoColorFactory.ALUMINIUM_4);
    g.fillRect(5, (int) height - 15 - TEXT_SIZE, 5, 5);
    g.drawString("Domicile", 15, (int) height - 10 - TEXT_SIZE);
    g.setColor(TangoColorFactory.PLUM_2);
    g.fillRect(6, (int) height - 9, 3, 3);
    g.drawString("Visit", 15, (int) height - 5);
    g.setColor(TangoColorFactory.ALUMINIUM_5);
    String locationsSizeString = travelingSalesmanTour.getLocationList().size() + " locations";
    g.drawString(locationsSizeString, ((int) width - g.getFontMetrics().stringWidth(locationsSizeString)) / 2,
            (int) height - 5);
    if (travelingSalesmanTour.getDistanceType() == DistanceType.AIR_DISTANCE) {
        String leftClickString = "Left click and drag between 2 locations to connect them.";
        g.drawString(leftClickString, (int) width - 5 - g.getFontMetrics().stringWidth(leftClickString),
                (int) height - 10 - TEXT_SIZE);
        String rightClickString = "Right click anywhere on the map to add a visit.";
        g.drawString(rightClickString, (int) width - 5 - g.getFontMetrics().stringWidth(rightClickString),
                (int) height - 5);
    }
    // Show soft score
    g.setColor(TangoColorFactory.ORANGE_3);
    SimpleLongScore score = travelingSalesmanTour.getScore();
    if (score != null) {
        String distanceString = travelingSalesmanTour.getDistanceString(NUMBER_FORMAT);
        g.setFont(g.getFont().deriveFont(Font.BOLD, (float) TEXT_SIZE * 2));
        g.drawString(distanceString, (int) width - g.getFontMetrics().stringWidth(distanceString) - 10,
                (int) height - 15 - 2 * TEXT_SIZE);
    }
    repaint();
}

From source file:bigdataproject.CustomFastScatterPlot.java

@Override
public void render(Graphics2D g2, Rectangle2D dataArea, PlotRenderingInfo info, CrosshairState crosshairState) {
    if (clusters != null) {
        int colorIndex = 0, points = 0;
        String shape = "";
        for (Integer index : clusters.keySet()) {
            float[][] clusterFloat = clusters.get(index);
            for (float[] clusterFloat1 : clusterFloat) {
                points++;/*from   www . j  a va2  s.co m*/
                float x = clusterFloat1[0];
                float y = clusterFloat1[1];
                int size = 6;
                int transX = (int) this.getDomainAxis().valueToJava2D(x, dataArea, RectangleEdge.BOTTOM);
                int transY = (int) this.getRangeAxis().valueToJava2D(y, dataArea, RectangleEdge.LEFT);
                g2.setPaint(colors[colorIndex % 11]);
                if (colorIndex % 2 == 0) {
                    g2.fillOval(transX, transY, size, size);
                    shape = "Round";
                } else {
                    g2.fillRect(transX, transY, size, size);
                    shape = "Square";
                }
            }
            System.out.println("Cluster number: " + colorIndex + " Points: " + clusterFloat.length + " Shape: "
                    + shape + " Color: " + colorArray[colorIndex % 11]);
            colorIndex++;
        }
        System.out.println(
                "\nClustering done! Total clusters: " + colorIndex + " Total points: " + points + "\n");
    }
}

From source file:com.projity.pm.graphic.gantt.GanttRenderer.java

private void drawNonWorking(Graphics2D g2, long startNonworking, long endNonWorking, Calendar cal,
        CoordinatesConverter coord, Rectangle bounds, boolean userScale2) {
    cal.setTimeInMillis(endNonWorking);//from  www  . j a  v a  2s.  c  o m
    if (userScale2)
        coord.getTimescaleManager().getScale().increment2(cal);
    else
        coord.getTimescaleManager().getScale().increment1(cal);
    endNonWorking = cal.getTimeInMillis();
    g2.fillRect((int) Math.round(coord.toX(startNonworking)), bounds.y,
            (int) Math.round(coord.toW(endNonWorking - startNonworking)), bounds.height);
}

From source file:au.org.ala.layers.web.UserDataService.java

@RequestMapping(value = WS_USERDATA_WMS, method = RequestMethod.GET)
public void getPointsMap(
        @RequestParam(value = "CQL_FILTER", required = false, defaultValue = "") String cql_filter,
        @RequestParam(value = "ENV", required = false, defaultValue = "") String env,
        @RequestParam(value = "BBOX", required = false, defaultValue = "") String bboxString,
        @RequestParam(value = "WIDTH", required = false, defaultValue = "") String widthString,
        @RequestParam(value = "HEIGHT", required = false, defaultValue = "") String heightString,
        HttpServletRequest request, HttpServletResponse response) {
    RecordsLookup.setUserDataDao(userDataDao);

    response.setHeader("Cache-Control", "max-age=86400"); //age == 1 day
    response.setContentType("image/png"); //only png images generated

    int width = 256, height = 256;
    try {//from   w  ww  .ja  v  a  2s  .  c  o m
        width = Integer.parseInt(widthString);
        height = Integer.parseInt(heightString);
    } catch (Exception e) {
        logger.error("error parsing to int: " + widthString + " or " + heightString, e);
    }

    try {
        env = URLDecoder.decode(env, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        logger.error("error decoding env from UTF-8: " + env, e);
    }
    int red = 0, green = 0, blue = 0, alpha = 0;
    String name = "circle";
    int size = 4;
    boolean uncertainty = false;
    String highlight = null;
    String colourMode = null;
    for (String s : env.split(";")) {
        String[] pair = s.split(":");
        if (pair[0].equals("color")) {
            while (pair[1].length() < 6) {
                pair[1] = "0" + pair[1];
            }
            red = Integer.parseInt(pair[1].substring(0, 2), 16);
            green = Integer.parseInt(pair[1].substring(2, 4), 16);
            blue = Integer.parseInt(pair[1].substring(4), 16);
        } else if (pair[0].equals("name")) {
            name = pair[1];
        } else if (pair[0].equals("size")) {
            size = Integer.parseInt(pair[1]);
        } else if (pair[0].equals("opacity")) {
            alpha = (int) (255 * Double.parseDouble(pair[1]));
            //            } else if (pair[0].equals("uncertainty")) {
            //                uncertainty = true;
        } else if (pair[0].equals("sel")) {
            try {
                highlight = URLDecoder.decode(s.substring(4), "UTF-8").replace("%3B", ";");
            } catch (Exception e) {
            }
        } else if (pair[0].equals("colormode")) {
            colourMode = pair[1];
        }
    }

    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("error converting bounding box value to double: " + s, e);
        }
    }
    try {

        //adjust bbox extents with half pixel width/height
        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 + (highlight != null ? HIGHLIGHT_RADIUS * 2 + size * 0.2 : 0) + 5);
        double yoffset = (bbox[3] - bbox[1]) / (double) height
                * (size + (highlight != null ? HIGHLIGHT_RADIUS * 2 + size * 0.2 : 0) + 5);

        //check offset for points bb by maximum uncertainty (?? 30k ??)
        if (uncertainty) {
            double xuoffset = 30000;
            double yuoffset = 30000;
            if (xoffset < xuoffset) {
                xoffset = xuoffset;
            }
            if (yoffset < yuoffset) {
                yoffset = yuoffset;
            }
        }

        //adjust offset for pixel height/width
        xoffset += pixelWidth;
        yoffset += pixelHeight;

        double[][] bb = {
                { SpatialUtils.convertMetersToLng(bbox[0] - xoffset),
                        SpatialUtils.convertMetersToLat(bbox[1] - yoffset) },
                { SpatialUtils.convertMetersToLng(bbox[2] + xoffset),
                        SpatialUtils.convertMetersToLat(bbox[3] + yoffset) } };

        double[] pbbox = new double[4]; //pixel bounding box
        pbbox[0] = SpatialUtils.convertLngToPixel(SpatialUtils.convertMetersToLng(bbox[0]));
        pbbox[1] = SpatialUtils.convertLatToPixel(SpatialUtils.convertMetersToLat(bbox[1]));
        pbbox[2] = SpatialUtils.convertLngToPixel(SpatialUtils.convertMetersToLng(bbox[2]));
        pbbox[3] = SpatialUtils.convertLatToPixel(SpatialUtils.convertMetersToLat(bbox[3]));

        String lsid = null;
        int p1 = 0;
        int p2 = cql_filter.indexOf('&', p1 + 1);
        if (p2 < 0) {
            p2 = cql_filter.indexOf(';', p1 + 1);
        }
        if (p2 < 0) {
            p2 = cql_filter.length();
        }
        if (p1 >= 0) {
            lsid = cql_filter.substring(0, p2);
        }

        double[] points = null;
        ArrayList<QueryField> listHighlight = null;
        QueryField colours = null;
        double[] pointsBB = null;
        Facet facet = null;
        String[] facetFields = null;
        if (highlight != null && !(colourMode != null && colourMode.equals("grid"))) {
            facet = Facet.parseFacet(highlight);
            facetFields = facet.getFields();
            listHighlight = new ArrayList<QueryField>();
        }

        int[] idx = null;
        if (lsid != null) {
            Object[] data = (Object[]) RecordsLookup.getData(lsid);
            points = (double[]) data[1];
            pointsBB = (double[]) data[4];
            idx = (int[]) data[5];

            if (points == null || points.length == 0 || pointsBB[0] > bb[1][0] || pointsBB[2] < bb[0][0]
                    || pointsBB[1] > bb[1][1] || pointsBB[3] < bb[0][1]) {
                setImageBlank(response);
                return;
            }

            ArrayList<QueryField> fields = (ArrayList<QueryField>) data[2];

            for (int j = 0; j < fields.size(); j++) {
                if (facet != null) {
                    for (int k = 0; k < facetFields.length; k++) {
                        if (facetFields[k].equals(fields.get(j).getName())) {
                            listHighlight.add(fields.get(j));
                        }
                    }
                }
                if (colourMode != null) {
                    if (fields.get(j).getName().equals(colourMode)) {
                        synchronized (fields.get(j)) {
                            //need to resize 'colours' facet to the correct length and store as new QueryField
                            for (int k = 0; k < fields.size(); k++) {
                                if (fields.get(k).getName().equals(colourMode + " resized")) {
                                    colours = fields.get(k);
                                }
                            }

                            if (colours == null) {
                                colours = fields.get(j);

                                //does it need to be rebuilt to the correct length?
                                int count = colours.getIntData() != null ? colours.getIntData().length
                                        : colours.getLongData() != null ? colours.getLongData().length
                                                : colours.getFloatData() != null ? colours.getFloatData().length
                                                        : colours.getDoubleData() != null
                                                                ? colours.getDoubleData().length
                                                                : 0;
                                if (count != points.length / 2) {
                                    QueryField qf = new QueryField();
                                    qf.setDisplayName(colours.getDisplayName());
                                    qf.setName(colours.getName() + " resized");
                                    for (int k = 0; k < idx.length; k++) {
                                        qf.add(colours.getAsString(idx[k]));
                                    }
                                    qf.store();

                                    fields.add(qf);

                                    colours = qf;
                                }
                            }
                        }
                    }
                }
            }
        }

        /* TODO: make this a copy instead of create */
        BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = (Graphics2D) img.getGraphics();
        g.setColor(new Color(0, 0, 0, 0));
        g.fillRect(0, 0, width, height);

        g.setColor(new Color(red, green, blue, alpha));
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        int x, y;
        int pointWidth = size * 2 + 1;
        double width_mult = (width / (pbbox[2] - pbbox[0]));
        double height_mult = (height / (pbbox[1] - pbbox[3]));

        if (colourMode != null && colourMode.equals("grid")) {
            int divs = 16;
            double grid_width_mult = (width / (pbbox[2] - pbbox[0])) / (256 / divs);
            double grid_height_mult = (height / (pbbox[1] - pbbox[3])) / (256 / divs);
            int[][] gridCounts = new int[divs][divs];
            for (i = 0; i < points.length; i += 2) {
                x = (int) ((SpatialUtils.convertLngToPixel(points[i]) - pbbox[0]) * grid_width_mult);
                y = (int) ((SpatialUtils.convertLatToPixel(points[i + 1]) - pbbox[3]) * grid_height_mult);
                if (x >= 0 && x < divs && y >= 0 && y < divs) {
                    gridCounts[x][y]++;
                }
            }
            int xstep = 256 / divs;
            int ystep = 256 / divs;
            for (x = 0; x < divs; x++) {
                for (y = 0; y < divs; y++) {
                    int v = gridCounts[x][y];
                    if (v > 0) {
                        if (v > 500) {
                            v = 500;
                        }
                        int colour = Legend.getLinearColour(v, 0, 500, 0xFFFFFF00, 0xFFFF0000);
                        g.setColor(new Color(colour));
                        g.fillRect(x * xstep, y * ystep, xstep, ystep);
                    }
                }
            }
        } else {
            //circle type
            if (name.equals("circle")) {
                if (colours == null) {
                    for (i = 0; i < points.length; i += 2) {
                        if (points[i] >= bb[0][0] && points[i] <= bb[1][0] && points[i + 1] >= bb[0][1]
                                && points[i + 1] <= bb[1][1]) {
                            x = (int) ((SpatialUtils.convertLngToPixel(points[i]) - pbbox[0]) * width_mult);
                            y = (int) ((SpatialUtils.convertLatToPixel(points[i + 1]) - pbbox[3])
                                    * height_mult);
                            g.fillOval(x - size, y - size, pointWidth, pointWidth);
                        }
                    }
                } else {
                    int prevColour = -1; //!= colours[0]
                    g.setColor(new Color(prevColour));
                    for (i = 0; i < points.length; i += 2) {
                        if (points[i] >= bb[0][0] && points[i] <= bb[1][0] && points[i + 1] >= bb[0][1]
                                && points[i + 1] <= bb[1][1]) {
                            //colours is made the correct length, see above
                            int thisColour = colours.getColour(i / 2);
                            if (thisColour != prevColour) {
                                g.setColor(new Color(thisColour));
                                prevColour = thisColour;
                            }
                            x = (int) ((SpatialUtils.convertLngToPixel(points[i]) - pbbox[0]) * width_mult);
                            y = (int) ((SpatialUtils.convertLatToPixel(points[i + 1]) - pbbox[3])
                                    * height_mult);
                            g.fillOval(x - size, y - size, pointWidth, pointWidth);
                        }
                    }
                }
            }

            if (highlight != null && facet != null) {
                g.setStroke(new BasicStroke(2));
                g.setColor(new Color(255, 0, 0, 255));
                int sz = size + HIGHLIGHT_RADIUS;
                int w = sz * 2 + 1;

                for (i = 0; i < points.length; i += 2) {
                    if (points[i] >= bb[0][0] && points[i] <= bb[1][0] && points[i + 1] >= bb[0][1]
                            && points[i + 1] <= bb[1][1]) {

                        if (facet.isValid(listHighlight, idx[i / 2])) {
                            x = (int) ((SpatialUtils.convertLngToPixel(points[i]) - pbbox[0]) * width_mult);
                            y = (int) ((SpatialUtils.convertLatToPixel(points[i + 1]) - pbbox[3])
                                    * height_mult);
                            g.drawOval(x - sz, y - sz, w, w);
                        }
                    }
                }
            }
        }

        g.dispose();

        try {
            OutputStream os = response.getOutputStream();
            ImageIO.write(img, "png", os);
            os.flush();
            os.close();
        } catch (IOException e) {
            logger.error("error in outputting wms/reflect image as png", e);
        }
    } catch (Exception e) {
        logger.error("error generating wms/reflect tile", e);
    }

    //logger.debug("[wms tile: " + (System.currentTimeMillis() - start) + "ms]");
}

From source file:me.solhub.simple.engine.DebugLocationsStructure.java

@Override
protected void draw() {
    Graphics2D g = (Graphics2D) getGraphics();
    Graphics2D bbg = (Graphics2D) _backBuffer.getGraphics();

    //anti-aliasing code
    //        bbg.setRenderingHint(
    //                RenderingHints.KEY_TEXT_ANTIALIASING,
    //                RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
    //        bbg.setRenderingHint( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );

    bbg.setColor(Color.WHITE);/*from  w w  w  . j  a  va2 s. co  m*/
    bbg.fillRect(0, 0, _windowWidth, _windowHeight);

    bbg.translate(_xOffset, _yOffset);

    // draw destinations
    bbg.setColor(_simState.startingDestination.getColor());
    bbg.drawOval(-(int) _simState.startingDestination.getRadius(),
            -(int) _simState.startingDestination.getRadius(),
            (int) _simState.startingDestination.getRadius() * 2,
            (int) _simState.startingDestination.getRadius() * 2);
    Iterator<Entry<Vector2D, Color>> blah = _destinationColors.entrySet().iterator();
    double destinationRadius = _simState.getDestinationRadius();
    while (blah.hasNext()) {
        Entry<Vector2D, Color> temp = blah.next();
        bbg.setColor(temp.getValue());
        //calculate center coordinate
        int x = (int) (temp.getKey().getX() - (destinationRadius));
        int y = (int) (temp.getKey().getY() - (destinationRadius));
        //drawOval draws a circle inside a rectangle
        bbg.drawOval(x, y, _simState.getDestinationRadius() * 2, _simState.getDestinationRadius() * 2);
    }

    // draw each of the agents
    Iterator<Agent> agentIter = _simState.getAgentIterator();
    while (agentIter.hasNext()) {
        Agent temp = agentIter.next();
        if (temp.isAlive()) {
            // decide whether to color for destination or group
            //                if( isDestinationColors )
            //                {
            //                    // if stopped then blink white and destination color
            //                    if( temp.hasReachedDestination() )
            //                    {
            //                        if( pulseWhite % 20 == 0 )
            //                        {
            //                            bbg.setColor( Color.WHITE );
            //                        }
            //                        else
            //                        {
            //                            bbg.setColor( temp.getDestinationColor() );
            //                        }
            //                    }
            //                    else
            //                    {
            //                        bbg.setColor( temp.getDestinationColor() );
            //                    }
            //                }
            //                else
            //                {
            //                    // if stopped then blink black and white
            //                    if( temp.hasReachedDestination() )
            //                    {
            //                        if( pulseWhite % 20 == 0 )
            //                        {
            //                            bbg.setColor( Color.WHITE );
            //                        }
            //                        else
            //                        {
            //                            bbg.setColor( temp.getGroup().getGroupColor() );
            //                        }
            //                    }
            //                    //set color to red if cancelled and global and not multiple initiators
            //                    else if(temp.getCurrentDecision().getDecision().getDecisionType().equals(
            //                            DecisionType.CANCELLATION ) 
            //                            && _simState.getCommunicationType().equals( "global" )
            //                            && !Agent.canMultipleInitiate()
            //                            )
            //                    {
            //                        bbg.setColor( Color.RED );
            //                    }
            //                    else
            //                    {
            //                        bbg.setColor( temp.getGroup().getGroupColor() );
            //                    }
            //                }

            double dx = temp.getCurrentDestination().getX() - temp.getCurrentLocation().getX();
            double dy = temp.getCurrentDestination().getY() - temp.getCurrentLocation().getY();
            double heading = Math.atan2(dy, dx);
            Utils.drawDirectionalTriangle(bbg, heading - Math.PI / 2, temp.getCurrentLocation().getX(),
                    temp.getCurrentLocation().getY(), 7, temp.getPreferredDestination().getColor(),
                    temp.getGroup().getGroupColor());

            //                bbg.fillOval( (int) temp.getCurrentLocation().getX() - _agentSize,
            //                        (int) temp.getCurrentLocation().getY() - _agentSize , _agentSize * 2, _agentSize * 2 );
        }
    }
    pulseWhite++;
    bbg.setColor(Color.BLACK);
    // the total number of groups
    bbg.setFont(_infoFont);

    bbg.drawString("Run: " + (_simState.getCurrentSimulationRun() + 1), _fontXOffset, _fontYOffset);
    bbg.drawString("Time: " + _simState.getSimulationTime(), _fontXOffset, _fontYOffset + _fontSize);
    bbg.drawString("Delay: " + LIVE_DELAY, _fontXOffset, _fontYOffset + _fontSize * 2);

    if (_simState.getCommunicationType().equals("global") && !Agent.canMultipleInitiate()) {
        String initiatorName = "None";
        if (_initiatingAgent != null) {
            initiatorName = _initiatingAgent.getId().toString();
        }
        bbg.drawString("Init: " + initiatorName, _fontXOffset, _fontYOffset + _fontSize * 3);
        bbg.drawString("Followers: " + _numberFollowing, _fontXOffset, _fontYOffset + _fontSize * 4);
    } else {
        bbg.drawString("Groups: " + _simState.getNumberGroups(), _fontXOffset, _fontYOffset + _fontSize * 3);
        bbg.drawString("Reached: " + _simState.numReachedDestination, _fontXOffset,
                _fontYOffset + _fontSize * 4);
        bbg.drawString("Inits: " + _simState.numInitiating, _fontXOffset, _fontYOffset + _fontSize * 5);
        bbg.drawString("Eaten: " + _simState.getPredator().getTotalAgentsEaten(), _fontXOffset,
                _fontYOffset + _fontSize * 6);
    }

    g.scale(_zoom, _zoom);
    g.drawImage(_backBuffer, 0, 0, this);
    if (SHOULD_VIDEO) {

        // setup to save to a png
        BufferedImage buff = new BufferedImage(_windowWidth, _windowHeight, BufferedImage.TYPE_INT_RGB);
        Graphics2D temp = (Graphics2D) buff.getGraphics();
        temp.scale(8, 4);
        temp.drawImage(_backBuffer, 0, 0, this);
        // sub-directory
        File dir = new File("video");
        dir.mkdir();
        // format string for filename
        String filename = String.format("video/run-%03d-time-%05d.png", _simState.getCurrentSimulationRun(),
                _simState.getSimulationTime());
        File outputfile = new File(filename);
        // save it
        try {
            ImageIO.write(buff, "png", outputfile);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:org.colombbus.tangara.CommandSelection.java

/**
 * Initializes the icons/*  w w  w  .  j  av a  2  s .c om*/
 *
 */
private void initializeIcons() {
    BufferedImage imageSelected = new BufferedImage(iconSize, iconSize, BufferedImage.TYPE_INT_RGB);
    Graphics2D g = (Graphics2D) imageSelected.getGraphics();
    g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g.setColor(selectedBackgroundColor);
    g.fillRect(0, 0, iconSize, iconSize);
    g.setColor(Color.green);
    g.fillOval(0, 0, iconSize - 1, iconSize - 1);
    iconSelected = new ImageIcon(imageSelected);
    BufferedImage imageNotSelected = new BufferedImage(iconSize, iconSize, BufferedImage.TYPE_INT_RGB);
    g = (Graphics2D) imageNotSelected.getGraphics();
    g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g.setColor(Color.white);
    g.fillRect(0, 0, iconSize, iconSize);
    g.setColor(Color.lightGray);
    g.fillOval(0, 0, iconSize - 1, iconSize - 1);
    iconNotSelected = new ImageIcon(imageNotSelected);
}