Example usage for java.awt Graphics dispose

List of usage examples for java.awt Graphics dispose

Introduction

In this page you can find the example usage for java.awt Graphics dispose.

Prototype

public abstract void dispose();

Source Link

Document

Disposes of this graphics context and releases any system resources that it is using.

Usage

From source file:EventQueuePanel.java

public void actionPerformed(ActionEvent evt) {
    Graphics g = getGraphics();

    displayPrompt(g, "Click to chooose the first point");
    Point p = getClick();//from   ww  w  .  jav a2  s.  co m
    g.drawOval(p.x - 2, p.y - 2, 4, 4);
    displayPrompt(g, "Click to choose the second point");
    Point q = getClick();
    g.drawOval(q.x - 2, q.y - 2, 4, 4);
    g.drawLine(p.x, p.y, q.x, q.y);
    displayPrompt(g, "Done! Press button the start again.");
    g.dispose();
}

From source file:com.eryansky.common.web.servlet.ValidateCodeServlet.java

private void createImage(HttpServletRequest request, HttpServletResponse response) throws IOException {

    response.setHeader("Pragma", "no-cache");
    response.setHeader("Cache-Control", "no-cache");
    response.setDateHeader("Expires", 0);
    response.setContentType("image/jpeg");

    /*//  ww  w .ja v  a  2  s  .c om
     * ??
     */
    String width = request.getParameter("width");
    String height = request.getParameter("height");
    if (StringUtils.isNumeric(width) && StringUtils.isNumeric(height)) {
        w = NumberUtils.toInt(width);
        h = NumberUtils.toInt(height);
    }

    BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
    Graphics g = image.getGraphics();

    /*
     * ?
     */
    createBackground(g);

    /*
     * ?
     */
    String s = createCharacter(g);
    request.getSession().setAttribute(SysConstants.SESSION_VALIDATE_CODE, s);

    g.dispose();
    OutputStream out = response.getOutputStream();
    ImageIO.write(image, "JPEG", out);
    out.close();

}

From source file:edu.umn.cs.spatialHadoop.operations.GeometricPlot.java

/**
 * Combines images of different datasets into one image that is displayed
 * to users./*from w  w w  .j av  a 2s  .c om*/
 * This method is called from the web interface to display one image for
 * multiple selected datasets.
 * @param fs The file system that contains the datasets and images
 * @param files Paths to directories which contains the datasets
 * @param includeBoundaries Also plot the indexing boundaries of datasets
 * @return An image that is the combination of all datasets images
 * @throws IOException
 */
public static BufferedImage combineImages(Configuration conf, Path[] files, boolean includeBoundaries,
        int width, int height) throws IOException {
    BufferedImage result = null;
    // Retrieve the MBRs of all datasets
    Rectangle allMbr = new Rectangle(Double.MAX_VALUE, Double.MAX_VALUE, -Double.MAX_VALUE, -Double.MAX_VALUE);
    for (Path file : files) {
        Rectangle mbr = FileMBR.fileMBR(file, new OperationsParams(conf));
        allMbr.expand(mbr);
    }

    // Adjust width and height to maintain aspect ratio
    if ((allMbr.x2 - allMbr.x1) / (allMbr.y2 - allMbr.y1) > (double) width / height) {
        // Fix width and change height
        height = (int) ((allMbr.y2 - allMbr.y1) * width / (allMbr.x2 - allMbr.x1));
    } else {
        width = (int) ((allMbr.x2 - allMbr.x1) * height / (allMbr.y2 - allMbr.y1));
    }
    result = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);

    for (Path file : files) {
        FileSystem fs = file.getFileSystem(conf);
        if (fs.getFileStatus(file).isDir()) {
            // Retrieve the MBR of this dataset
            Rectangle mbr = FileMBR.fileMBR(file, new OperationsParams(conf));
            // Compute the coordinates of this image in the whole picture
            mbr.x1 = (mbr.x1 - allMbr.x1) * width / allMbr.getWidth();
            mbr.x2 = (mbr.x2 - allMbr.x1) * width / allMbr.getWidth();
            mbr.y1 = (mbr.y1 - allMbr.y1) * height / allMbr.getHeight();
            mbr.y2 = (mbr.y2 - allMbr.y1) * height / allMbr.getHeight();
            // Retrieve the image of this dataset
            Path imagePath = new Path(file, "_data.png");
            if (!fs.exists(imagePath))
                throw new RuntimeException("Image " + imagePath + " not ready");
            FSDataInputStream imageFile = fs.open(imagePath);
            BufferedImage image = ImageIO.read(imageFile);
            imageFile.close();
            // Draw the image
            Graphics graphics = result.getGraphics();
            graphics.drawImage(image, (int) mbr.x1, (int) mbr.y1, (int) mbr.getWidth(), (int) mbr.getHeight(),
                    null);
            graphics.dispose();

            if (includeBoundaries) {
                // Plot also the image of the boundaries
                // Retrieve the image of the dataset boundaries
                imagePath = new Path(file, "_partitions.png");
                if (fs.exists(imagePath)) {
                    imageFile = fs.open(imagePath);
                    image = ImageIO.read(imageFile);
                    imageFile.close();
                    // Draw the image
                    graphics = result.getGraphics();
                    graphics.drawImage(image, (int) mbr.x1, (int) mbr.y1, (int) mbr.getWidth(),
                            (int) mbr.getHeight(), null);
                    graphics.dispose();
                }
            }
        }
    }

    return result;
}

