Example usage for java.awt.image BufferedImage getGraphics

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

Introduction

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

Prototype

public java.awt.Graphics getGraphics() 

Source Link

Document

This method returns a Graphics2D , but is here for backwards compatibility.

Usage

From source file:edu.emory.library.tast.images.ThumbnailServlet.java

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    // location of images
    String baseUrl = AppConfig.getConfiguration().getString(AppConfig.IMAGES_URL);
    baseUrl = StringUtils.trimEnd(baseUrl, '/');

    // image name and size
    String imageFileName = request.getParameter("i");
    int thumbnailWidth = Integer.parseInt(request.getParameter("w"));
    int thumbnailHeight = Integer.parseInt(request.getParameter("h"));

    // image dir//from   w ww . j  a v a  2  s.c  o m
    String imagesDir = AppConfig.getConfiguration().getString(AppConfig.IMAGES_DIRECTORY);

    // create the thumbnail name
    String thumbnailFileName = FilenameUtils.getBaseName(imageFileName) + "-" + thumbnailWidth + "x"
            + thumbnailHeight + ".png";

    // does it exist?
    File thumbnailFile = new File(imagesDir, thumbnailFileName);
    if (thumbnailFile.exists()) {
        response.sendRedirect(baseUrl + "/" + thumbnailFileName);
        return;
    }

    // read the image
    File imageFile = new File(imagesDir, imageFileName);
    BufferedImage image = ImageIO.read(imageFile);
    int imageWidth = image.getWidth();
    int imageHeight = image.getHeight();
    BufferedImage imageCopy = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_RGB);
    imageCopy.getGraphics().drawImage(image, 0, 0, imageWidth, imageHeight, 0, 0, imageWidth, imageHeight,
            null);

    // height is calculated automatically
    if (thumbnailHeight == 0)
        thumbnailHeight = (int) ((double) thumbnailWidth / (double) imageWidth * (double) imageHeight);

    // width is calculated automatically
    if (thumbnailWidth == 0)
        thumbnailWidth = (int) ((double) thumbnailHeight / (double) imageHeight * (double) imageWidth);

    // create an empty thumbnail
    BufferedImage thumbnail = new BufferedImage(thumbnailWidth, thumbnailHeight, BufferedImage.TYPE_INT_RGB);
    Graphics2D gr = thumbnail.createGraphics();
    gr.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
    gr.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);

    // determine the piece of the image which we want to clip
    int clipX1, clipX2, clipY1, clipY2;
    if (imageWidth * thumbnailHeight > thumbnailWidth * imageHeight) {

        int clipWidth = (int) Math
                .round(((double) thumbnailWidth / (double) thumbnailHeight) * (double) imageHeight);
        int imgCenterX = imageWidth / 2;
        clipX1 = imgCenterX - clipWidth / 2;
        clipX2 = imgCenterX + clipWidth / 2;
        clipY1 = 0;
        clipY2 = imageHeight;
    } else {
        int clipHeight = (int) Math
                .round(((double) thumbnailHeight / (double) thumbnailWidth) * (double) imageWidth);
        int imgCenterY = imageHeight / 2;
        clipX1 = 0;
        clipX2 = imageWidth;
        clipY1 = imgCenterY - clipHeight / 2;
        clipY2 = imgCenterY + clipHeight / 2;
    }

    // we filter the image first to get better results when shrinking
    if (2 * thumbnailWidth < clipX2 - clipX1 || 2 * thumbnailHeight < clipY2 - clipY1) {

        int kernelDimX = (clipX2 - clipX1) / (thumbnailWidth);
        int kernelDimY = (clipY2 - clipY1) / (thumbnailHeight);

        if (kernelDimX % 2 == 0)
            kernelDimX++;
        if (kernelDimY % 2 == 0)
            kernelDimY++;

        if (kernelDimX < kernelDimY)
            kernelDimX = kernelDimY;
        if (kernelDimY < kernelDimX)
            kernelDimY = kernelDimX;

        float[] blurKernel = new float[kernelDimX * kernelDimY];
        for (int i = 0; i < kernelDimX; i++)
            for (int j = 0; j < kernelDimY; j++)
                blurKernel[i * kernelDimX + j] = 1.0f / (float) (kernelDimX * kernelDimY);

        BufferedImageOp op = new ConvolveOp(new Kernel(kernelDimX, kernelDimY, blurKernel));
        imageCopy = op.filter(imageCopy, null);

    }

    // draw the thumbnail
    gr.drawImage(imageCopy, 0, 0, thumbnailWidth, thumbnailHeight, clipX1, clipY1, clipX2, clipY2, null);

    // and we are done
    gr.dispose();
    ImageIO.write(thumbnail, "png", thumbnailFile);

    // redirect to it
    response.sendRedirect(baseUrl + "/" + thumbnailFileName);

}

