Example usage for java.awt.image BufferedImage TYPE_INT_RGB

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

Introduction

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

Prototype

int TYPE_INT_RGB

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

Click Source Link

Document

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

Usage

From source file:com.ace.erp.controller.sys.company.OrganizationController.java

@RequestMapping(value = "/company/uploadLogo", method = RequestMethod.POST)
@ResponseBody//from   www . j  av a 2s  .  c o m
public Response uploadLogo(@CurrentUser User user, String srcImageFile, int x, int y, int destWidth,
        int destHeight, int srcShowWidth, int srcShowHeight, HttpServletRequest request) {
    try {
        String path = request.getSession().getServletContext().getRealPath("/");
        String contextPath = request.getContextPath();
        Image img;
        ImageFilter cropFilter;
        //String srcFileName = FilenameUtils.getName(srcImageFile);
        String srcFileName = StringUtils.isNotBlank(contextPath) ? srcImageFile.replaceFirst(contextPath, "")
                : srcImageFile;
        // ???
        File srcFile = new File(path + "/" + srcFileName);

        BufferedImage bi = ImageIO.read(srcFile);
        //??????????
        int srcWidth = bi.getWidth(); // ?
        int srcHeight = bi.getHeight(); // ?
        if (srcShowWidth == 0)
            srcShowWidth = srcWidth;
        if (srcShowHeight == 0)
            srcShowHeight = srcHeight;

        if (srcShowWidth >= destWidth && srcShowHeight >= destHeight) {
            //???
            Image image = bi.getScaledInstance(srcShowWidth, srcShowHeight, Image.SCALE_DEFAULT);

            cropFilter = new CropImageFilter(x, y, destWidth, destHeight);

            img = Toolkit.getDefaultToolkit()
                    .createImage(new FilteredImageSource(image.getSource(), cropFilter));
            BufferedImage tag = new BufferedImage(destWidth, destHeight, BufferedImage.TYPE_INT_RGB);
            Graphics g = tag.getGraphics();
            g.drawImage(img, 0, 0, null); // ??
            g.dispose();

            String ext = FilenameUtils.getExtension(srcImageFile);

            //path += HEADER_PIC;
            //User loginUser = SystemUtil.getLoginUser(request.getSession());
            //String fileName = user.getOrganizationList().get(0).getId()+"";
            File destImageFile = new File(path + "/" + System.currentTimeMillis() + ".jpg");
            // 
            ImageIO.write(tag, ext, destImageFile);

            //loginUser.setPicPath(SystemConst.SYSTEM_CONTEXT_PATH_VALUE + HEADER_PIC + "/" + fileName);
            //userService.update(loginUser);
            // 
            srcFile.delete();
            return new Response(new ResponseHeader(200, 20));
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:ddf.catalog.transformer.input.pdf.PdfInputTransformer.java

private byte[] generatePdfThumbnail(PDDocument pdfDocument) throws IOException {

    PDFRenderer pdfRenderer = new PDFRenderer(pdfDocument);

    if (pdfDocument.getNumberOfPages() < 1) {
        /*/* w  w  w  . j  a  v  a 2 s.  c  o m*/
         * Can there be a PDF with zero pages??? Should we throw an error or what? The
         * original implementation assumed that a PDF would always have at least one
         * page. That's what I've implemented here, but I don't like make those
         * kinds of assumptions :-( But I also don't want to change the original
         * behavior without knowing how it will impact the system.
         */
    }

    PDPage page = pdfDocument.getPage(0);

    BufferedImage image = pdfRenderer.renderImageWithDPI(0, RESOLUTION_DPI, ImageType.RGB);

    int largestDimension = Math.max(image.getHeight(), image.getWidth());
    float scalingFactor = IMAGE_HEIGHTWIDTH / largestDimension;
    int scaledHeight = (int) (image.getHeight() * scalingFactor);
    int scaledWidth = (int) (image.getWidth() * scalingFactor);

    BufferedImage scaledImage = new BufferedImage(scaledWidth, scaledHeight, BufferedImage.TYPE_INT_RGB);
    Graphics2D graphics = scaledImage.createGraphics();
    graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    graphics.drawImage(image, 0, 0, scaledWidth, scaledHeight, null);
    graphics.dispose();

    try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
        ImageIOUtil.writeImage(scaledImage, FORMAT_NAME, outputStream, RESOLUTION_DPI, IMAGE_QUALITY);
        return outputStream.toByteArray();
    }
}

From source file:ddf.catalog.transformer.input.pptx.PptxInputTransformer.java

/**
 * If the slide show doesn't contain any slides, then return null. Otherwise, return jpeg
 * image data of the first slide in the deck.
 *
 * @param slideShow/*from  www  . j  a v  a 2s  .  co  m*/
 * @return jpeg thumbnail or null if thumbnail can't be created
 * @throws IOException
 */
private byte[] generatePptxThumbnail(XMLSlideShow slideShow) throws IOException {

    if (slideShow.getSlides().isEmpty()) {
        LOGGER.info("the powerpoint file does not contain any slides, skipping thumbnail generation");
        return null;
    }

    Dimension pgsize = slideShow.getPageSize();

    int largestDimension = (int) Math.max(pgsize.getHeight(), pgsize.getWidth());
    float scalingFactor = IMAGE_HEIGHTWIDTH / largestDimension;
    int scaledHeight = (int) (pgsize.getHeight() * scalingFactor);
    int scaledWidth = (int) (pgsize.getWidth() * scalingFactor);
    BufferedImage img = new BufferedImage(scaledWidth, scaledHeight, BufferedImage.TYPE_INT_RGB);

    Graphics2D graphics = img.createGraphics();

    try {
        graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        graphics.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
        graphics.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS,
                RenderingHints.VALUE_FRACTIONALMETRICS_ON);

        graphics.scale(scalingFactor, scalingFactor);

        slideShow.getSlides().get(0).draw(graphics);

        try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
            ImageIOUtil.writeImage(img, FORMAT_NAME, outputStream, RESOLUTION_DPI, IMAGE_QUALITY);
            return outputStream.toByteArray();
        }
    } catch (RuntimeException e) {
        if (e.getCause() instanceof javax.imageio.IIOException) {
            LOGGER.warn("unable to generate thumbnail for PPTX file", e);
        } else {
            throw e;
        }
    } finally {
        graphics.dispose();
    }

    return null;
}

From source file:de.romankreisel.faktotum.beans.BundesbruderBean.java

private Byte[] storeImageToByteArray(Image image) throws IOException {
    if (!(image instanceof RenderedImage)) {
        BufferedImage newImage = new BufferedImage(image.getWidth(null), image.getHeight(null),
                BufferedImage.TYPE_INT_RGB);
        newImage.getGraphics().drawImage(image, 0, 0, null);
        image = newImage;/* www . j  av a  2s  .  c o  m*/
    }
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    ImageIO.write((RenderedImage) image, "jpg", byteArrayOutputStream);
    byteArrayOutputStream.flush();
    byte[] imageInByte = byteArrayOutputStream.toByteArray();
    byteArrayOutputStream.close();
    return ArrayUtils.toObject(imageInByte);
}

From source file:editeurpanovisu.ReadWriteImage.java

/**
 *
 * @param img//from  ww w.  ja  v  a  2  s .  co  m
 * @param destFile
 * @param sharpen
 * @param sharpenLevel
 * @throws IOException
 */
public static void writeBMP(Image img, String destFile, boolean sharpen, float sharpenLevel)
        throws IOException {
    sharpenMatrix = calculeSharpenMatrix(sharpenLevel);
    BufferedImage imageRGBSharpen = null;
    IIOImage iioImage = null;

    BufferedImage image = SwingFXUtils.fromFXImage(img, null); // Get buffered image.
    BufferedImage imageRGB = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.OPAQUE); // Remove alpha-channel from buffered image.

    Graphics2D graphics = imageRGB.createGraphics();
    graphics.drawImage(image, 0, 0, null);
    if (sharpen) {

        imageRGBSharpen = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_RGB);
        Kernel kernel = new Kernel(3, 3, sharpenMatrix);
        ConvolveOp cop = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);
        cop.filter(imageRGB, imageRGBSharpen);
    }
    ImageWriter writer = null;
    FileImageOutputStream output = null;
    try {
        writer = ImageIO.getImageWritersByFormatName("bmp").next();
        ImageWriteParam param = writer.getDefaultWriteParam();
        output = new FileImageOutputStream(new File(destFile));
        writer.setOutput(output);
        if (sharpen) {
            iioImage = new IIOImage(imageRGBSharpen, null, null);
        } else {
            iioImage = new IIOImage(imageRGB, null, null);
        }
        writer.write(null, iioImage, param);
    } catch (IOException ex) {
        throw ex;
    } finally {
        if (writer != null) {
            writer.dispose();
        }
        if (output != null) {
            output.close();
        }
    }
    graphics.dispose();
}

