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:PNGDecoder.java

/**
 * Decodes image from an input stream passed into constructor.
 * @return a BufferedImage object/*from w w  w. j  av  a  2  s.c o  m*/
 * @throws IOException
 */
public BufferedImage decode() throws IOException {

    byte[] id = read(12);
    checkEquality(id, new byte[] { -119, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13 });

    byte[] ihdr = read(4);
    checkEquality(ihdr, "IHDR".getBytes());

    int width = readInt();
    int height = readInt();

    BufferedImage result = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

    byte[] head = read(5);
    int mode;
    if (compare(head, new byte[] { 1, 0, 0, 0, 0 })) {
        mode = PNGEncoder.BW_MODE;
    } else if (compare(head, new byte[] { 8, 0, 0, 0, 0 })) {
        mode = PNGEncoder.GREYSCALE_MODE;
    } else if (compare(head, new byte[] { 8, 2, 0, 0, 0 })) {
        mode = PNGEncoder.COLOR_MODE;
    } else {
        throw (new RuntimeException("Format error"));
    }

    readInt();//!!crc

    int size = readInt();

    byte[] idat = read(4);
    checkEquality(idat, "IDAT".getBytes());

    byte[] data = read(size);

    Inflater inflater = new Inflater();
    inflater.setInput(data, 0, size);

    int color;

    try {
        switch (mode) {
        case PNGEncoder.BW_MODE: {
            int bytes = (int) (width / 8);
            if ((width % 8) != 0) {
                bytes++;
            }
            byte colorset;
            byte[] row = new byte[bytes];
            for (int y = 0; y < height; y++) {
                inflater.inflate(new byte[1]);
                inflater.inflate(row);
                for (int x = 0; x < bytes; x++) {
                    colorset = row[x];
                    for (int sh = 0; sh < 8; sh++) {
                        if (x * 8 + sh >= width) {
                            break;
                        }
                        if ((colorset & 0x80) == 0x80) {
                            result.setRGB(x * 8 + sh, y, Color.white.getRGB());
                        } else {
                            result.setRGB(x * 8 + sh, y, Color.black.getRGB());
                        }
                        colorset <<= 1;
                    }
                }
            }
        }
            break;
        case PNGEncoder.GREYSCALE_MODE: {
            byte[] row = new byte[width];
            for (int y = 0; y < height; y++) {
                inflater.inflate(new byte[1]);
                inflater.inflate(row);
                for (int x = 0; x < width; x++) {
                    color = row[x];
                    result.setRGB(x, y, (color << 16) + (color << 8) + color);
                }
            }
        }
            break;
        case PNGEncoder.COLOR_MODE: {
            byte[] row = new byte[width * 3];
            for (int y = 0; y < height; y++) {
                inflater.inflate(new byte[1]);
                inflater.inflate(row);
                for (int x = 0; x < width; x++) {
                    result.setRGB(x, y, ((row[x * 3 + 0] & 0xff) << 16) + ((row[x * 3 + 1] & 0xff) << 8)
                            + ((row[x * 3 + 2] & 0xff)));
                }
            }
        }
        }
    } catch (DataFormatException e) {
        throw (new RuntimeException("ZIP error" + e));
    }

    readInt();//!!crc
    readInt();//0

    byte[] iend = read(4);
    checkEquality(iend, "IEND".getBytes());

    readInt();//!!crc
    in.close();

    return (result);
}

From source file:SaveImage.java

public void filterImage() {
    BufferedImageOp op = null;/*from w  w  w  .j  a va  2s .  co m*/

    if (opIndex == lastOp) {
        return;
    }
    lastOp = opIndex;
    switch (opIndex) {

    case 0:
        biFiltered = bi; /* original */
        return;
    case 1: /* low pass filter */
    case 2: /* sharpen */
        float[] data = (opIndex == 1) ? BLUR3x3 : SHARPEN3x3;
        op = new ConvolveOp(new Kernel(3, 3, data), ConvolveOp.EDGE_NO_OP, null);

        break;

    case 3: /* lookup */
        byte lut[] = new byte[256];
        for (int j = 0; j < 256; j++) {
            lut[j] = (byte) (256 - j);
        }
        ByteLookupTable blut = new ByteLookupTable(0, lut);
        op = new LookupOp(blut, null);
        break;
    }

    /*
     * Rather than directly drawing the filtered image to the destination,
     * filter it into a new image first, then that filtered image is ready for
     * writing out or painting.
     */
    biFiltered = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
    op.filter(bi, biFiltered);
}