From source file:ScaleTest_2008.java

/**
 * Progressive bilinear scaling: for any downscale size, scale
 * iteratively by halves using BILINEAR filtering until the proper 
 * size is reached./*from   w ww . ja  v a  2s.c  o m*/
 */
private BufferedImage getOptimalScalingImage(BufferedImage inputImage, int startSize, int endSize) {
    int currentSize = startSize;
    BufferedImage currentImage = inputImage;
    int delta = currentSize - endSize;
    int nextPow2 = currentSize >> 1;
    while (currentSize > 1) {
        if (delta <= nextPow2) {
            if (currentSize != endSize) {
                BufferedImage tmpImage = new BufferedImage(endSize, endSize, BufferedImage.TYPE_INT_RGB);
                Graphics g = tmpImage.getGraphics();
                ((Graphics2D) g).setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                        RenderingHints.VALUE_INTERPOLATION_BILINEAR);
                g.drawImage(currentImage, 0, 0, tmpImage.getWidth(), tmpImage.getHeight(), null);
                currentImage = tmpImage;
            }
            return currentImage;
        } else {
            BufferedImage tmpImage = new BufferedImage(currentSize >> 1, currentSize >> 1,
                    BufferedImage.TYPE_INT_RGB);
            Graphics g = tmpImage.getGraphics();
            ((Graphics2D) g).setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                    RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            g.drawImage(currentImage, 0, 0, tmpImage.getWidth(), tmpImage.getHeight(), null);
            currentImage = tmpImage;
            currentSize = currentImage.getWidth();
            delta = currentSize - endSize;
            nextPow2 = currentSize >> 1;
        }
    }
    return currentImage;
}

From source file:org.messic.server.facade.controllers.pages.CaptchaController.java

@ApiMethod(path = "/captcha", verb = ApiVerb.GET, description = "Get a captcha", produces = {
        MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE })
@ApiErrors(apierrors = { @ApiError(code = UnknownMessicRESTException.VALUE, description = "Unknown error") })
@RequestMapping(value = "", method = RequestMethod.GET)
@ResponseStatus(HttpStatus.OK)/* w w  w  .  j  a  v  a  2s. c om*/
@ResponseBody
@ApiResponseObject
public Captcha getCaptcha() throws UnknownMessicRESTException {

    try {
        UUID idOne = UUID.randomUUID();
        // create the image with the text
        BufferedImage bi = service.getImageChallengeForID(idOne.toString());
        BufferedImage bi2 = Util.ImagedeepCopy(bi);
        Graphics2D g2d = (Graphics2D) bi.getGraphics();
        float alpha = 0.25f;
        int type = AlphaComposite.SRC_OVER;
        AlphaComposite composite = AlphaComposite.getInstance(type, alpha);
        g2d.setComposite(composite);

        final int Min = 5;
        final int Max = 30;
        int random1 = Min + (int) (Math.random() * ((Max - Min) + 1));
        int random2 = Min + (int) (Math.random() * ((Max - Min) + 1));

        g2d.drawImage(bi2, random1, random2, null);

        alpha = 0.80f;
        type = AlphaComposite.SRC_OVER;
        composite = AlphaComposite.getInstance(type, alpha);
        g2d.setComposite(composite);

        int MinX = 0;
        int MaxX = bi.getWidth();
        int MinY = 0;
        int MaxY = bi.getHeight();
        g2d.setColor(Color.black);
        for (int i = 0; i < random2; i++) {
            int random3 = MinX + (int) (Math.random() * ((MaxX - MinX) + 1));
            int random4 = MinX + (int) (Math.random() * ((MaxX - MinX) + 1));
            int random5 = MinY + (int) (Math.random() * ((MaxY - MinY) + 1));
            int random6 = MinY + (int) (Math.random() * ((MaxY - MinY) + 1));
            g2d.drawLine(random3, random5, random4, random6);
        }

        Captcha result = new Captcha();
        result.id = idOne.toString();

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(bi, "jpg", baos);
        byte[] resultb64 = Base64.encode(baos.toByteArray());
        result.captchaImage = new String(resultb64);
        return result;
    } catch (Exception e) {
        throw new UnknownMessicRESTException(e);
    }
}