From source file:JuliaSet2.java

void computeImage() {
    // Create the image
    image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

    // Now loop through the pixels
    int i, j;/*from www.  j a  v  a2  s .c o  m*/
    double x, y;
    double dx = (x2 - x1) / width;
    double dy = (y2 - y1) / height;
    for (j = 0, y = y1; j < height; j++, y += dy) {
        for (i = 0, x = x1; i < width; i++, x += dx) {
            // For each pixel, call testPoint() to determine a value.
            // Then map that value to a color and set it in the image.
            // If testPoint() returns 0, the point is part of the Julia set
            // and is displayed in black. If it returns 63, the point is
            // displayed in white. Values in-between are displayed in
            // varying shades of gray.
            image.setRGB(i, j, colors[testPoint(x, y)]);
        }
    }
}

From source file:RasterTest.java

public void updateRenderRaster() {
    // takes the Depth Raster and updates the Render Raster
    // containing the image based on the depth values stored in
    // the Depth Raster.

    // create a temporary BufferedImage for the depth components
    BufferedImage tempBufferedImage = new BufferedImage(m_DepthRaster.getDepthComponent().getWidth(),
            m_DepthRaster.getDepthComponent().getHeight(), BufferedImage.TYPE_INT_RGB);

    // allocate an array of ints to store the depth components from the
    // Depth Raster
    if (m_DepthData == null)
        m_DepthData = new int[m_DepthRaster.getDepthComponent().getWidth()
                * m_DepthRaster.getDepthComponent().getHeight()];

    // copy the depth values from the Raster into the int array
    ((DepthComponentInt) m_DepthRaster.getDepthComponent()).getDepthData(m_DepthData);

    // assign the depth values to the temporary image, the integer depths
    // will be//from  w w  w  . j  a v a 2 s . c  om
    // interpreted as integer rgb values.
    tempBufferedImage.setRGB(0, 0, m_DepthRaster.getDepthComponent().getWidth(),
            m_DepthRaster.getDepthComponent().getHeight(), m_DepthData, 0,
            m_DepthRaster.getDepthComponent().getWidth());

    // get a graphics device for the image
    Graphics g = tempBufferedImage.getGraphics();
    Dimension size = new Dimension();
    m_RenderRaster.getSize(size);

    // because the Depth Raster is a different size to the Render Raster,
    // i.e. the Depth Raster is canvas width by canvas height and the Render
    // Raster
    // is of aritrary size, we rescale the image here.
    g.drawImage(tempBufferedImage, 0, 0, (int) size.getWidth(), (int) size.getHeight(), null);

    // finally, assign the scaled image to the RenderRaster
    m_RenderRaster.setImage(new ImageComponent2D(BufferedImage.TYPE_INT_RGB, tempBufferedImage));
}