From source file:com.foudroyantfactotum.mod.fousarchive.midi.generation.MidiImageGeneration.java

public ImmutablePair<String, BufferedImage> buildImage() throws InterruptedException, ExecutionException {
    final Future<String> name = pool.submit(new LineProcessor(imgX));
    final BufferedImage mdbf = new BufferedImage(imgX, imgY, BufferedImage.TYPE_BYTE_GRAY);
    final Graphics g = mdbf.getGraphics();

    g.setColor(Color.BLACK);//w  w  w  .  j  a  v a2  s .  c  o m
    g.fillRect(0, 0, imgX, imgY);
    g.setColor(Color.WHITE);

    for (Line l = lines.take(); l != TERMINATE; l = lines.take()) {
        g.drawLine(l.note, (int) Math.round(l.tickStart * imgY), l.note, (int) Math.round(l.tickEnd * imgY));
    }

    pool.shutdown();

    g.dispose();

    return ImmutablePair.of(name.get(), mdbf);
}

From source file:com.baidu.rigel.biplatform.ma.auth.resource.RandomValidateCode.java

/**
 * //from  w  ww  .  java  2s .c  om
 * @param request
 * @param response
 * @param cacheManagerForResource 
 */
public static void getRandcode(HttpServletRequest request, HttpServletResponse response,
        CacheManagerForResource cacheManagerForResource) {
    // BufferedImageImage,Image????
    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
    Graphics g = image.getGraphics(); // ImageGraphics,?????
    g.fillRect(0, 0, width, height);
    g.setFont(new Font("Times New Roman", Font.ROMAN_BASELINE, 18));
    g.setColor(getRandColor(110, 133));
    // 
    for (int i = 0; i <= lineSize; i++) {
        drowLine(g);
    }
    // ?
    String randomString = "";
    for (int i = 1; i <= stringNum; i++) {
        randomString = drowString(g, randomString, i);
    }
    String key = null;
    if (request.getCookies() != null) {
        for (Cookie tmp : request.getCookies()) {
            if (tmp.getName().equals(Constants.RANDOMCODEKEY)) {
                key = tmp.getName();
                cacheManagerForResource.removeFromCache(key);
                break;
            }
        }
    }
    if (StringUtils.isEmpty(key)) {
        key = String.valueOf(System.nanoTime());
    }
    cacheManagerForResource.setToCache(key, randomString);
    final Cookie cookie = new Cookie(Constants.RANDOMCODEKEY, key);
    cookie.setPath(Constants.COOKIE_PATH);
    response.addCookie(cookie);
    g.dispose();
    try {
        ImageIO.write(image, "JPEG", response.getOutputStream()); // ??
    } catch (Exception e) {
        LOG.info(e.getMessage());
    }
}

From source file:com.ikon.module.common.CommonWorkflowModule.java

/**
 * Get Process Definition Image//from  w  w w.  j  a  v  a  2s. com
 */
