Example usage for java.awt.image BufferedImage BufferedImage

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

Introduction

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

Prototype

public BufferedImage(int width, int height, int imageType) 

Source Link

Document

Constructs a BufferedImage of one of the predefined image types.

Usage

From source file:com.pureinfo.srm.common.ImageHelper.java

public static void drawRectangle(Paint _color, Point _point, OutputStream _os) throws PureException {
    int nWidth = _point.x;
    int nHeight = _point.y;

    BufferedImage image = new BufferedImage(nWidth, nHeight, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2 = image.createGraphics();
    g2.setPaint(_color);//from   w  w  w .  j  a  va  2s  . c  o m
    g2.fillRect(0, 0, nWidth, nHeight);

    g2.dispose();
    try {
        EncoderUtil.writeBufferedImage(image, ImageFormat.PNG, _os);
    } catch (Exception ex) {
        throw new PureException(PureException.UNKNOWN, "", ex);
    }
}

From source file:de.tor.tribes.ui.algo.TimeFrameVisualizer.java

/** Creates new form TimeFrameVisualizer */
public TimeFrameVisualizer() {
    initComponents();/*from w  w w . j  a  v  a2  s  .  co m*/
    try {
        STROKED = new BufferedImage(3, 3, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = STROKED.createGraphics();
        g2d.setColor(Constants.DS_BACK_LIGHT);
        g2d.fillRect(0, 0, 3, 3);
        g2d.setColor(Constants.DS_BACK);
        g2d.drawLine(0, 2, 2, 0);
        g2d.dispose();
        DAILY_START_FRAME_FILL = new BufferedImage(3, 3, BufferedImage.TYPE_INT_RGB);
        g2d = DAILY_START_FRAME_FILL.createGraphics();
        g2d.setColor(Color.CYAN);
        g2d.fillRect(0, 0, 3, 3);
        g2d.setColor(Color.BLUE);
        g2d.drawLine(0, 2, 2, 0);
        g2d.dispose();
        EXACT_START_FRAME_FILL = new BufferedImage(3, 3, BufferedImage.TYPE_INT_RGB);
        g2d = EXACT_START_FRAME_FILL.createGraphics();
        g2d.setColor(Color.CYAN);
        g2d.fillRect(0, 0, 3, 3);
        g2d.dispose();
        ONE_DAY_START_FRAME_FILL = new BufferedImage(3, 3, BufferedImage.TYPE_INT_RGB);
        g2d = ONE_DAY_START_FRAME_FILL.createGraphics();
        g2d.setColor(Color.CYAN);
        g2d.fillRect(0, 0, 3, 3);
        g2d.setColor(Color.BLUE);
        g2d.drawLine(1, 0, 1, 2);
        g2d.dispose();
        ARRIVE_FRAME_FILL = new BufferedImage(3, 3, BufferedImage.TYPE_INT_RGB);
        g2d = ARRIVE_FRAME_FILL.createGraphics();
        g2d.setColor(Color.RED);
        g2d.fillRect(0, 0, 3, 3);
        g2d.setColor(Color.BLACK);
        g2d.drawLine(0, 2, 2, 0);
        g2d.dispose();
    } catch (Exception e) {
    }

    popupInfo = new HashMap<String, Object>();
    addMouseMotionListener(new MouseMotionListener() {

        @Override
        public void mouseDragged(MouseEvent e) {
        }

        @Override
        public void mouseMoved(MouseEvent e) {
            repaint();
        }
    });

    addMouseListener(new MouseListener() {

        @Override
        public void mouseClicked(MouseEvent e) {
            fireClickEvent(e);
        }

        @Override
        public void mousePressed(MouseEvent e) {
        }

        @Override
        public void mouseReleased(MouseEvent e) {
        }

        @Override
        public void mouseEntered(MouseEvent e) {
        }

        @Override
        public void mouseExited(MouseEvent e) {
        }
    });
}

From source file:Thumbnail.java

/**
* Reads an image in a file and creates a thumbnail in another file.
* largestDimension is the largest dimension of the thumbnail, the other dimension is scaled accordingly.
* Utilises weighted stepping method to gradually reduce the image size for better results,
* i.e. larger steps to start with then smaller steps to finish with.
* Note: always writes a JPEG because GIF is protected or something - so always make your outFilename end in 'jpg'.
* PNG's with transparency are given white backgrounds
*///from w w w .  j av  a  2  s .  co m
public String createThumbnail(String inFilename, String outFilename, int largestDimension) {
    try {
        double scale;
        int sizeDifference, originalImageLargestDim;
        if (!inFilename.endsWith(".jpg") && !inFilename.endsWith(".jpeg") && !inFilename.endsWith(".gif")
                && !inFilename.endsWith(".png")) {
            return "Error: Unsupported image type, please only either JPG, GIF or PNG";
        } else {
            Image inImage = Toolkit.getDefaultToolkit().getImage(inFilename);
            if (inImage.getWidth(null) == -1 || inImage.getHeight(null) == -1) {
                return "Error loading file: \"" + inFilename + "\"";
            } else {
                //find biggest dimension       
                if (inImage.getWidth(null) > inImage.getHeight(null)) {
                    scale = (double) largestDimension / (double) inImage.getWidth(null);
                    sizeDifference = inImage.getWidth(null) - largestDimension;
                    originalImageLargestDim = inImage.getWidth(null);
                } else {
                    scale = (double) largestDimension / (double) inImage.getHeight(null);
                    sizeDifference = inImage.getHeight(null) - largestDimension;
                    originalImageLargestDim = inImage.getHeight(null);
                }
                //create an image buffer to draw to
                BufferedImage outImage = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB); //arbitrary init so code compiles
                Graphics2D g2d;
                AffineTransform tx;
                if (scale < 1.0d) //only scale if desired size is smaller than original
                {
                    int numSteps = sizeDifference / 100;
                    int stepSize = sizeDifference / numSteps;
                    int stepWeight = stepSize / 2;
                    int heavierStepSize = stepSize + stepWeight;
                    int lighterStepSize = stepSize - stepWeight;
                    int currentStepSize, centerStep;
                    double scaledW = inImage.getWidth(null);
                    double scaledH = inImage.getHeight(null);
                    if (numSteps % 2 == 1) //if there's an odd number of steps
                        centerStep = (int) Math.ceil((double) numSteps / 2d); //find the center step
                    else
                        centerStep = -1; //set it to -1 so it's ignored later
                    Integer intermediateSize = originalImageLargestDim,
                            previousIntermediateSize = originalImageLargestDim;
                    Integer calculatedDim;
                    for (Integer i = 0; i < numSteps; i++) {
                        if (i + 1 != centerStep) //if this isn't the center step
                        {
                            if (i == numSteps - 1) //if this is the last step
                            {
                                //fix the stepsize to account for decimal place errors previously
                                currentStepSize = previousIntermediateSize - largestDimension;
                            } else {
                                if (numSteps - i > numSteps / 2) //if we're in the first half of the reductions
                                    currentStepSize = heavierStepSize;
                                else
                                    currentStepSize = lighterStepSize;
                            }
                        } else //center step, use natural step size
                        {
                            currentStepSize = stepSize;
                        }
                        intermediateSize = previousIntermediateSize - currentStepSize;
                        scale = (double) intermediateSize / (double) previousIntermediateSize;
                        scaledW = (int) scaledW * scale;
                        scaledH = (int) scaledH * scale;
                        outImage = new BufferedImage((int) scaledW, (int) scaledH, BufferedImage.TYPE_INT_RGB);
                        g2d = outImage.createGraphics();
                        g2d.setBackground(Color.WHITE);
                        g2d.clearRect(0, 0, outImage.getWidth(), outImage.getHeight());
                        g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
                        tx = new AffineTransform();
                        tx.scale(scale, scale);
                        g2d.drawImage(inImage, tx, null);
                        g2d.dispose();
                        inImage = new ImageIcon(outImage).getImage();
                        previousIntermediateSize = intermediateSize;
                    }
                } else {
                    //just copy the original
                    outImage = new BufferedImage(inImage.getWidth(null), inImage.getHeight(null),
                            BufferedImage.TYPE_INT_RGB);
                    g2d = outImage.createGraphics();
                    g2d.setBackground(Color.WHITE);
                    g2d.clearRect(0, 0, outImage.getWidth(), outImage.getHeight());
                    tx = new AffineTransform();
                    tx.setToIdentity(); //use identity matrix so image is copied exactly
                    g2d.drawImage(inImage, tx, null);
                    g2d.dispose();
                }
                //JPEG-encode the image and write to file.
                OutputStream os = new FileOutputStream(outFilename);
                JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(os);
                encoder.encode(outImage);
                os.close();
            }
        }
    } catch (Exception ex) {
        String errorMsg = "";
        errorMsg += "<br>Exception: " + ex.toString();
        errorMsg += "<br>Cause = " + ex.getCause();
        errorMsg += "<br>Stack Trace = ";
        StackTraceElement stackTrace[] = ex.getStackTrace();
        for (int traceLine = 0; traceLine < stackTrace.length; traceLine++) {
            errorMsg += "<br>" + stackTrace[traceLine];
        }
        return errorMsg;
    }
    return ""; //success
}

From source file:de.jwic.ecolib.controls.chart.ChartControl.java

public void renderImage() throws IOException {
    // create image to draw into
    BufferedImage bi = new BufferedImage(width < 10 ? 10 : width, height < 10 ? 10 : height,
            BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2d = bi.createGraphics();

    if (chart != null) {
        chart.setBackgroundPaint(Color.WHITE);
        chart.draw(g2d, new Rectangle2D.Double(0, 0, width < 10 ? 10 : width, height < 10 ? 10 : height));
    } else {/*  w w  w  . ja va2s. com*/
        g2d.setColor(Color.BLACK);
        g2d.drawString("No chart has been assigned.", 1, 20);
    }
    // finish drawing
    g2d.dispose();

    // write image data into output stream
    ByteArrayOutputStream out = getImageOutputStream();
    out.reset();
    // create a PNG image
    ImageWriter imageWriter = new PNGImageWriter(null);
    ImageWriteParam param = imageWriter.getDefaultWriteParam();
    imageWriter.setOutput(new MemoryCacheImageOutputStream(out));
    imageWriter.write(null, new IIOImage(bi, null, null), param);
    imageWriter.dispose();

    setMimeType(MIME_TYPE_PNG);
}

From source file:com.lcw.one.common.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");

    /*// w  ww .  j  a  v a2s . c o m
     * ??
     */
    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();

}

From source file:com.github.orangefoundry.gorender.controllers.ImageRenderController.java

private byte[] renderPlaceHolder(String size, String colour) throws IOException {

    if (size == null || size.isEmpty()) {
        size = Default.SIZE.getValue();//from  ww  w  .j  a  v a 2 s .c  om
    }

    if (colour == null || colour.isEmpty()) {
        colour = Default.COLOUR.getValue();
    }

    String[] sizes = new String[2];

    if (size != null && !size.isEmpty()) {
        sizes = size.toLowerCase().split("x");
    }

    int width = Integer.parseInt(sizes[0]), height = Integer.parseInt(sizes[1]);

    final ColourToAWTColour colourToAWTColour = new ColourToAWTColour();
    Color myColour = colourToAWTColour.getColour(colour);
    int rgb = myColour.getRGB();

    BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    int[] data = new int[width * height];
    int i = 0;
    for (int y = 0; y < height; y++) {
        for (int x = 0; x < width; x++) {
            data[i++] = rgb;
        }
    }
    bi.setRGB(0, 0, width, height, data, 0, width);

    ByteArrayOutputStream bao = new ByteArrayOutputStream();

    ImageIO.write(bi, "png", bao);

    return bao.toByteArray();
}

From source file:cytoscape.render.immed.GraphGraphicsTest.java

public void setUp() {
    image = new BufferedImage(canvasSize, canvasSize, BufferedImage.TYPE_INT_ARGB);
    currentGraphGraphics = new GraphGraphics(image, false);
    currentGraphGraphics.clear(Color.white, 0, 0, 1.0);
    oldGraphGraphics = new OldGraphGraphics(image, false);
    oldGraphGraphics.clear(Color.white, 0, 0, 1.0);
}

From source file:net.rptools.lib.image.ThumbnailManager.java

private Image createThumbnail(File file) throws IOException {
    // Gather info
    File thumbnailFile = getThumbnailFile(file);
    if (thumbnailFile.exists()) {
        return ImageUtil.getImage(thumbnailFile);
    }//from www .  j ava2  s. c  om

    Image image = ImageUtil.getImage(file);
    Dimension imgSize = new Dimension(image.getWidth(null), image.getHeight(null));

    // Test if we Should we bother making a thumbnail ?
    // Jamz: New size 100k (was 30k) and put in check so we're not creating thumbnails LARGER than the original...
    if (file.length() < 102400
            || (imgSize.width <= thumbnailSize.width && imgSize.height <= thumbnailSize.height)) {
        return image;
    }
    // Transform the image
    SwingUtil.constrainTo(imgSize, Math.min(image.getWidth(null), thumbnailSize.width),
            Math.min(image.getHeight(null), thumbnailSize.height));
    BufferedImage thumbnailImage = new BufferedImage(imgSize.width, imgSize.height,
            ImageUtil.pickBestTransparency(image));

    Graphics2D g = thumbnailImage.createGraphics();
    g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
    g.drawImage(image, 0, 0, imgSize.width, imgSize.height, null);
    g.dispose();

    // Use png to preserve transparency
    FileUtils.writeByteArrayToFile(thumbnailFile, ImageUtil.imageToBytes(thumbnailImage, "png"));

    return thumbnailImage;
}

From source file:bjerne.gallery.service.impl.ImageResizeServiceImpl.java

@Override
public void resizeImage(File origImage, File newImage, int width, int height) throws IOException {
    LOG.debug("Entering resizeImage(origImage={}, width={}, height={})", origImage, width, height);
    long startTime = System.currentTimeMillis();
    InputStream is = new BufferedInputStream(new FileInputStream(origImage));
    BufferedImage i = ImageIO.read(is);
    IOUtils.closeQuietly(is);//from  w w w.  j  a  v a2  s .  c  o  m
    BufferedImage scaledImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    int origWidth = i.getWidth();
    int origHeight = i.getHeight();
    LOG.debug("Original size of image - width: {}, height={}", origWidth, height);
    float widthFactor = ((float) origWidth) / ((float) width);
    float heightFactor = ((float) origHeight) / ((float) height);
    float maxFactor = Math.max(widthFactor, heightFactor);
    int newHeight, newWidth;
    if (maxFactor > 1) {
        newHeight = (int) (((float) origHeight) / maxFactor);
        newWidth = (int) (((float) origWidth) / maxFactor);
    } else {
        newHeight = origHeight;
        newWidth = origWidth;
    }
    LOG.debug("Size of scaled image will be: width={}, height={}", newWidth, newHeight);
    int startX = Math.max((width - newWidth) / 2, 0);
    int startY = Math.max((height - newHeight) / 2, 0);
    Graphics2D scaledGraphics = scaledImage.createGraphics();
    scaledGraphics.setColor(backgroundColor);
    scaledGraphics.fillRect(0, 0, width, height);
    scaledGraphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
            RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    scaledGraphics.drawImage(i, startX, startY, newWidth, newHeight, null);
    OutputStream resultImageOutputStream = new BufferedOutputStream(FileUtils.openOutputStream(newImage));
    String extension = FilenameUtils.getExtension(origImage.getName());
    ImageIO.write(scaledImage, extension, resultImageOutputStream);
    IOUtils.closeQuietly(resultImageOutputStream);
    long duration = System.currentTimeMillis() - startTime;
    LOG.debug("Time in milliseconds to scale {}: {}", newImage.toString(), duration);
}

From source file:be.fedict.eid.applet.service.PhotoServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    LOG.debug("doGet");
    response.setContentType("image/jpg");
    response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate, max-age=-1"); // http 1.1
    response.setHeader("Pragma", "no-cache, no-store"); // http 1.0
    response.setDateHeader("Expires", -1);
    ServletOutputStream out = response.getOutputStream();
    HttpSession session = request.getSession();
    byte[] photoData = (byte[]) session.getAttribute(IdentityDataMessageHandler.PHOTO_SESSION_ATTRIBUTE);
    if (null != photoData) {
        BufferedImage photo = ImageIO.read(new ByteArrayInputStream(photoData));
        if (null == photo) {
            /*/*from  w  ww .  j av a 2  s  . c  om*/
             * In this case we render a photo containing some error message.
             */
            photo = new BufferedImage(140, 200, BufferedImage.TYPE_INT_RGB);
            Graphics2D graphics = (Graphics2D) photo.getGraphics();
            RenderingHints renderingHints = new RenderingHints(RenderingHints.KEY_TEXT_ANTIALIASING,
                    RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
            graphics.setRenderingHints(renderingHints);
            graphics.setColor(Color.WHITE);
            graphics.fillRect(1, 1, 140 - 1 - 1, 200 - 1 - 1);
            graphics.setColor(Color.RED);
            graphics.setFont(new Font("Dialog", Font.BOLD, 20));
            graphics.drawString("Photo Error", 0, 200 / 2);
            graphics.dispose();
            ImageIO.write(photo, "jpg", out);
        } else {
            out.write(photoData);
        }
    }
    out.close();
}