From source file:com.openbravo.pos.util.JRPrinterAWT.java

/**
 *
 *///from w w w.j  ava  2  s . co  m
public Image printPageToImage(int pageIndex, float zoom) throws JRException {
    Image pageImage = new BufferedImage((int) (jasperPrint.getPageWidth() * zoom) + 1,
            (int) (jasperPrint.getPageHeight() * zoom) + 1, BufferedImage.TYPE_INT_RGB);

    JRGraphics2DExporter exporter = new JRGraphics2DExporter(jasperReportsContext);
    exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
    exporter.setParameter(JRGraphics2DExporterParameter.GRAPHICS_2D, pageImage.getGraphics());
    exporter.setParameter(JRExporterParameter.PAGE_INDEX, Integer.valueOf(pageIndex));
    exporter.setParameter(JRGraphics2DExporterParameter.ZOOM_RATIO, new Float(zoom));
    exporter.exportReport();

    return pageImage;
}

From source file:com.galenframework.utils.GalenUtils.java

/**
 * Check the devicePixelRatio and adapts the size of the screenshot as if the ratio was 1.0
 * @param driver//from   ww  w  .  jav a 2s. com
 * @param screenshotImage
 * @return
 */
public static BufferedImage resizeScreenshotIfNeeded(WebDriver driver, BufferedImage screenshotImage) {
    Double devicePixelRatio = ((Number) ((JavascriptExecutor) driver)
            .executeScript(JS_RETRIEVE_DEVICE_PIXEL_RATIO)).doubleValue();

    if (devicePixelRatio > 1.0 && screenshotImage.getWidth() > 0) {
        Long screenSize = (Long) ((JavascriptExecutor) driver).executeScript(
                "return Math.max(" + "document.body.scrollWidth, document.documentElement.scrollWidth,"
                        + "document.body.offsetWidth, document.documentElement.offsetWidth,"
                        + "document.body.clientWidth, document.documentElement.clientWidth);");

        Double estimatedPixelRatio = ((double) screenshotImage.getWidth()) / ((double) screenSize);

        if (estimatedPixelRatio > 1.0) {

            int newWidth = (int) (screenshotImage.getWidth() / estimatedPixelRatio);
            int newHeight = (int) (screenshotImage.getHeight() / estimatedPixelRatio);

            Image tmp = screenshotImage.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH);
            BufferedImage scaledImage = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);

            Graphics2D g2d = scaledImage.createGraphics();
            g2d.drawImage(tmp, 0, 0, null);
            g2d.dispose();

            return scaledImage;
        } else
            return screenshotImage;
    } else
        return screenshotImage;
}