From source file:com.hmsinc.epicenter.spatial.render.SpatialScanRenderer.java

/**
 * @param context//from ww  w  . j av a2 s  .c o m
 * @return
 */
private BufferedImage renderImage(final MapContext context, int width, int height) {

    logger.trace("Image width: {}  height: {}", width, height);

    final BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);

    final Graphics2D graphics2D = (Graphics2D) image.getGraphics();

    final GTRenderer renderer = new StreamingRenderer();
    final RenderingHints h = new RenderingHints(RenderingHints.KEY_INTERPOLATION,
            RenderingHints.VALUE_INTERPOLATION_BICUBIC);
    h.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
    h.put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    h.put(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
    h.put(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE);
    renderer.setJava2DHints(h);
    renderer.setContext(context);
    renderer.paint(graphics2D, new Rectangle(width, height), context.getAreaOfInterest());

    return image;
}

From source file:nl.b3p.kaartenbalie.core.server.b3pLayering.ConfigLayer.java

protected void addTagsToImage(BufferedImage bufImage, Map parameterMap) {
    Graphics2D g2d = (Graphics2D) bufImage.getGraphics();
    Boolean showName = (Boolean) parameterMap.get("showname");
    if (showName != null && showName.booleanValue() == true) {
        drawTitledMessageBox(g2d, "KaartenBalie", "Message for Layer '" + super.getUniqueName() + "'", 20, 20,
                300, 30);//from   ww  w . ja  v  a2  s .  co m
    }
}

From source file:com.compomics.pepshell.view.statistics.CleavingProbabilityPane.java

@Override
public void setGraphData(PepshellProtein aPepshellProtein) {
    //obligatory checks
    if (aPepshellProtein != null && experiment.getProteins().contains(aPepshellProtein)) {
        if (aPepshellProtein != currentPepshellProtein) {
            //TODO: run this outside of the gui thread
            currentPepshellProtein = experiment.getProteins()
                    .get(experiment.getProteins().indexOf(aPepshellProtein));
            XYSeriesCollection xYSeriesCollection = new XYSeriesCollection();
            fillSeries(currentPepshellProtein).forEach(xYSeriesCollection::addSeries);
            JFreeChart CPDTchart = ChartFactory.createXYLineChart("probability of cleaving",
                    "aminoacids of " + currentPepshellProtein.getVisibleAccession(), "probability",
                    xYSeriesCollection, PlotOrientation.VERTICAL, false, true, false);
            prettifyChart(CPDTchart);//from   ww w.  j a  v a 2s . c  om
            CPDTchart.getXYPlot().getRangeAxis().setLowerBound(cutoff - 0.05);
            for (int i = 0; i < CPDTchart.getXYPlot().getSeriesCount(); i++) {
                CPDTchart.getXYPlot().getRenderer().setSeriesStroke(i, new BasicStroke(5));
            }
            if (!aPepshellProtein.getDomains().isEmpty()) {
                CPDTchart.setBackgroundImageAlpha(0.18f);
                CPDTchart.getXYPlot().getDomainAxis().setRange(0,
                        aPepshellProtein.getProteinSequence().length());
                BufferedImage anImage = new BufferedImage(this.getHeight(), this.getWidth(),
                        BufferedImage.TYPE_INT_ARGB);
                for (FeatureWithLocation aDomain : aPepshellProtein.getDomains()) {
                    anImage.getGraphics().drawRect(aDomain.getStartPosition(), 0, aDomain.getEndPosition(),
                            this.getHeight());
                }
                CPDTchart.setBackgroundImage(anImage);
            }
            chart.setChart(CPDTchart);
        }
    } else {
        chart.setChart(null);
        this.getGraphics().drawString("missing data", 0, 0);
    }
}

From source file:jtrace.Scene.java

/**
 * Add a set of axes to an image.  If the object parameter is not null,
 * the axes corresponding to the object's coordinate system are drawn.
 * //from w  w w.ja  va  2s  .  c om
 * @param image Image generated using scene's camera
 * @param object (Possibly null) object
 */