From source file:PSDReader.java

/**
 * Gets the image contents of frame n. Note that this expands the image to the
 * full frame size (if the layer was smaller) and any subsequent use of
 * getLayer() will return the full image.
 * /*w w  w .java2 s  .c o  m*/
 * @return BufferedImage representation of frame, or null if n is invalid.
 */
public BufferedImage getFrame(int n) {
    BufferedImage im = null;
    if ((n >= 0) && (n < nLayers)) {
        im = frames[n];
        LayerInfo info = layers[n];
        if ((info.w != width) || (info.h != height)) {
            BufferedImage temp = new BufferedImage(width, height, ImageType);
            Graphics2D gc = temp.createGraphics();
            gc.drawImage(im, info.x, info.y, null);
            gc.dispose();
            im = temp;
            frames[n] = im;
        }
    }
    return im;
}

From source file:ch.rasc.downloadchart.DownloadChartServlet.java

private static void handleJpg(HttpServletResponse response, byte[] imageData, Integer width, Integer height,
        String filename, JpegOptions options) throws IOException {

    response.setContentType("image/jpeg");
    response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + ".jpg\";");

    BufferedImage image = ImageIO.read(new ByteArrayInputStream(imageData));

    Dimension newDimension = calculateDimension(image, width, height);
    int imgWidth = image.getWidth();
    int imgHeight = image.getHeight();
    if (newDimension != null) {
        imgWidth = newDimension.width;//  ww w  . j  a  v a  2  s  . c o  m
        imgHeight = newDimension.height;
    }

    BufferedImage newImage = new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_INT_RGB);

    Graphics2D g = newImage.createGraphics();
    g.drawImage(image, 0, 0, imgWidth, imgHeight, Color.BLACK, null);
    g.dispose();

    if (newDimension != null) {
        g.setComposite(AlphaComposite.Src);
        g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    }

    try (ImageOutputStream ios = ImageIO.createImageOutputStream(response.getOutputStream())) {
        Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName("jpg");
        ImageWriter writer = iter.next();
        ImageWriteParam iwp = writer.getDefaultWriteParam();
        iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        if (options != null && options.quality != null && options.quality != 0 && options.quality != 100) {
            iwp.setCompressionQuality(options.quality / 100f);
        } else {
            iwp.setCompressionQuality(1);
        }
        writer.setOutput(ios);
        writer.write(null, new IIOImage(newImage, null, null), iwp);
        writer.dispose();
    }
}

From source file:AffineTransformApp.java

public void createBufferedImages() {
    biSrc = new BufferedImage(displayImage.getWidth(this), displayImage.getHeight(this),
            BufferedImage.TYPE_INT_RGB);

    big = biSrc.createGraphics();/*from w  ww. j  a v  a 2  s . co m*/
    big.drawImage(displayImage, 0, 0, this);

    bi = biSrc;

    biDest = new BufferedImage(displayImage.getWidth(this), displayImage.getHeight(this),
            BufferedImage.TYPE_INT_RGB);
}

From source file:edu.sdsc.scigraph.services.jersey.writers.ImageWriter.java

private static BufferedImage renderImage(JPanel panel) {
    JFrame frame = new JFrame();
    frame.setUndecorated(true);//from   www  .ja v  a2 s. c  o  m
    frame.getContentPane().add(panel);
    frame.pack();
    BufferedImage bi = new BufferedImage(panel.getWidth(), panel.getHeight(), BufferedImage.TYPE_INT_ARGB);
    Graphics2D graphics = bi.createGraphics();
    panel.print(graphics);
    graphics.dispose();
    frame.dispose();
    return bi;
}

From source file:probe.com.model.util.vaadintoimageutil.Convertor.java

