Example usage for java.awt Graphics2D dispose

List of usage examples for java.awt Graphics2D dispose

Introduction

In this page you can find the example usage for java.awt Graphics2D 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:edu.ku.brc.ui.IconManager.java

/**
 * Gets a scaled icon and if it doesn't exist it creates one and scales it
 * @param icon image to be scaled//from ww  w. ja v  a 2  s .c  om
 * @param iconSize the icon size (Std)
 * @param scaledIconSize the new scaled size in pixels
 * @return the scaled icon
 */
public Image getFastScale(final ImageIcon icon, final IconSize iconSize, final IconSize scaledIconSize) {
    if (icon != null) {
        int width = scaledIconSize.size();
        int height = scaledIconSize.size();

        if ((width < 0) || (height < 0)) { //image is nonstd, revert to original size
            width = icon.getIconWidth();
            height = icon.getIconHeight();
        }

        Image imgMemory = createImage(icon.getImage().getSource());
        //make sure all pixels in the image were loaded
        imgMemory = new ImageIcon(imgMemory).getImage();

        BufferedImage thumbImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);

        Graphics2D graphics2D = thumbImage.createGraphics();
        graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        graphics2D.drawImage(imgMemory, 0, 0, width, height, null);
        graphics2D.dispose();

        imgMemory = thumbImage;
        return imgMemory;

    }
    //else
    log.error("Couldn't find icon [" + iconSize + "] to scale to [" + scaledIconSize + "]");
    return null;
}

From source file:org.hydroponics.dao.JDBCHydroponicsDaoImpl.java