public static byte[] getProcessDefinitionImage(long processDefinitionId, String node) throws WorkflowException {
    log.debug("getProcessDefinitionImage({}, {})", new Object[] { processDefinitionId, node });
    JbpmContext jbpmContext = JBPMUtils.getConfig().createJbpmContext();
    byte[] image = null;

    try {
        GraphSession graphSession = jbpmContext.getGraphSession();
        org.jbpm.graph.def.ProcessDefinition pd = graphSession.getProcessDefinition(processDefinitionId);
        FileDefinition fileDef = pd.getFileDefinition();

        WorkflowUtils.DiagramInfo dInfo = WorkflowUtils.getDiagramInfo(fileDef.getInputStream("gpd.xml"));
        WorkflowUtils.DiagramNodeInfo dNodeInfo = dInfo.getNodeMap().get(node);
        BufferedImage img = ImageIO.read(fileDef.getInputStream("processimage.jpg"));

        // Obtain all nodes Y and X
        List<Integer> ordenadas = new ArrayList<Integer>();
        List<Integer> abcisas = new ArrayList<Integer>();

        for (WorkflowUtils.DiagramNodeInfo nodeInfo : dInfo.getNodeMap().values()) {
            ordenadas.add(nodeInfo.getY());
            abcisas.add(nodeInfo.getX());
        }

        // Calculate minimal Y
        Collections.sort(ordenadas);
        int fixOrd = ordenadas.get(0) < 0 ? ordenadas.get(0) : 0;

        // Calculate minimal X
        Collections.sort(abcisas);
        int fixAbs = abcisas.get(0) < 0 ? abcisas.get(0) : 0;

        if (dNodeInfo != null) {
            // Select node
            log.debug("DiagramNodeInfo: {}", dNodeInfo);
            Graphics g = img.getGraphics();
            Graphics2D g2d = (Graphics2D) g;
            g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.25F));
            g2d.setColor(Color.blue);
            g2d.fillRect(dNodeInfo.getX() - fixAbs, dNodeInfo.getY() - fixOrd, dNodeInfo.getWidth(),
                    dNodeInfo.getHeight());
            g.dispose();
        }

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(img, "jpg", baos);
        image = baos.toByteArray();
        baos.flush();
        baos.close();
    } catch (JbpmException e) {
        throw new WorkflowException(e.getMessage(), e);
    } catch (IOException e) {
        throw new WorkflowException(e.getMessage(), e);
    } finally {
        jbpmContext.close();
    }

    log.debug("getProcessDefinitionImage: {}", image);
    return image;
}

From source file:org.dd4t.mvc.controllers.AbstractBinaryController.java

private void fillResponse(final HttpServletRequest request, final HttpServletResponse response,
        final Binary binary, final String path, int resizeToWidth) throws IOException {
    InputStream content = null;//from   w  w w .  ja  v a  2 s . c  o  m

    try {
        final long contentLength;
        if (isUseBinaryStorage()) {
            // Check last modified dates
            File binaryFile = new File(path);
            if (!binaryFile.exists() || binary.getLastPublishedDate().isAfter(binaryFile.lastModified())) {
                if (resizeToWidth == -1) {
                    saveBinary(binary, binaryFile);
                } else {
                    File tempBinary = new File(path + ".tmp");
                    saveBinary(binary, tempBinary);
                    content = new FileInputStream(tempBinary);
                    BufferedImage before = ImageIO.read(content);
                    int w = before.getWidth();
                    int h = before.getHeight();
                    float factor = (float) resizeToWidth / w;
                    int newH = Math.round(factor * h);

                    BufferedImage after = new BufferedImage(resizeToWidth, newH, BufferedImage.TYPE_INT_RGB);
                    Graphics g = after.createGraphics();
                    g.drawImage(before, 0, 0, resizeToWidth, newH, null);
                    g.dispose();

                    ImageIO.write(after, getImageType(path), binaryFile);
                }
            }
            content = new FileInputStream(binaryFile);
            contentLength = binaryFile.length();
        } else {
            content = binary.getBinaryData().getInputStream();
            contentLength = binary.getBinaryData().getDataSize();
        }

        response.setContentType(getContentType(binary, path, request));
        response.setHeader(CONTENT_LENGTH, Long.toString(contentLength));
        response.setHeader(LAST_MODIFIED, createDateFormat().format(binary.getLastPublishedDate().toDate()));
        response.setStatus(HttpStatus.OK.value());

        // Write binary data to output stream
        byte[] buffer = new byte[response.getBufferSize()];
        int len;
        while ((len = content.read(buffer)) != -1) {
            response.getOutputStream().write(buffer, 0, len);
        }
    } finally {
        if (content != null) {
            try {
                content.close();
            } catch (IOException e) {
                LOG.error("Failed to close binary input stream", e);
            }
        }
    }
}