From source file:com.esri.ArcGISController.java

@RequestMapping(value = "/rest/services/InfoUSA/MapServer/export", method = { RequestMethod.GET,
        RequestMethod.POST })//  ww  w .j  a  v  a 2 s.c  om
public void doExport(@RequestParam("bbox") final String bbox,
        @RequestParam(value = "size", required = false) final String size,
        @RequestParam(value = "layerDefs", required = false) final String layerDefs,
        @RequestParam(value = "transparent", required = false) final String transparent,
        final HttpServletResponse response) throws IOException {
    double xmin = -1.0, ymin = -1.0, xmax = 1.0, ymax = 1.0;
    if (bbox != null && bbox.length() > 0) {
        final String[] tokens = m_patternComma.split(bbox);
        if (tokens.length == 4) {
            xmin = Double.parseDouble(tokens[0]);
            ymin = Double.parseDouble(tokens[1]);
            xmax = Double.parseDouble(tokens[2]);
            ymax = Double.parseDouble(tokens[3]);
        } else {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                    "bbox is not in the form xmin,ymin,xmax,ymax");
            return;
        }
    } else {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "bbox is null or empty");
        return;
    }

    final double xdel = xmax - xmin;
    final double ydel = ymax - ymin;

    int imageWidth = 400;
    int imageHeight = 400;
    if (size != null && size.length() > 0) {
        final String[] tokens = m_patternComma.split(size);
        if (tokens.length == 2) {
            imageWidth = Integer.parseInt(tokens[0], 10);
            imageHeight = Integer.parseInt(tokens[1], 10);
        } else {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "size is not in the form width,height");
            return;
        }
    }
    String where = null;
    double lo = Double.NaN;
    double hi = Double.NaN;
    int[] ramp = null;
    if (layerDefs != null) {
        final String[] tokens = m_patternSemiColon.split(layerDefs);
        for (final String token : tokens) {
            final String[] keyval = m_patternEqual.split(token.substring(2));
            if (keyval.length == 2) {
                final String key = keyval[0];
                final String val = keyval[1];
                if ("lo".equalsIgnoreCase(key)) {
                    lo = "NaN".equalsIgnoreCase(val) ? Double.NaN : Double.parseDouble(val);
                } else if ("hi".equalsIgnoreCase(key)) {
                    hi = "NaN".equalsIgnoreCase(val) ? Double.NaN : Double.parseDouble(val);
                } else if ("ramp".equalsIgnoreCase(key)) {
                    ramp = parseRamp(val);
                } else if ("where".equalsIgnoreCase(key)) {
                    where = val;
                }
            }
        }
    }
    if (ramp == null) {
        ramp = new int[] { 0xFFFFFF, 0x000000 };
    }

    final Range range = new Range();
    final Map<Long, Double> map = query(where, xmin, ymin, xmax, ymax, range);
    if (!Double.isNaN(lo)) {
        range.lo = lo;
    }
    if (!Double.isNaN(hi)) {
        range.hi = hi;
    }
    range.dd = range.hi - range.lo;

    final int typeIntRgb = "true".equalsIgnoreCase(transparent) ? BufferedImage.TYPE_INT_ARGB
            : BufferedImage.TYPE_INT_RGB;
    BufferedImage bufferedImage = new BufferedImage(imageWidth, imageHeight, typeIntRgb);
    final Graphics2D graphics = bufferedImage.createGraphics();
    try {
        graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        graphics.setBackground(new Color(0, 0, 0, 0));

        drawCells(graphics, imageWidth, imageHeight, xmin, ymin, xdel, ydel, range, ramp, map.entrySet());
    } finally {
        graphics.dispose();
    }

    // bufferedImage = m_op.filter(bufferedImage, null);

    final ByteArrayOutputStream baos = new ByteArrayOutputStream(10 * 1024);
    ImageIO.write(bufferedImage, "PNG", baos);

    response.setStatus(HttpServletResponse.SC_OK);
    response.setContentType("image/png");
    response.setContentLength(baos.size());
    baos.writeTo(response.getOutputStream());
    response.getOutputStream().flush();
}