private void renderAxes(BufferedImage image, SceneObject object) {

    Graphics gr = image.getGraphics();
    int[] origin, xhat, yhat, zhat;

    if (object == null) {
        origin = camera.getPixel(image.getWidth(), image.getHeight(), Vector3D.ZERO);
        xhat = camera.getPixel(image.getWidth(), image.getHeight(), Vector3D.PLUS_I);
        yhat = camera.getPixel(image.getWidth(), image.getHeight(), Vector3D.PLUS_J);
        zhat = camera.getPixel(image.getWidth(), image.getHeight(), Vector3D.PLUS_K);
    } else {
        origin = camera.getPixel(image.getWidth(), image.getHeight(),
                object.objectToSceneVector(Vector3D.ZERO));
        xhat = camera.getPixel(image.getWidth(), image.getHeight(),
                object.objectToSceneVector(Vector3D.PLUS_I));
        yhat = camera.getPixel(image.getWidth(), image.getHeight(),
                object.objectToSceneVector(Vector3D.PLUS_J));
        zhat = camera.getPixel(image.getWidth(), image.getHeight(),
                object.objectToSceneVector(Vector3D.PLUS_K));
    }

    String objName;
    if (object == null)
        objName = "";
    else
        objName = "(" + object.getClass().getSimpleName() + ")";

    gr.setColor(Color.red);
    gr.drawLine(origin[0], origin[1], xhat[0], xhat[1]);
    gr.setColor(Color.white);
    gr.drawString("x " + objName, xhat[0], xhat[1]);

    gr.setColor(Color.green);
    gr.drawLine(origin[0], origin[1], yhat[0], yhat[1]);
    gr.setColor(Color.white);
    gr.drawString("y " + objName, yhat[0], yhat[1]);

    gr.setColor(Color.blue);
    gr.drawLine(origin[0], origin[1], zhat[0], zhat[1]);
    gr.setColor(Color.white);
    gr.drawString("z " + objName, zhat[0], zhat[1]);
}

From source file:com.opopov.cloud.image.service.ImageStitchingServiceImpl.java

private byte[] combineImagesIntoStitchedImage(@RequestBody ImageStitchingConfiguration config,
        IndexMap indexMap) throws IOException {
    int tileWidth = config.getSourceWidth();
    int tileHeight = config.getSourceHeight();

    //we are creating this big image in memory for the very short time frame, just when
    //all source data has been downloaded and decoded
    BufferedImage image = new BufferedImage(config.getRowCount() * tileWidth,
            config.getColumnCount() * tileHeight, BufferedImage.TYPE_4BYTE_ABGR);

    Graphics g = image.getGraphics();
    int indexOfTileInList = 0;
    for (int i = 0; i < config.getRowCount(); i++) {
        for (int j = 0; j < config.getColumnCount(); j++) {
            Optional<DecodedImage> decoded = indexMap.get(indexOfTileInList++);
            if (decoded != null) {
                if (decoded.isPresent()) {
                    g.drawImage(decoded.get().getImage(), i * config.getSourceWidth(),
                            j * config.getSourceHeight(), null);
                }/*from   w  w w  . jav a2  s. c  om*/
            }
        }
    }

    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    image.flush();
    ImageIO.write(image, config.getOutputFormat(), buffer);
    g.dispose();

    return buffer.toByteArray();
}

From source file:jtrace.Scene.java

/**
 * Render scene overlayed with wire frame representation of objects.
 * /*from  w  ww. j a v a2s .  c o m*/
 * @param width
 * @param height
 * @param maxRecursionDepth
 * @return 
 */
public BufferedImage renderWireFrame(int width, int height, int maxRecursionDepth) {
    BufferedImage image = render(width, height, maxRecursionDepth);
    Graphics gr = image.getGraphics();
    gr.setColor(java.awt.Color.cyan);

    // Object wireframes
    for (SceneObject object : sceneObjects) {
        for (Vector3D[] edge : object.getWireFrame()) {
            int[] coord1 = camera.getPixel(width, height, edge[0]);
            int[] coord2 = camera.getPixel(width, height, edge[1]);

            gr.drawLine(coord1[0], coord1[1], coord2[0], coord2[1]);
        }

        // Render object axes
        renderAxes(image, object);
    }

    // Render scene axes
    renderAxes(image, null);

    return image;
}

From source file:haven.Utils.java

public static BufferedImage outline2(BufferedImage img, Color col) {
    BufferedImage ol = outline(img, col);
    Graphics g = ol.getGraphics();
    g.drawImage(img, 1, 1, null);//  w  ww  .jav  a 2 s . co m
    g.dispose();
    return (ol);
}