public byte[] getThumbnail(BufferedImage buffImage) throws IOException {
    BufferedImage pDestImage = new BufferedImage(Constants.THUMBNAIL_WIDTH, Constants.THUMBNAIL_HEIGHT,
            BufferedImage.TYPE_3BYTE_BGR);

    AffineTransform transform = new AffineTransform();
    transform.scale((float) Constants.THUMBNAIL_WIDTH / (float) buffImage.getWidth(),
            (float) Constants.THUMBNAIL_HEIGHT / (float) buffImage.getHeight());

    Graphics2D g = (Graphics2D) pDestImage.getGraphics();

    //set the rendering hints for a good thumbnail image
    Map m = g.getRenderingHints();
    m.put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    m.put(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
    m.put(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    m.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
    g.setRenderingHints(m);/*from ww  w .j a v  a2s .c o m*/

    g.drawImage(buffImage, transform, null);
    g.dispose();

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ImageIO.write(pDestImage, "JPEG", out);
    return out.toByteArray();
}

From source file:com.stanley.captioner.Transcriber.java

public void start() {
    // Create stream speech recognizer.
    StreamSpeechRecognizer recognizer = null;
    try {/*from   w  w  w .  j  a  va2  s  . c o  m*/
        recognizer = new StreamSpeechRecognizer(config);
    } catch (IOException e) {
        System.out.println("Failed to create recognizer.");
    }

    // Open print writer for writing text output.
    PrintWriter writer = null;
    try {
        writer = new PrintWriter(textOut);
    } catch (FileNotFoundException e) {
        System.out.println("Failed to create print writer.");
    }

    // Open stream for first pass.
    InputStream stream = null;
    try {
        stream = new FileInputStream(audio);
    } catch (FileNotFoundException e) {
        System.out.println("Failed to stream file.");
    }

    // Initialize loop variables.
    SpeechResult result;
    int resultCount = 0;
    Stats stats = recognizer.createStats(1);

    // Start recognizer for first pass.
    recognizer.startRecognition(stream);
    System.out.println("First pass (stats collection) started.");

    // First pass loop to collect statistics for model adaptation.
    while ((result = recognizer.getResult()) != null) {
        try {
            stats.collect(result);
        } catch (Exception e) {
            System.out.println("Failed to collect stats.");
        }

        resultCount++;

        // Toggle for testing.
        if (quickTest && resultCount > 5) {
            break;
        }
    }
    // Close recognizer (end of first pass).
    recognizer.stopRecognition();
    System.out.println("Stats collection stopped.");

    // Transform model using model adaptation.
    Transform transform = stats.createTransform();
    recognizer.setTransform(transform);

    // Reopen stream for second pass.
    stream = null;
    try {
        stream = new FileInputStream(audio);
    } catch (FileNotFoundException e) {
        System.out.println("Failed to stream file.");
    }

    // Start recognizer for second pass.
    recognizer.startRecognition(stream);
    System.out.println("Second pass started.");

    // Create output text file header.
    writer.printf("%-20s", "WORD:");
    writer.printf("%20s", "CONFIDENCE:");
    writer.printf("%20s", "START TIME:");
    writer.printf("%20s", "END_TIME:");
    writer.println();
    for (int i = 0; i < 80; i++) {
        writer.print("-");
    }
    writer.println();

    // Initialize loop variables.
    int wordCount = 0;
    String sentence = "";
    int sentenceLength = 0;
    long sentenceStart = 0;
    long sentenceEnd = 0;
    ArrayList<Sentence> sentences = new ArrayList<>();

    // Second pass loop to calculate sentences.
    RECOG: while ((result = recognizer.getResult()) != null) {
        for (WordResult wordResult : result.getWords()) {
            wordCount++;
            String word = wordResult.getWord().toString();
            double confidence = wordResult.getConfidence();
            long startTime = wordResult.getTimeFrame().getStart();
            long endTime = wordResult.getTimeFrame().getEnd();
            writer.printf("%-20s", word);
            writer.printf("%20.1f", confidence);
            writer.printf("%20d", startTime);
            writer.printf("%20d", endTime);
            writer.println();

            if (sentenceLength + word.length() < 40) {
                // Add to current sentence.
                sentence += " " + word;
                sentenceLength += word.length();
                sentenceEnd = endTime;
            } else {
                // End of current sentence, store and start a new one.
                sentences.add(new Sentence(sentence, sentenceStart, sentenceEnd));
                sentenceStart = sentenceEnd;
                sentence = "";
                sentenceLength = 0;
            }

            // Toggle for testing.
            if (quickTest && wordCount > 50) {
                break RECOG;
            }
        }
    }

    // Close print writer and recognizer (end of second pass).
    writer.close();
    recognizer.stopRecognition();
    System.out.println("Second pass stopped.");

    // Create folder for caption images.
    String imageDirPath = FilenameUtils.concat(textOut.getParent(),
            FilenameUtils.getBaseName(textOut.getAbsolutePath()));
    System.out.println(imageDirPath);
    File imageDir = new File(imageDirPath);
    if (!imageDir.exists()) {
        // Create the folder if it doesn't already exist.
        imageDir.mkdir();
    }

    // Calculate video output path.
    String videoOutPath = FilenameUtils.concat(textOut.getParent(),
            FilenameUtils.getBaseName(textOut.getAbsolutePath()) + ".mp4");
    System.out.println(videoOutPath);

    // Initialize a command string for overlaying the captions.
    String commandString = String.format("%s -y -loglevel quiet -i %s", new Converter().getFFmpegPath(),
            videoIn.getAbsolutePath());
    System.out.println(commandString);

    // Initialize a complex filter for overlaying the captions.
    String filterString = "-filter_complex";

    // Acquire a probe object for collecting video details.
    Converter converter = new Converter();
    FFprobe ffprobe = null;
    try {
        ffprobe = new FFprobe(converter.getFFprobePath());
    } catch (IOException e) {
        System.out.println("Failed to find ffprobe.");
    }

    // Probe the video for details.
    FFmpegProbeResult probeResult = null;
    try {
        probeResult = ffprobe.probe(videoIn.getAbsolutePath());
    } catch (IOException e) {
        System.out.println("Failed to probe video file.");
    }

    // Get the width and height of the video.
    FFmpegStream videoStream = probeResult.getStreams().get(0);
    int videoWidth = videoStream.width;
    int videoHeight = videoStream.height;

    // Calculate the x and y coordinates of the captions.
    int captionX = (videoWidth / 2) - 220;
    int captionY = videoHeight - 25 - 10;

    // Loop over the sentences, generate captions, and build command string.
    int k = 0;
    for (Sentence s : sentences) {
        // Create caption image from sentence.
        BufferedImage bi = new BufferedImage(440, 50, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = bi.createGraphics();
        g.setPaint(new Color(0, 0, 0, 128));
        g.fillRect(0, 0, 440, 50);
        g.setPaint(new Color(255, 255, 255, 255));
        g.setFont(new Font("Serif", Font.BOLD, 20));
        FontMetrics fm = g.getFontMetrics();
        int x = bi.getWidth() - fm.stringWidth(s.text) - 5;
        int y = fm.getHeight() - 5;
        g.drawString(s.text, x, y);
        g.dispose();

        // Write the image to file for future reference.
        String suffix = String.format("caption-%03d.png", k);
        String imagePath = FilenameUtils.concat(imageDirPath, suffix);
        try {
            File imageFile = new File(imagePath);
            ImageIO.write(bi, "png", imageFile);
        } catch (IOException e) {
            System.out.println("Failed to write caption image to file.");
        }

        // Add the caption image path to the command string.
        commandString += " -i " + imagePath;

        // Add an entry to the complex filter with the caption timeframe.
        if (k == 0) {
            filterString += String.format(" \"[0:v][1:v] overlay=%d:%d:enable='between(t,%d,%d)'%s", captionX,
                    captionY, s.startTime / 1000, s.endTime / 1000,
                    (k == sentences.size() - 1) ? "\"" : " [tmp];");
        } else {
            filterString += String.format(" [tmp][%d:v] overlay=%d:%d:enable='between(t,%d,%d)'%s", k + 1,
                    captionX, captionY, s.startTime / 1000, s.endTime / 1000,
                    (k == sentences.size() - 1) ? "\"" : " [tmp];");
        }
        k++;
    }

    // Build final command string.
    String finalCommand = String.format("%s %s -codec:a copy %s", commandString, filterString, videoOutPath);

    System.out.println(finalCommand);

    // Attempt to run the final command string to embed the captions.
    try {
        Process p = Runtime.getRuntime().exec(finalCommand);
        try {
            if (p.waitFor() != 0) {
                // Embedding the captions failed.
                System.out.println("Image overlay failed.");
            }
        } catch (InterruptedException e) {
            // Embedding the captions was interrupted.
            System.out.println("Interrupted image overlay.");
        }
    } catch (IOException e) {
        // Command string failed to execute.
        System.out.println("Failed to execute image overlay.");
    }

    // Delete intermediate audio file.
    audio.delete();

    System.out.println("........................CAPTIONING COMPLETE........................");
}

From source file:main.MapKit.java

@Override
public void paintWaypoint(Graphics2D g, JXMapViewer viewer, MyWaypoint w) {
    g = (Graphics2D) g.create();//from   w  w  w .  j a v  a 2s .  c o  m

    Point2D point = viewer.getTileFactory().geoToPixel(w.getPosition(), viewer.getZoom());
    int x = (int) point.getX();
    int y = (int) point.getY();

    if (w.amount == -1) { //means it's an original data point
        int fontSize = 28 - viewer.getZoom() * 2; //font size is larger when zoom in
        if (fontSize < 6)
            fontSize = 6;
        g.setFont(new Font("Arial", Font.PLAIN, fontSize));
        g.setColor(w.color);
        g.drawString("x", x - fontSize / 2, y + fontSize / 2);
        g.dispose();
        return;
    }

    if (origImage == null) {
        return;
    }

    BufferedImage myImg = map.get(w.color);

    if (myImg == null) {
        myImg = convert(origImage, w.color);
        map.put(w.color, myImg);
    }

    g.drawImage(myImg, x - myImg.getWidth() / 2, y - myImg.getHeight(), null);

    String label = String.valueOf(w.amount);

    //      g.setFont(font);
    FontMetrics metrics = g.getFontMetrics();
    int tw = metrics.stringWidth(label);
    int th = 1 + metrics.getAscent();

    //      g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g.drawString(label, x - tw / 2, y + th);

    g.dispose();
}

From source file:jboost.visualization.HistogramFrame.java

private void toPDF() {

    File pdf = selectPDFFile();//from  w  w w. jav  a 2s  . c  om

    if (pdf != null) {

        JComponent toDraw = this.jSplitPane2;

        File[] tmpFiles = new File[infoParser.maxNumIter];

        for (int i = 0; i < infoParser.maxNumIter; i++) {

            post("Printing " + infoParser.iterNoList[i] + "...");

            jList1.setSelectedIndex(i);
            jList1.scrollRectToVisible(jList1.getCellBounds(i, i));
            loadIteration(i);

            BufferedImage bimg = new BufferedImage(toDraw.getWidth(), toDraw.getHeight(),
                    BufferedImage.TYPE_INT_RGB);
            Graphics2D g = bimg.createGraphics();
            toDraw.paint(g);
            g.dispose();

            // add leading zeros
            String file_idx = Integer.toString(i);
            while (file_idx.length() < 3)
                file_idx = "0" + file_idx;

            try {
                tmpFiles[i] = new File("scorevistmp" + file_idx + ".png");
                javax.imageio.ImageIO.write(bimg, "png", tmpFiles[i]);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

        // restore plots
        jList1.setSelectedIndex(iter);
        loadIteration(iter);

        boolean success = true;

        // call convert to make pdf
        try {
            Process p = Runtime.getRuntime().exec("convert scorevistmp*.png " + pdf.getAbsolutePath());
            p.waitFor();
        } catch (Exception e) {
            success = false;
        }

        if (!success) {
            System.out.println("'convert' is missing. You need to have ImageMagick installed.");
            System.out.println("PDF is not generated but you can find PNG files in the current directory.");
        } else {
            /*
             * for (int i=0;i<maxNumIter-1;i++) { tmpFiles[i].delete(); }
             */

            if (infoParser.maxNumIter > 0) {
                tmpFiles[infoParser.maxNumIter - 1].renameTo(new File(pdf.getAbsolutePath() + ".png"));
            }

            JOptionPane.showMessageDialog(this, "PDF file is generated!", "Done",
                    JOptionPane.INFORMATION_MESSAGE);
        }
    }
}

From source file:TexturedPanel.java

/**
 * Creates a new TexturePaint using the provided colors and texture map.
 *///w  w w  . j  a v a 2  s .c  om
private void setupTexturePainter(Color foreground, Color background, boolean[][] texture, int scale) {
    if (texture == null || texture.length < 1 || texture[0].length < 1) {
        setupDefaultPainter(foreground, background);
        return;
    }

    else if (foreground == null || background == null) {
        ourPainter = null;
        return;
    }

    scale = Math.max(1, scale);
    int w = texture[0].length;
    int h = texture.length;

    BufferedImage buff = new BufferedImage(w * scale, h * scale, BufferedImage.TYPE_INT_ARGB_PRE);

    Graphics2D g2 = buff.createGraphics();

    g2.setColor(background);
    g2.fillRect(0, 0, w * scale, h * scale);

    g2.setColor(foreground);
    for (int i = 0; i < h; i++) {
        for (int j = 0; j < w; j++) {
            try {
                if (texture[i][j])
                    g2.fillRect(j * scale, i * scale, scale, scale);
            }
            // g2.drawLine(j, i, j, i); }
            catch (ArrayIndexOutOfBoundsException aob) {
            }
        }
    }

    ourPainter = new TexturePaint(buff, new Rectangle(0, 0, w * scale, h * scale));

    g2.dispose();
}

From source file:Main.java

private void renderImage() throws Exception {
    if (alignment == LINEAR_LEFT_TO_RIGHT) {
        int[] rgbRange = loadRGBRange(width, rgbs, positions);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                pixels[x + y * width] = rgbRange[x];
            }//  w w w  . j a  v  a2 s .com
        }
    } else if (alignment == LINEAR_RIGHT_TO_LEFT) {
        int[] rgbRange = loadRGBRange(width, rgbs, positions);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                pixels[x + y * width] = rgbRange[width - x - 1];
            }
        }
    } else if (alignment == LINEAR_BOTTOM_TO_TOP) {
        int[] rgbRange = loadRGBRange(height, rgbs, positions);
        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {
                pixels[x + y * width] = rgbRange[height - y - 1];
            }
        }
    } else if (alignment == LINEAR_TOP_TO_BOTTOM) {
        int[] rgbRange = loadRGBRange(height, rgbs, positions);
        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {
                pixels[x + y * width] = rgbRange[y];
            }
        }
    } else if (alignment == RADIAL_FROM_TOP_LEFT_CORNER) {
        int[] rgbRange = loadRGBRange((int) Math.sqrt((width - 1) * (width - 1) + (height - 1) * (height - 1)),
                rgbs, positions);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                pixels[x + y * width] = rgbRange[(int) Math.sqrt((x - 1) * (x - 1) + (y - 1) * (y - 1))];
            }
        }
    } else if (alignment == RADIAL_FROM_BOTTOM_LEFT_CORNER) {
        int[] rgbRange = loadRGBRange((int) Math.sqrt((width - 1) * (width - 1) + (height - 1) * (height - 1)),
                rgbs, positions);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                pixels[x + (height - y - 1) * width] = rgbRange[(int) Math
                        .sqrt((x - 1) * (x - 1) + (y - 1) * (y - 1))];
            }
        }
    } else if (alignment == RADIAL_FROM_TOP_RIGHT_CORNER) {
        int[] rgbRange = loadRGBRange((int) Math.sqrt((width - 1) * (width - 1) + (height - 1) * (height - 1)),
                rgbs, positions);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                pixels[(width - x - 1)
                        + y * width] = rgbRange[(int) Math.sqrt((x - 1) * (x - 1) + (y - 1) * (y - 1))];
            }
        }
    } else if (alignment == RADIAL_FROM_BOTTOM_RIGHT_CORNER) {
        int[] rgbRange = loadRGBRange((int) Math.sqrt((width - 1) * (width - 1) + (height - 1) * (height - 1)),
                rgbs, positions);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                pixels[(width - x - 1) + (height - y - 1) * width] = rgbRange[(int) Math
                        .sqrt((x - 1) * (x - 1) + (y - 1) * (y - 1))];
            }
        }
    } else if (alignment == RADIAL_FROM_CENTER) {
        int[] divArray = divideArray(positions, 2);
        BufferedImage quad1 = new GradientImage(width >> 1, height >> 1, colors, divArray,
                GradientImage.RADIAL_FROM_BOTTOM_RIGHT_CORNER).getImage();
        BufferedImage quad2 = new GradientImage(width >> 1, height >> 1, colors, divArray,
                GradientImage.RADIAL_FROM_BOTTOM_LEFT_CORNER).getImage();
        BufferedImage quad3 = new GradientImage(width >> 1, height >> 1, colors, divArray,
                GradientImage.RADIAL_FROM_TOP_RIGHT_CORNER).getImage();
        BufferedImage quad4 = new GradientImage(width >> 1, height >> 1, colors, divArray,
                GradientImage.RADIAL_FROM_TOP_LEFT_CORNER).getImage();
        Graphics2D g = image.createGraphics();
        g.drawImage(quad1, 0, 0, null);
        g.drawImage(quad2, width >> 1, 0, null);
        g.drawImage(quad3, 0, height >> 1, null);
        g.drawImage(quad4, width >> 1, height >> 1, null);
        g.dispose();
    } else if (alignment == RADIAL_FROM_CORNERS) {
        int[] divArray = divideArray(positions, 2);
        BufferedImage quad1 = new GradientImage(width >> 1, height >> 1, colors, divArray,
                GradientImage.RADIAL_FROM_TOP_LEFT_CORNER).getImage();
        BufferedImage quad2 = new GradientImage(width >> 1, height >> 1, colors, divArray,
                GradientImage.RADIAL_FROM_TOP_RIGHT_CORNER).getImage();
        BufferedImage quad3 = new GradientImage(width >> 1, height >> 1, colors, divArray,
                GradientImage.RADIAL_FROM_BOTTOM_LEFT_CORNER).getImage();
        BufferedImage quad4 = new GradientImage(width >> 1, height >> 1, colors, divArray,
                GradientImage.RADIAL_FROM_BOTTOM_RIGHT_CORNER).getImage();
        Graphics2D g = image.createGraphics();
        g.drawImage(quad1, 0, 0, null);
        g.drawImage(quad2, width >> 1, 0, null);
        g.drawImage(quad3, 0, height >> 1, null);
        g.drawImage(quad4, width >> 1, height >> 1, null);
        g.dispose();
    } else if (alignment == LINEAR_DIAGONAL_UP) {
        int[] rgbRange = loadRGBRange((int) Math.sqrt((width - 1) * (width - 1) + (height - 1) * (height - 1)),
                rgbs, positions);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                pixels[x + (height - y - 1) * width] = rgbRange[Math.max(y - x, x - y)];
            }
        }
    } else if (alignment == LINEAR_DIAGONAL_DOWN) {
        int[] rgbRange = loadRGBRange((int) Math.sqrt((width - 1) * (width - 1) + (height - 1) * (height - 1)),
                rgbs, positions);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                pixels[x + y * width] = rgbRange[Math.max(y - x, x - y)];
            }
        }
    } else if (alignment == LINEAR_FROM_TOP_RIGHT_CORNER) {
        int[] rgbRange = loadRGBRange((width + height) >> 1, rgbs, positions);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                pixels[x + (height - y - 1) * width] = rgbRange[rgbRange.length - ((x + y) >> 1) - 1];
            }
        }
    } else if (alignment == LINEAR_FROM_TOP_LEFT_CORNER) {
        int[] rgbRange = loadRGBRange((width + height) >> 1, rgbs, positions);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                pixels[(width - x - 1) + (height - y - 1) * width] = rgbRange[rgbRange.length - ((x + y) >> 1)
                        - 1];
            }
        }
    } else if (alignment == LINEAR_FROM_BOTTOM_RIGHT_CORNER) {
        int[] rgbRange = loadRGBRange((width + height) >> 1, rgbs, positions);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                pixels[x + y * width] = rgbRange[rgbRange.length - ((x + y) >> 1) - 1];
            }
        }
    } else if (alignment == LINEAR_FROM_BOTTOM_LEFT_CORNER) {
        int[] rgbRange = loadRGBRange((width + height) >> 1, rgbs, positions);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                pixels[(width - x - 1) + y * width] = rgbRange[rgbRange.length - ((x + y) >> 1) - 1];
            }
        }
    } else if (alignment == LINEAR_FROM_CENTER) {
        int[] divArray = divideArray(positions, 2);
        BufferedImage quad1 = new GradientImage(width >> 1, height >> 1, colors, divArray,
                GradientImage.LINEAR_FROM_BOTTOM_RIGHT_CORNER).getImage();
        BufferedImage quad2 = new GradientImage(width >> 1, height >> 1, colors, divArray,
                GradientImage.LINEAR_FROM_BOTTOM_LEFT_CORNER).getImage();
        BufferedImage quad3 = new GradientImage(width >> 1, height >> 1, colors, divArray,
                GradientImage.LINEAR_FROM_TOP_RIGHT_CORNER).getImage();
        BufferedImage quad4 = new GradientImage(width >> 1, height >> 1, colors, divArray,
                GradientImage.LINEAR_FROM_TOP_LEFT_CORNER).getImage();
        Graphics2D g = image.createGraphics();
        g.drawImage(quad1, 0, 0, null);
        g.drawImage(quad2, width >> 1, 0, null);
        g.drawImage(quad3, 0, height >> 1, null);
        g.drawImage(quad4, width >> 1, height >> 1, null);
        g.dispose();
    } else if (alignment == LINEAR_FROM_CORNERS) {
        int[] divArray = divideArray(positions, 2);
        BufferedImage quad1 = new GradientImage(width >> 1, height >> 1, colors, divArray,
                GradientImage.LINEAR_FROM_TOP_LEFT_CORNER).getImage();
        BufferedImage quad2 = new GradientImage(width >> 1, height >> 1, colors, divArray,
                GradientImage.LINEAR_FROM_TOP_RIGHT_CORNER).getImage();
        BufferedImage quad3 = new GradientImage(width >> 1, height >> 1, colors, divArray,
                GradientImage.LINEAR_FROM_BOTTOM_LEFT_CORNER).getImage();
        BufferedImage quad4 = new GradientImage(width >> 1, height >> 1, colors, divArray,
                GradientImage.LINEAR_FROM_BOTTOM_RIGHT_CORNER).getImage();
        Graphics2D g = image.createGraphics();
        g.drawImage(quad1, 0, 0, null);
        g.drawImage(quad2, width >> 1, 0, null);
        g.drawImage(quad3, 0, height >> 1, null);
        g.drawImage(quad4, width >> 1, height >> 1, null);
        g.dispose();
    } else if (alignment == PATH_FROM_TOP_LEFT_CORNER) {
        int[] rgbRange = loadRGBRange(Math.max(width, height), rgbs, positions);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                pixels[x + y * width] = rgbRange[Math.max(x, y)];
            }
        }
    } else if (alignment == PATH_FROM_TOP_RIGHT_CORNER) {
        int[] rgbRange = loadRGBRange(Math.max(width, height), rgbs, positions);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                pixels[(width - x - 1) + y * width] = rgbRange[Math.max(x, y)];
            }
        }
    } else if (alignment == PATH_FROM_BOTTOM_LEFT_CORNER) {
        int[] rgbRange = loadRGBRange(Math.max(width, height), rgbs, positions);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                pixels[x + (height - y - 1) * width] = rgbRange[Math.max(x, y)];
            }
        }
    } else if (alignment == PATH_FROM_BOTTOM_RIGHT_CORNER) {
        int[] rgbRange = loadRGBRange(Math.max(width, height), rgbs, positions);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                pixels[(width - x - 1) + (height - y - 1) * width] = rgbRange[Math.max(x, y)];
            }
        }
    } else if (alignment == PATH_FROM_CENTER) {
        int[] divArray = divideArray(positions, 2);
        BufferedImage quad1 = new GradientImage(width >> 1, height >> 1, colors, divArray,
                GradientImage.PATH_FROM_BOTTOM_RIGHT_CORNER).getImage();
        BufferedImage quad2 = new GradientImage(width >> 1, height >> 1, colors, divArray,
                GradientImage.PATH_FROM_BOTTOM_LEFT_CORNER).getImage();
        BufferedImage quad3 = new GradientImage(width >> 1, height >> 1, colors, divArray,
                GradientImage.PATH_FROM_TOP_RIGHT_CORNER).getImage();
        BufferedImage quad4 = new GradientImage(width >> 1, height >> 1, colors, divArray,
                GradientImage.PATH_FROM_TOP_LEFT_CORNER).getImage();
        Graphics2D g = image.createGraphics();
        g.drawImage(quad1, 0, 0, null);
        g.drawImage(quad2, width >> 1, 0, null);
        g.drawImage(quad3, 0, height >> 1, null);
        g.drawImage(quad4, width >> 1, height >> 1, null);
        g.dispose();
    } else if (alignment == PATH_FROM_CORNERS) {
        int[] divArray = divideArray(positions, 2);
        BufferedImage quad1 = new GradientImage(width >> 1, height >> 1, colors, divArray,
                GradientImage.PATH_FROM_TOP_LEFT_CORNER).getImage();
        BufferedImage quad2 = new GradientImage(width >> 1, height >> 1, colors, divArray,
                GradientImage.PATH_FROM_TOP_RIGHT_CORNER).getImage();
        BufferedImage quad3 = new GradientImage(width >> 1, height >> 1, colors, divArray,
                GradientImage.PATH_FROM_BOTTOM_LEFT_CORNER).getImage();
        BufferedImage quad4 = new GradientImage(width >> 1, height >> 1, colors, divArray,
                GradientImage.PATH_FROM_BOTTOM_RIGHT_CORNER).getImage();
        Graphics2D g = image.createGraphics();
        g.drawImage(quad1, 0, 0, null);
        g.drawImage(quad2, width >> 1, 0, null);
        g.drawImage(quad3, 0, height >> 1, null);
        g.drawImage(quad4, width >> 1, height >> 1, null);
        g.dispose();
    }
}