From source file:com.actionbazaar.controller.SellController.java

/**
 * Saves the uploaded file into a folder for the user.
 * @param imageFile - image file to be saved
 * @return image id/* w  w  w .  j  a  v a 2 s.  c  o m*/
 */
private String save(UploadedFile imageFile) {
    try {
        File saveFld = new File(imageFolder + File.separator + userDisplay.getUser().getUsername());
        if (!saveFld.exists()) {
            if (!saveFld.mkdir()) {
                logger.log(Level.INFO, "Unable to create folder: {0}", saveFld.getAbsolutePath());
                return null;
            }
        }
        File tmp = File.createTempFile("img", "img");
        IOUtils.copy(imageFile.getInputstream(), new FileOutputStream(tmp));
        File thumbnailImage = new File(saveFld + File.separator + UUID.randomUUID().toString() + ".png");
        File fullResolution = new File(saveFld + File.separator + UUID.randomUUID().toString() + ".png");

        // Create the thumbnail
        BufferedImage image = ImageIO.read(tmp);
        Image thumbnailIm = image.getScaledInstance(310, 210, Image.SCALE_SMOOTH);
        // Convert the thumbnail java.awt.Image into a rendered image which we can save
        BufferedImage thumbnailBi = new BufferedImage(thumbnailIm.getWidth(null), thumbnailIm.getHeight(null),
                BufferedImage.TYPE_INT_RGB);
        Graphics bg = thumbnailBi.getGraphics();
        bg.drawImage(thumbnailIm, 0, 0, null);
        bg.dispose();

        ImageIO.write(thumbnailBi, "png", thumbnailImage);
        // Write out the full resolution image as a thumbnail
        ImageIO.write(image, "png", fullResolution);
        if (!tmp.delete()) {
            logger.log(Level.INFO, "Unable to delete: {0}", tmp.getAbsolutePath());
        }
        String imageId = UUID.randomUUID().toString();
        imageBean.addImage(imageId, new ImageRecord(imageFile.getFileName(), fullResolution.getAbsolutePath(),
                thumbnailImage.getAbsolutePath(), userDisplay.getUser().getUsername()));
        return imageId;
    } catch (Throwable t) {
        logger.log(Level.SEVERE, "Unable to save the image.", t);
        return null;
    }
}

From source file:PrintSampleApp.java

public void paint(Graphics g) {
    Dimension size = getSize();//from  w w  w .  j  a v a 2  s . c  o m
    int width = size.width;
    int height = size.height;
    int x1 = (int) (width * 0.1);
    int x2 = (int) (width * 0.9);
    int y1 = (int) (height * 0.1);
    int y2 = (int) (height * 0.9);
    g.drawRect(x1, y1, x2 - x1, y2 - y1);
    g.drawOval(x1, y1, x2 - x1, y2 - y1);
    g.drawLine(x1, y1, x2, y2);
    g.drawLine(x2, y1, x1, y2);
    String text = "Print Me! ";
    text += text;
    text += text;
    g.drawString(text, x1, (int) ((y1 + y2) / 2));
    g.dispose();
}

From source file:J3dSwingFrame.java

/**
 * Set the texture on our goemetry/*from   w  w  w  .j  a v  a 2  s .  c  o m*/
 * <P>
 * Always specified as a URL so that we may fetch it from anywhere.
 * 
 * @param url
 *            The url to the image.
 */
public void setTexture(URL url) {
    Toolkit tk = Toolkit.getDefaultToolkit();
    Image src_img = tk.createImage(url);
    BufferedImage buf_img = null;

    if (!(src_img instanceof BufferedImage)) {
        // create a component anonymous inner class to give us the image
        // observer we need to get the width and height of the source image.
        Component obs = new Component() {
        };

        int width = src_img.getWidth(obs);
        int height = src_img.getHeight(obs);

        // construct the buffered image from the source data.
        buf_img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);

        Graphics g = buf_img.getGraphics();
        g.drawImage(src_img, 0, 0, null);
        g.dispose();
    } else
        buf_img = (BufferedImage) src_img;

    src_img.flush();

    ImageComponent img_comp = new ImageComponent2D(ImageComponent.FORMAT_RGB, buf_img);

    texture = new Texture2D(Texture.BASE_LEVEL, Texture.RGB, img_comp.getWidth(), img_comp.getHeight());

    appearance.setTexture(texture);

    buf_img.flush();
}