Example usage for java.awt.image BufferedImage TYPE_INT_ARGB

List of usage examples for java.awt.image BufferedImage TYPE_INT_ARGB

Introduction

In this page you can find the example usage for java.awt.image BufferedImage TYPE_INT_ARGB.

Prototype

int TYPE_INT_ARGB

To view the source code for java.awt.image BufferedImage TYPE_INT_ARGB.

Click Source Link

Document

Represents an image with 8-bit RGBA color components packed into integer pixels.

Usage

From source file:web.diva.server.model.SomClustering.SomClustImgGenerator.java

public String generateScale(Dataset dataset, boolean clustColumn) {
    int W = 0;/*from   w  w  w .ja  v  a2 s  . com*/
    if (clustColumn) {
        W = (Math.min((upperTree.getWidth() + 21), 250));
    } else {
        W = (Math.min((dataset.getColumnIds().length * 12 + 21), 250));
    }
    BufferedImage nfo = new BufferedImage(W, 50, BufferedImage.TYPE_INT_ARGB);
    Graphics g = nfo.getGraphics();
    g.setFont(getTableFont(9));
    drawScale(g, new Point(0, 0), W, 30);
    return this.generateEncodedImg(nfo);

}

From source file:au.org.ala.biocache.web.MapController.java

@Deprecated
@RequestMapping(value = "/occurrences/wms", method = RequestMethod.GET)
public void pointsWmsImage(SpatialSearchRequestParams requestParams,
        @RequestParam(value = "colourby", required = false, defaultValue = "0") Integer colourby,
        @RequestParam(value = "width", required = false, defaultValue = "256") Integer widthObj,
        @RequestParam(value = "height", required = false, defaultValue = "256") Integer heightObj,
        @RequestParam(value = "zoom", required = false, defaultValue = "0") Integer zoomLevel,
        @RequestParam(value = "symsize", required = false, defaultValue = "4") Integer symsize,
        @RequestParam(value = "symbol", required = false, defaultValue = "circle") String symbol,
        @RequestParam(value = "bbox", required = false, defaultValue = "110,-45,157,-9") String bboxString,
        @RequestParam(value = "type", required = false, defaultValue = "normal") String type,
        @RequestParam(value = "outline", required = true, defaultValue = "false") boolean outlinePoints,
        @RequestParam(value = "outlineColour", required = true, defaultValue = "0x000000") String outlineColour,
        HttpServletResponse response) throws Exception {

    // size of the circles
    int size = symsize.intValue();
    int width = widthObj.intValue();
    int height = heightObj.intValue();

    requestParams.setStart(0);/*from   w w w  .j  av  a 2s  .  c  om*/
    requestParams.setPageSize(Integer.MAX_VALUE);
    String query = requestParams.getQ();
    String[] filterQuery = requestParams.getFq();

    if (StringUtils.isBlank(query) && StringUtils.isBlank(requestParams.getFormattedQuery())) {
        displayBlankImage(width, height, false, response);
        return;
    }

    // let's force it to PNG's for now 
    response.setContentType("image/png");

    // Convert array to list so we append more values onto it
    ArrayList<String> fqList = null;
    if (filterQuery != null) {
        fqList = new ArrayList<String>(Arrays.asList(filterQuery));
    } else {
        fqList = new ArrayList<String>();
    }

    // the bounding box
    double[] bbox = new double[4];
    int i;
    i = 0;
    for (String s : bboxString.split(",")) {
        try {
            bbox[i] = Double.parseDouble(s);
            i++;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }

    double pixelWidth = (bbox[2] - bbox[0]) / width;
    double pixelHeight = (bbox[3] - bbox[1]) / height;
    bbox[0] += pixelWidth / 2;
    bbox[2] -= pixelWidth / 2;
    bbox[1] += pixelHeight / 2;
    bbox[3] -= pixelHeight / 2;

    //offset for points bounding box by size
    double xoffset = (bbox[2] - bbox[0]) / (double) width * (size * 2);
    double yoffset = (bbox[3] - bbox[1]) / (double) height * (size * 2);

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

    double[] bbox2 = new double[4];
    bbox2[0] = convertMetersToLng(bbox[0] - xoffset);
    bbox2[1] = convertMetersToLat(bbox[1] - yoffset);
    bbox2[2] = convertMetersToLng(bbox[2] + xoffset);
    bbox2[3] = convertMetersToLat(bbox[3] + yoffset);

    bbox[0] = convertMetersToLng(bbox[0]);
    bbox[1] = convertMetersToLat(bbox[1]);
    bbox[2] = convertMetersToLng(bbox[2]);
    bbox[3] = convertMetersToLat(bbox[3]);

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

    String bboxString2 = bbox2[0] + "," + bbox2[1] + "," + bbox2[2] + "," + bbox2[3];
    bboxToQuery(bboxString2, fqList);

    PointType pointType = getPointTypeForZoomLevel(zoomLevel);

    String[] newFilterQuery = (String[]) fqList.toArray(new String[fqList.size()]); // convert back to array

    requestParams.setFq(newFilterQuery);

    List<OccurrencePoint> points = searchDAO.getFacetPoints(requestParams, pointType);
    logger.debug("Points search for " + pointType.getLabel() + " - found: " + points.size());

    if (points.size() == 0) {
        displayBlankImage(width, height, false, response);
        return;
    }

    BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g = (Graphics2D) img.getGraphics();
    g.setColor(Color.RED);

    int x, y;
    int pointWidth = size * 2;
    double width_mult = (width / (pbbox[2] - pbbox[0]));
    double height_mult = (height / (pbbox[1] - pbbox[3]));

    g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    Color oColour = Color.decode(outlineColour);

    for (i = 0; i < points.size(); i++) {
        OccurrencePoint pt = points.get(i);
        float lng = pt.getCoordinates().get(0).floatValue();
        float lat = pt.getCoordinates().get(1).floatValue();

        x = (int) ((convertLngToPixel(lng) - pbbox[0]) * width_mult);
        y = (int) ((convertLatToPixel(lat) - pbbox[3]) * height_mult);

        if (colourby != null) {
            int colour = 0xFF000000 | colourby.intValue();
            Color c = new Color(colour);
            g.setPaint(c);
        } else {
            g.setPaint(Color.blue);
        }

        // g.fillOval(x - (size / 2), y - (size / 2), pointWidth, pointWidth);
        Shape shp = getShape(symbol, x - (size / 2), y - (size / 2), pointWidth, pointWidth);
        g.draw(shp);
        g.fill(shp);
        if (outlinePoints) {
            g.setPaint(oColour);
            g.drawOval(x - (size / 2), y - (size / 2), pointWidth, pointWidth);
        }
    }

    g.dispose();

    try {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(img, "png", outputStream);
        ServletOutputStream outStream = response.getOutputStream();
        outStream.write(outputStream.toByteArray());
        outStream.flush();
        outStream.close();

    } catch (Exception e) {
        logger.error("Unable to write image", e);
    }
}

From source file:net.sf.mcf2pdf.mcfelements.util.ImageUtil.java

/**
 * Rotates the given buffered image by the given angle, and returns a newly
 * created image, containing the rotated image.
 *
 * @param img Image to rotate./* w w  w .ja  v  a  2s.com*/
 * @param angle Angle, in radians, by which to rotate the image.
 * @param drawOffset Receives the offset which is required to draw the image,
 * relative to the original (0,0) corner, so that the center of the image is
 * still on the same position.
 *
 * @return A newly created image containing the rotated image.
 */
public static BufferedImage rotateImage(BufferedImage img, float angle, Point drawOffset) {
    int w = img.getWidth();
    int h = img.getHeight();

    AffineTransform tf = AffineTransform.getRotateInstance(angle, w / 2.0, h / 2.0);

    // get coordinates for all corners to determine real image size
    Point2D[] ptSrc = new Point2D[4];
    ptSrc[0] = new Point(0, 0);
    ptSrc[1] = new Point(w, 0);
    ptSrc[2] = new Point(w, h);
    ptSrc[3] = new Point(0, h);

    Point2D[] ptTgt = new Point2D[4];
    tf.transform(ptSrc, 0, ptTgt, 0, ptSrc.length);

    Rectangle rc = new Rectangle(0, 0, w, h);

    for (Point2D p : ptTgt) {
        if (p.getX() < rc.x) {
            rc.width += rc.x - p.getX();
            rc.x = (int) p.getX();
        }
        if (p.getY() < rc.y) {
            rc.height += rc.y - p.getY();
            rc.y = (int) p.getY();
        }
        if (p.getX() > rc.x + rc.width)
            rc.width = (int) (p.getX() - rc.x);
        if (p.getY() > rc.y + rc.height)
            rc.height = (int) (p.getY() - rc.y);
    }

    BufferedImage imgTgt = new BufferedImage(rc.width, rc.height, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2d = imgTgt.createGraphics();

    // create a NEW rotation transformation around new center
    tf = AffineTransform.getRotateInstance(angle, rc.getWidth() / 2, rc.getHeight() / 2);
    g2d.setTransform(tf);
    g2d.drawImage(img, -rc.x, -rc.y, null);
    g2d.dispose();

    drawOffset.x += rc.x;
    drawOffset.y += rc.y;

    return imgTgt;
}

From source file:com.github.lindenb.jvarkit.util.command.Command.java

protected Image getImageIcon() {
    BufferedImage img = new BufferedImage(ICON_SIZE, ICON_SIZE, BufferedImage.TYPE_INT_ARGB);

    return img;
}

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

public void start() {
    // Create stream speech recognizer.
    StreamSpeechRecognizer recognizer = null;
    try {/*from  w ww .j av a2s .  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:base.BasePlayer.BedCanvas.java

BedCanvas(int width, int height) {

    this.width = width;
    this.height = height;
    bufImage = MethodLibrary.toCompatibleImage(new BufferedImage((int) Main.screenSize.getWidth(),
            (int) Main.screenSize.getHeight(), BufferedImage.TYPE_INT_ARGB));
    buf = (Graphics2D) bufImage.getGraphics();
    //   buf.setRenderingHints(Draw.rh);
    nodeImage = MethodLibrary.toCompatibleImage(new BufferedImage((int) Main.screenSize.getWidth(),
            (int) Main.screenSize.getHeight(), BufferedImage.TYPE_INT_ARGB));
    nodebuf = (Graphics2D) nodeImage.getGraphics();
    //   nodebuf.setRenderingHints(Draw.rh);
    backupComposite = nodebuf.getComposite();
    buf.setFont(Draw.defaultFont);//from   ww w  .  j  a va 2s . co  m
    //nodebuf.setFont(Draw.defaultFont);
    addMouseListener(this);
    addKeyListener(this);
    addMouseMotionListener(this);
    addMouseWheelListener(new MouseWheelListener() {
        public void mouseWheelMoved(MouseWheelEvent mwe) {
            bedTrack.get(hoverIndex).mouseWheel -= mwe.getWheelRotation();
            if (bedTrack.get(hoverIndex).mouseWheel > 0) {
                bedTrack.get(hoverIndex).mouseWheel = 0;
            }
            repaint();
        }
    });
}

From source file:de.mprengemann.intellij.plugin.androidicons.images.ImageUtils.java

private static BufferedImage generateBordersImage(BufferedImage source, int trimmedWidth, int trimmedHeight)
        throws Wrong9PatchException, IOException {
    BufferedImage finalBorder = UIUtil.createImage(trimmedWidth + 2, trimmedHeight + 2,
            BufferedImage.TYPE_INT_ARGB);
    int cutW = source.getWidth() - 2;
    int cutH = source.getHeight() - 2;

    // left border
    BufferedImage leftBorder = UIUtil.createImage(1, cutH, BufferedImage.TYPE_INT_ARGB);
    leftBorder.setRGB(0, 0, 1, cutH, source.getRGB(0, 1, 1, cutH, null, 0, 1), 0, 1);
    verifyBorderImage(leftBorder);//  ww  w.jav a  2  s .c o  m
    leftBorder = resizeBorder(leftBorder, 1, trimmedHeight);
    finalBorder.setRGB(0, 1, 1, trimmedHeight, leftBorder.getRGB(0, 0, 1, trimmedHeight, null, 0, 1), 0, 1);

    // right border
    BufferedImage rightBorder = UIUtil.createImage(1, cutH, BufferedImage.TYPE_INT_ARGB);
    rightBorder.setRGB(0, 0, 1, cutH, source.getRGB(cutW + 1, 1, 1, cutH, null, 0, 1), 0, 1);
    verifyBorderImage(rightBorder);
    rightBorder = resizeBorder(rightBorder, 1, trimmedHeight);
    finalBorder.setRGB(trimmedWidth + 1, 1, 1, trimmedHeight,
            rightBorder.getRGB(0, 0, 1, trimmedHeight, null, 0, 1), 0, 1);

    // top border
    BufferedImage topBorder = UIUtil.createImage(cutW, 1, BufferedImage.TYPE_INT_ARGB);
    topBorder.setRGB(0, 0, cutW, 1, source.getRGB(1, 0, cutW, 1, null, 0, cutW), 0, cutW);
    verifyBorderImage(topBorder);
    topBorder = resizeBorder(topBorder, trimmedWidth, 1);
    finalBorder.setRGB(1, 0, trimmedWidth, 1, topBorder.getRGB(0, 0, trimmedWidth, 1, null, 0, trimmedWidth), 0,
            trimmedWidth);

    // bottom border
    BufferedImage bottomBorder = UIUtil.createImage(cutW, 1, BufferedImage.TYPE_INT_ARGB);
    bottomBorder.setRGB(0, 0, cutW, 1, source.getRGB(1, cutH + 1, cutW, 1, null, 0, cutW), 0, cutW);
    verifyBorderImage(bottomBorder);
    bottomBorder = resizeBorder(bottomBorder, trimmedWidth, 1);
    finalBorder.setRGB(1, trimmedHeight + 1, trimmedWidth, 1,
            bottomBorder.getRGB(0, 0, trimmedWidth, 1, null, 0, trimmedWidth), 0, trimmedWidth);

    return finalBorder;
}

From source file:net.sf.mzmine.chartbasics.graphicsexport.ChartExportUtil.java

public static void writeChartToPNG(JFreeChart chart, ChartRenderingInfo info, int width, int height,
        File fileName, int resolution) throws IOException {
    if (resolution == 72)
        writeChartToPNG(chart, info, width, height, fileName);
    else {//from www . j a va2 s . com
        OutputStream out = new BufferedOutputStream(new FileOutputStream(fileName));
        try {
            BufferedImage image = paintScaledChartToBufferedImage(chart, info, out, width, height, resolution,
                    BufferedImage.TYPE_INT_ARGB);
            out.write(ChartUtils.encodeAsPNG(image));
        } finally {
            out.close();
        }
    }
}

From source file:com.sun.socialsite.util.ImageUtil.java

/**
 * Convenience method that returns a scaled instance of the
 * provided {@code BufferedImage}./*from w w  w .  ja v a 2  s .  co m*/
 *
 * NOTE: Adapted from code at
 * {@link http://today.java.net/pub/a/today/2007/04/03/perils-of-image-getscaledinstance.html}.
 *
 * @param img the original image to be scaled
 * @param targetWidth the desired width of the scaled instance,
 *    in pixels
 * @param targetHeight the desired height of the scaled instance,
 *    in pixels
 * @param hint one of the rendering hints that corresponds to
 *    {@code RenderingHints.KEY_INTERPOLATION} (e.g.
 *    {@code RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR},
 *    {@code RenderingHints.VALUE_INTERPOLATION_BILINEAR},
 *    {@code RenderingHints.VALUE_INTERPOLATION_BICUBIC})
 * @param higherQuality if true, this method will use a multi-step
 *    scaling technique that provides higher quality than the usual
 *    one-step technique (only useful in downscaling cases, where
 *    {@code targetWidth} or {@code targetHeight} is
 *    smaller than the original dimensions, and generally only when
 *    the {@code BILINEAR} hint is specified)
 * @return a scaled version of the original {@code BufferedImage}
 */
private static BufferedImage getScaledInstance(BufferedImage img, int targetWidth, int targetHeight,
        Object hint, boolean higherQuality) {
    int type = BufferedImage.TYPE_INT_ARGB;
    BufferedImage ret = (BufferedImage) img;
    int w, h;
    if (higherQuality) {
        // Use multi-step technique: start with original size, then
        // scale down in multiple passes with drawImage()
        // until the target size is reached
        w = img.getWidth();
        h = img.getHeight();
    } else {
        // Use one-step technique: scale directly from original
        // size to target size with a single drawImage() call
        w = targetWidth;
        h = targetHeight;
    }

    do {
        if (higherQuality && w > targetWidth) {
            w /= 2;
            if (w < targetWidth) {
                w = targetWidth;
            }
        }

        if (higherQuality && h > targetHeight) {
            h /= 2;
            if (h < targetHeight) {
                h = targetHeight;
            }
        }

        BufferedImage tmp = new BufferedImage(w, h, type);
        Graphics2D g2 = tmp.createGraphics();
        g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, hint);
        g2.drawImage(ret, 0, 0, w, h, null);
        g2.dispose();

        ret = tmp;
    } while (w > targetWidth || h > targetHeight);

    return ret;
}

From source file:org.fao.geonet.services.region.GetMap.java

public Element exec(Element params, ServiceContext context) throws Exception {
    Util.toLowerCase(params);// ww w  .  j a  v a  2s . co m
    String id = params.getChildText(Params.ID);
    String srs = Util.getParam(params, MAP_SRS_PARAM, "EPSG:4326");
    String widthString = Util.getParamText(params, WIDTH_PARAM);
    String heightString = Util.getParamText(params, HEIGHT_PARAM);
    String background = Util.getParamText(params, BACKGROUND_PARAM);
    String geomParam = Util.getParamText(params, GEOM_PARAM);
    String geomType = Util.getParam(params, GEOM_TYPE_PARAM, GeomFormat.WKT.toString());
    String geomSrs = Util.getParam(params, GEOM_SRS_PARAM, "EPSG:4326");

    if (id == null && geomParam == null) {
        throw new BadParameterEx(Params.ID, "Either " + GEOM_PARAM + " or " + Params.ID + " is required");
    }
    if (id != null && geomParam != null) {
        throw new BadParameterEx(Params.ID, "Only one of " + GEOM_PARAM + " or " + Params.ID + " is permitted");
    }

    // see calculateImageSize for more parameter checks

    Geometry geom = null;
    if (id != null) {
        Collection<RegionsDAO> daos = context.getApplicationContext().getBeansOfType(RegionsDAO.class).values();
        for (RegionsDAO regionsDAO : daos) {
            geom = regionsDAO.getGeom(context, id, false, srs);
            if (geom != null) {
                break;
            }
        }
        if (geom == null) {
            throw new RegionNotFoundEx(id);
        }
    } else {
        GeomFormat format = GeomFormat.find(geomType);
        geom = format.parse(geomParam);
        if (!geomSrs.equals(srs)) {
            CoordinateReferenceSystem mapCRS = Region.decodeCRS(srs);
            CoordinateReferenceSystem geomCRS = Region.decodeCRS(geomSrs);
            MathTransform transform = CRS.findMathTransform(geomCRS, mapCRS, true);
            geom = JTS.transform(geom, transform);
        }
    }
    BufferedImage image;
    Envelope bboxOfImage = new Envelope(geom.getEnvelopeInternal());
    double expandFactor = 0.2;
    bboxOfImage.expandBy(bboxOfImage.getWidth() * expandFactor, bboxOfImage.getHeight() * expandFactor);
    Dimension imageDimenions = calculateImageSize(bboxOfImage, widthString, heightString);

    Exception error = null;
    if (background != null) {

        if (this.namedBackgrounds.containsKey(background)) {
            background = this.namedBackgrounds.get(background);
        }

        String minx = Double.toString(bboxOfImage.getMinX());
        String maxx = Double.toString(bboxOfImage.getMaxX());
        String miny = Double.toString(bboxOfImage.getMinY());
        String maxy = Double.toString(bboxOfImage.getMaxY());
        background = background.replace("{minx}", minx).replace("{maxx}", maxx).replace("{miny}", miny)
                .replace("{maxy}", maxy).replace("{srs}", srs)
                .replace("{width}", Integer.toString(imageDimenions.width))
                .replace("{height}", Integer.toString(imageDimenions.height)).replace("{MINX}", minx)
                .replace("{MAXX}", maxx).replace("{MINY}", miny).replace("{MAXY}", maxy).replace("{SRS}", srs)
                .replace("{WIDTH}", Integer.toString(imageDimenions.width))
                .replace("{HEIGHT}", Integer.toString(imageDimenions.height));

        InputStream in = null;
        try {
            URL imageUrl = new URL(background);
            in = imageUrl.openStream();
            image = ImageIO.read(in);
        } catch (IOException e) {
            image = new BufferedImage(imageDimenions.width, imageDimenions.height, BufferedImage.TYPE_INT_ARGB);
            error = e;
        } finally {
            if (in != null) {
                IOUtils.closeQuietly(in);
            }

        }
    } else {
        image = new BufferedImage(imageDimenions.width, imageDimenions.height, BufferedImage.TYPE_INT_ARGB);
    }

    Graphics2D graphics = image.createGraphics();
    try {
        if (error != null) {
            graphics.drawString(error.getMessage(), 0, imageDimenions.height / 2);
        }
        ShapeWriter shapeWriter = new ShapeWriter();
        AffineTransform worldToScreenTransform = worldToScreenTransform(bboxOfImage, imageDimenions);
        //            MathTransform mathTransform = new AffineTransform2D(worldToScreenTransform);
        //            Geometry screenGeom = JTS.transform(geom, mathTransform);
        Shape shape = worldToScreenTransform.createTransformedShape(shapeWriter.toShape(geom));
        graphics.setColor(Color.yellow);
        graphics.draw(shape);

        graphics.setColor(new Color(255, 255, 0, 100));
        graphics.fill(shape);

    } finally {
        graphics.dispose();
    }

    File tmpFile = File.createTempFile("GetMap", "." + format);
    ImageIO.write(image, format, tmpFile);
    return BinaryFile.encode(200, tmpFile.getAbsolutePath(), true);
}