From source file:net.sf.webphotos.tools.Thumbnail.java

private static Image estampar(Image im) {
    try {/*from ww w. ja  v  a 2 s  .co  m*/
        Image temp = new ImageIcon(im).getImage();

        BufferedImage buf = new BufferedImage(temp.getWidth(null), temp.getHeight(null),
                BufferedImage.TYPE_INT_RGB);

        Graphics2D g2 = (Graphics2D) buf.getGraphics();

        g2.drawImage(temp, 0, 0, null);
        g2.setBackground(Color.BLUE);

        Dimension dimensaoFoto = new Dimension(im.getWidth(null), im.getHeight(null));

        // aplicar texto
        if (texto != null) {
            Util.out.println("aplicando texto " + texto);

            Font fonte = new Font(txFamilia, txEstilo, txTamanho);
            g2.setFont(fonte);
            FontMetrics fm = g2.getFontMetrics(fonte);
            Dimension dimensaoTexto = new Dimension(fm.stringWidth(texto), fm.getHeight());
            Point posTexto = calculaPosicao(dimensaoFoto, dimensaoTexto, txMargem, txPosicao);

            g2.setPaint(txCorFundo);
            g2.drawString(texto, (int) posTexto.getX() + 1, (int) posTexto.getY() + 1 + fm.getHeight());
            g2.setPaint(txCorFrente);
            g2.drawString(texto, (int) posTexto.getX(), (int) posTexto.getY() + fm.getHeight());
        }

        // aplicar marca dagua
        if (marcadagua != null) {
            Image marca = new ImageIcon(marcadagua).getImage();
            int rule = AlphaComposite.SRC_OVER;
            float alpha = (float) mdTransparencia / 100;
            Point pos = calculaPosicao(dimensaoFoto, new Dimension(marca.getWidth(null), marca.getHeight(null)),
                    mdMargem, mdPosicao);

            g2.setComposite(AlphaComposite.getInstance(rule, alpha));
            g2.drawImage(marca, (int) pos.getX(), (int) pos.getY(), null);
        }

        g2.dispose();
        //return (Image) buf;
        return Toolkit.getDefaultToolkit().createImage(buf.getSource());
    } catch (Exception e) {
        Util.err.println("[Thumbnail.estampar]/ERRO: Inesperado - " + e.getMessage());
        e.printStackTrace(Util.err);
        return im;
    }
}