public String toImage(int height, int width, JComponent component) {
    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    Graphics2D graphics = image.createGraphics();
    graphics.setPaint(Color.WHITE);
    component.paint(graphics);/*from   w w  w .  j ava  2 s. c  om*/
    //        super.paint(graphics);
    byte[] imageData = null;

    try {

        imageData = in.encode(image);
    } catch (Exception e) {
        System.out.println(e.getLocalizedMessage());
    }

    String base64 = Base64.encodeBytes(imageData);
    base64 = "data:image/png;base64," + base64;
    return base64;

}

From source file:org.n52.io.measurement.img.ChartIoHandler.java

private BufferedImage createImage() {
    int width = getChartStyleDefinitions().getWidth();
    int height = getChartStyleDefinitions().getHeight();
    BufferedImage chartImage = new BufferedImage(width, height, TYPE_INT_RGB);
    Graphics2D chartGraphics = chartImage.createGraphics();
    chartGraphics.fillRect(0, 0, width, height);
    chartGraphics.setColor(WHITE);//from  w  w  w  . j a  va 2s  .c  om

    chart.setTextAntiAlias(true);
    chart.setAntiAlias(true);
    if (chart.getLegend() != null) {
        chart.getLegend().setFrame(BlockBorder.NONE);
    }
    chart.draw(chartGraphics, new Rectangle2D.Float(0, 0, width, height));
    return chartImage;
}

From source file:Main.java

public BufferedImage getImageAsCircle() {
    if (circleImage == null) {
        circleImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        circlePixels = ((DataBufferInt) circleImage.getRaster().getDataBuffer()).getData();
        int radius = Math.min(width, height) >> 1;
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                if (Math.sqrt((Math.max(width >> 1, x) - Math.min(width >> 1, x))
                        * (Math.max(width >> 1, x) - Math.min(width >> 1, x))
                        + (Math.max(height >> 1, y) - Math.min(height >> 1, y))
                                * (Math.max(height >> 1, y) - Math.min(height >> 1, y))) <= radius) {
                    circlePixels[x + y * width] = pixels[x + y * width];
                }/*from   ww w  .  j  av a  2 s  . c  om*/
            }
        }
    }
    return circleImage;
}

From source file:com.aquest.emailmarketing.web.controllers.TrackingController.java

/**
 * Gets the image./*w  ww .  j a  v  a  2s . c o  m*/
 *
 * @param request the request
 * @param response the response
 * @param trackingId the tracking id
 * @return the image
 * @throws IOException Signals that an I/O exception has occurred.
 * @throws FileNotFoundException the file not found exception
 * @throws ParserConfigurationException the parser configuration exception
 * @throws TransformerException the transformer exception
 * @throws ServletException the servlet exception
 * @throws FileUploadException the file upload exception
 */
@RequestMapping(value = "/openTrack", method = RequestMethod.GET)
public void getImage(HttpServletRequest request, HttpServletResponse response,
        @RequestParam("trackingId") String trackingId) throws IOException, FileNotFoundException,
        ParserConfigurationException, TransformerException, ServletException, FileUploadException {
    BufferedImage pixel;
    Timestamp curTimestamp = new java.sql.Timestamp(Calendar.getInstance().getTime().getTime());

    EmailList emailList = emailListService.getEmailListById(trackingId);
    TrackingResponse trackingResponse = new TrackingResponse();
    trackingResponse.setBroadcast_id(emailList.getBroadcast_id());
    trackingResponse.setEmail(emailList.getEmail());
    trackingResponse.setResponse_type("Open");
    trackingResponse.setUnique_id(emailList.getId());
    trackingResponse.setResponse_source("Internal Tracking");
    trackingResponse.setResponse_time(curTimestamp);
    trackingResponse.setProcessed_dttm(curTimestamp);
    trackingResponseService.SaveOrUpdate(trackingResponse);

    System.out.println(trackingId);
    // dodati logiku za ubacivanje response-a.

    pixel = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
    pixel.setRGB(0, 0, (0xFF));

    response.setContentType("image/png");
    OutputStream os = response.getOutputStream();
    ImageIO.write(pixel, "png", os);
    System.out.println("Neko je pristupio!!!");
}