From source file:com.tascape.qa.th.android.driver.App.java

/**
 * The method starts a GUI to let an user inspect element tree and take screenshot when the user is interacting
 * with the app-under-test manually. Please make sure to set timeout long enough for manual interaction.
 *
 * @param timeoutMinutes timeout in minutes to fail the manual steps
 *
 * @throws Exception if case of error/*from w ww  .  j  a v  a2  s . co m*/
 */
public void interactManually(int timeoutMinutes) throws Exception {
    LOG.info("Start manual UI interaction");
    long end = System.currentTimeMillis() + timeoutMinutes * 60000L;

    AtomicBoolean visible = new AtomicBoolean(true);
    AtomicBoolean pass = new AtomicBoolean(false);
    String tName = Thread.currentThread().getName() + "m";
    SwingUtilities.invokeLater(() -> {
        JDialog jd = new JDialog((JFrame) null, "Manual Device UI Interaction - " + device.getProductDetail());
        jd.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);

        JPanel jpContent = new JPanel(new BorderLayout());
        jd.setContentPane(jpContent);
        jpContent.setPreferredSize(new Dimension(1088, 828));
        jpContent.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));

        JPanel jpInfo = new JPanel();
        jpContent.add(jpInfo, BorderLayout.PAGE_START);
        jpInfo.setLayout(new BorderLayout());
        {
            JButton jb = new JButton("PASS");
            jb.setForeground(Color.green.darker());
            jb.setFont(jb.getFont().deriveFont(Font.BOLD));
            jpInfo.add(jb, BorderLayout.LINE_START);
            jb.addActionListener(event -> {
                pass.set(true);
                jd.dispose();
                visible.set(false);
            });
        }
        {
            JButton jb = new JButton("FAIL");
            jb.setForeground(Color.red);
            jb.setFont(jb.getFont().deriveFont(Font.BOLD));
            jpInfo.add(jb, BorderLayout.LINE_END);
            jb.addActionListener(event -> {
                pass.set(false);
                jd.dispose();
                visible.set(false);
            });
        }

        JLabel jlTimeout = new JLabel("xxx seconds left", SwingConstants.CENTER);
        jpInfo.add(jlTimeout, BorderLayout.CENTER);
        jpInfo.add(jlTimeout, BorderLayout.CENTER);
        new SwingWorker<Long, Long>() {
            @Override
            protected Long doInBackground() throws Exception {
                while (System.currentTimeMillis() < end) {
                    Thread.sleep(1000);
                    long left = (end - System.currentTimeMillis()) / 1000;
                    this.publish(left);
                }
                return 0L;
            }

            @Override
            protected void process(List<Long> chunks) {
                Long l = chunks.get(chunks.size() - 1);
                jlTimeout.setText(l + " seconds left");
                if (l < 850) {
                    jlTimeout.setForeground(Color.red);
                }
            }
        }.execute();

        JPanel jpResponse = new JPanel(new BorderLayout());
        JPanel jpProgress = new JPanel(new BorderLayout());
        jpResponse.add(jpProgress, BorderLayout.PAGE_START);

        JTextArea jtaJson = new JTextArea();
        jtaJson.setEditable(false);
        jtaJson.setTabSize(4);
        Font font = jtaJson.getFont();
        jtaJson.setFont(new Font("Courier New", font.getStyle(), font.getSize()));

        JTree jtView = new JTree();

        JTabbedPane jtp = new JTabbedPane();
        jtp.add("tree", new JScrollPane(jtView));
        jtp.add("json", new JScrollPane(jtaJson));

        jpResponse.add(jtp, BorderLayout.CENTER);

        JPanel jpScreen = new JPanel();
        jpScreen.setMinimumSize(new Dimension(200, 200));
        jpScreen.setLayout(new BoxLayout(jpScreen, BoxLayout.PAGE_AXIS));
        JScrollPane jsp1 = new JScrollPane(jpScreen);
        jpResponse.add(jsp1, BorderLayout.LINE_START);

        JPanel jpJs = new JPanel(new BorderLayout());
        JTextArea jtaJs = new JTextArea();
        jpJs.add(new JScrollPane(jtaJs), BorderLayout.CENTER);

        JSplitPane jSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, jpResponse, jpJs);
        jSplitPane.setResizeWeight(0.88);
        jpContent.add(jSplitPane, BorderLayout.CENTER);

        JPanel jpLog = new JPanel();
        jpLog.setBorder(BorderFactory.createEmptyBorder(5, 0, 0, 0));
        jpLog.setLayout(new BoxLayout(jpLog, BoxLayout.LINE_AXIS));

        JCheckBox jcbTap = new JCheckBox("Enable Click", null, false);
        jpLog.add(jcbTap);
        jpLog.add(Box.createHorizontalStrut(8));

        JButton jbLogUi = new JButton("Log Screen");
        jpResponse.add(jpLog, BorderLayout.PAGE_END);
        {
            jpLog.add(jbLogUi);
            jbLogUi.addActionListener((ActionEvent event) -> {
                jtaJson.setText("waiting for screenshot...");
                Thread t = new Thread(tName) {
                    @Override
                    public void run() {
                        LOG.debug("\n\n");
                        try {
                            WindowHierarchy wh = device.loadWindowHierarchy();
                            jtView.setModel(getModel(wh));

                            jtaJson.setText("");
                            jtaJson.append(wh.root.toJson().toString(2));
                            jtaJson.append("\n");

                            File png = device.takeDeviceScreenshot();
                            BufferedImage image = ImageIO.read(png);

                            int w = device.getDisplayWidth();
                            int h = device.getDisplayHeight();

                            BufferedImage resizedImg = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
                            Graphics2D g2 = resizedImg.createGraphics();
                            g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                                    RenderingHints.VALUE_INTERPOLATION_BILINEAR);
                            g2.drawImage(image, 0, 0, w, h, null);
                            g2.dispose();

                            JLabel jLabel = new JLabel(new ImageIcon(resizedImg));
                            jpScreen.removeAll();
                            jsp1.setPreferredSize(new Dimension(w + 30, h));
                            jpScreen.add(jLabel);

                            jLabel.addMouseListener(new MouseAdapter() {
                                @Override
                                public void mouseClicked(MouseEvent e) {
                                    LOG.debug("clicked at {},{}", e.getPoint().getX(), e.getPoint().getY());
                                    if (jcbTap.isSelected()) {
                                        device.click(e.getPoint().x, e.getPoint().y);
                                        device.waitForIdle();
                                        jbLogUi.doClick();
                                    }
                                }
                            });
                        } catch (Exception ex) {
                            LOG.error("Cannot log screen", ex);
                            jtaJson.append("Cannot log screen");
                        }
                        jtaJson.append("\n\n\n");
                        LOG.debug("\n\n");

                        jd.setSize(jd.getBounds().width + 1, jd.getBounds().height + 1);
                        jd.setSize(jd.getBounds().width - 1, jd.getBounds().height - 1);
                    }
                };
                t.start();
            });
        }
        jpLog.add(Box.createHorizontalStrut(38));
        {
            JButton jbLogMsg = new JButton("Log Message");
            jpLog.add(jbLogMsg);
            JTextField jtMsg = new JTextField(10);
            jpLog.add(jtMsg);
            jtMsg.addFocusListener(new FocusListener() {
                @Override
                public void focusLost(final FocusEvent pE) {
                }

                @Override
                public void focusGained(final FocusEvent pE) {
                    jtMsg.selectAll();
                }
            });
            jtMsg.addKeyListener(new KeyAdapter() {
                @Override
                public void keyPressed(java.awt.event.KeyEvent e) {
                    if (e.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER) {
                        jbLogMsg.doClick();
                    }
                }
            });
            jbLogMsg.addActionListener(event -> {
                Thread t = new Thread(tName) {
                    @Override
                    public void run() {
                        String msg = jtMsg.getText();
                        if (StringUtils.isNotBlank(msg)) {
                            LOG.info("{}", msg);
                            jtMsg.selectAll();
                        }
                    }
                };
                t.start();
                try {
                    t.join();
                } catch (InterruptedException ex) {
                    LOG.error("Cannot take screenshot", ex);
                }
                jtMsg.requestFocus();
            });
        }
        jpLog.add(Box.createHorizontalStrut(38));
        {
            JButton jbClear = new JButton("Clear");
            jpLog.add(jbClear);
            jbClear.addActionListener(event -> {
                jtaJson.setText("");
            });
        }

        JPanel jpAction = new JPanel();
        jpContent.add(jpAction, BorderLayout.PAGE_END);
        jpAction.setLayout(new BoxLayout(jpAction, BoxLayout.LINE_AXIS));
        jpJs.add(jpAction, BorderLayout.PAGE_END);

        jd.pack();
        jd.setVisible(true);
        jd.setLocationRelativeTo(null);

        jbLogUi.doClick();
    });

    while (visible.get()) {
        if (System.currentTimeMillis() > end) {
            LOG.error("Manual UI interaction timeout");
            break;
        }
        Thread.sleep(500);
    }

    if (pass.get()) {
        LOG.info("Manual UI Interaction returns PASS");
    } else {
        Assert.fail("Manual UI Interaction returns FAIL");
    }
}

From source file:com.frochr123.fabqr.gui.FabQRUploadDialog.java

private void btnPhotoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPhotoActionPerformed

    // Get latest full camera image (without resize)
    latestFullCameraImage = null;//from  w ww .j ava 2s . com

    if (cameraThread != null) {
        Image image = cameraThread.getLatestRawImage();

        // Convert image to bufferedimage
        if (image != null) {
            BufferedImage bufferedImage = new BufferedImage(image.getWidth(null), image.getHeight(null),
                    BufferedImage.TYPE_INT_ARGB);
            Graphics2D graphics = bufferedImage.createGraphics();
            graphics.drawImage(image, 0, 0, null);
            graphics.dispose();

            latestFullCameraImage = bufferedImage;
        }
    }

    // Stop camera, freeze image
    closeCamera();

    // Set correct UI button states
    btnPhoto.setEnabled(false);
    btnPhotoRedo.setEnabled(true);
    btnPublish.setEnabled(true);
}