Example usage for java.awt.image BufferedImage flush

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

Introduction

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

Prototype

public void flush() 

Source Link

Document

Flushes all reconstructable resources being used by this Image object.

Usage

From source file:org.wkm.mtool.service.QRCodeService.java

/**
 * ??(QRCode)// w  w w  .  ja va 2  s . c  o m
 * @param content
 * @param imgFile
 */
private void encoderQRCode(String content, File imgFile) {
    try {
        Qrcode qrcodeHandler = new Qrcode();
        qrcodeHandler.setQrcodeErrorCorrect('M');
        qrcodeHandler.setQrcodeEncodeMode('B');
        qrcodeHandler.setQrcodeVersion(7);

        System.out.println(content);
        byte[] contentBytes = content.getBytes(Consts.UTF_8.name());

        BufferedImage bufImg = new BufferedImage(140, 140, BufferedImage.TYPE_INT_RGB);

        Graphics2D gs = bufImg.createGraphics();

        gs.setBackground(Color.WHITE);
        gs.clearRect(0, 0, 140, 140);

        // ? > BLACK
        gs.setColor(Color.BLACK);

        // ??? ???
        int pixoff = 2;
        //  > ?
        if (contentBytes.length > 0 && contentBytes.length < 120) {
            boolean[][] codeOut = qrcodeHandler.calQrcode(contentBytes);
            for (int i = 0; i < codeOut.length; i++) {
                for (int j = 0; j < codeOut.length; j++) {
                    if (codeOut[j][i]) {
                        gs.fillRect(j * 3 + pixoff, i * 3 + pixoff, 3, 3);
                    }
                }
            }
        } else {
            System.err.println("QRCode content bytes length = " + contentBytes.length + " not in [ 0,120 ]. ");
        }

        gs.dispose();
        bufImg.flush();

        // ??QRCode
        ImageIO.write(bufImg, "png", imgFile);

    } catch (Exception e) {
        log.info("Exception:" + e.getMessage());
    }
}

From source file:dk.dma.msiproxy.common.repo.ThumbnailService.java

/**
 * Creates a thumbnail for the image file using plain old java
 * @param file the image file// w  w w.j a  v  a 2  s. c  om
 * @param thumbFile the resulting thumbnail file
 * @param size the size of the thumbnail
 */
private void createThumbnailUsingJava(Path file, Path thumbFile, IconSize size) throws IOException {

    try {
        BufferedImage image = ImageIO.read(file.toFile());

        int w = image.getWidth();
        int h = image.getHeight();

        // Never scale up
        if (w <= size.getSize() && h <= size.getSize()) {
            FileUtils.copyFile(file.toFile(), thumbFile.toFile());

        } else {
            // Compute the scale factor
            double dx = (double) size.getSize() / (double) w;
            double dy = (double) size.getSize() / (double) h;
            double d = Math.min(dx, dy);

            // Create the thumbnail
            BufferedImage thumbImage = new BufferedImage((int) Math.round(w * d), (int) Math.round(h * d),
                    BufferedImage.TYPE_INT_RGB);
            Graphics2D g2d = thumbImage.createGraphics();
            AffineTransform at = AffineTransform.getScaleInstance(d, d);
            g2d.drawRenderedImage(image, at);
            g2d.dispose();

            // Save the thumbnail
            String fileName = thumbFile.getFileName().toString();
            ImageIO.write(thumbImage, FilenameUtils.getExtension(fileName), thumbFile.toFile());

            // Releas resources
            image.flush();
            thumbImage.flush();
        }

        // Update the timestamp of the thumbnail file to match the change date of the image file
        Files.setLastModifiedTime(thumbFile, Files.getLastModifiedTime(file));

    } catch (Exception e) {
        log.error("Error creating thumbnail for image " + file, e);
        throw new IOException(e);
    }
}

From source file:J3dSwingFrame.java

/**
 * Set the texture on our goemetry/*from   ww w. j  a v a 2 s .c om*/
 * <P>
 * Always specified as a URL so that we may fetch it from anywhere.
 * 
 * @param url
 *            The url to the image.
 */
public void setTexture(URL url) {
    Toolkit tk = Toolkit.getDefaultToolkit();
    Image src_img = tk.createImage(url);
    BufferedImage buf_img = null;

    if (!(src_img instanceof BufferedImage)) {
        // create a component anonymous inner class to give us the image
        // observer we need to get the width and height of the source image.
        Component obs = new Component() {
        };

        int width = src_img.getWidth(obs);
        int height = src_img.getHeight(obs);

        // construct the buffered image from the source data.
        buf_img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);

        Graphics g = buf_img.getGraphics();
        g.drawImage(src_img, 0, 0, null);
        g.dispose();
    } else
        buf_img = (BufferedImage) src_img;

    src_img.flush();

    ImageComponent img_comp = new ImageComponent2D(ImageComponent.FORMAT_RGB, buf_img);

    texture = new Texture2D(Texture.BASE_LEVEL, Texture.RGB, img_comp.getWidth(), img_comp.getHeight());

    appearance.setTexture(texture);

    buf_img.flush();
}

From source file:dk.dma.msinm.web.OsmStaticMap.java

public BufferedImage createBaseMap(MapImageCtx ctx) {
    BufferedImage image = new BufferedImage(ctx.width, ctx.height, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2 = image.createGraphics();
    int startX = (int) Math.floor(ctx.centerX - (ctx.width / ctx.tileSize) / 2.0);
    int startY = (int) Math.floor(ctx.centerY - (ctx.height / ctx.tileSize) / 2.0);
    int endX = (int) Math.ceil(ctx.centerX + (ctx.width / ctx.tileSize) / 2.0);
    int endY = (int) Math.ceil(ctx.centerY + (ctx.height / ctx.tileSize) / 2.0);
    ctx.offsetX = -Math.floor((ctx.centerX - Math.floor(ctx.centerX)) * ctx.tileSize);
    ctx.offsetY = -Math.floor((ctx.centerY - Math.floor(ctx.centerY)) * ctx.tileSize);
    ctx.offsetX += Math.floor(ctx.width / 2.0);
    ctx.offsetY += Math.floor(ctx.height / 2.0);
    ctx.offsetX += Math.floor(startX - Math.floor(ctx.centerX)) * ctx.tileSize;
    ctx.offsetY += Math.floor(startY - Math.floor(ctx.centerY)) * ctx.tileSize;

    for (int x = startX; x <= endX; x++) {
        for (int y = startY; y <= endY; y++) {
            String url = String.format(OSM_URL, ctx.zoom, x, y);
            log.info("Fetching " + url);
            try {
                BufferedImage tileImage = fetchTile(url);
                double destX = (x - startX) * ctx.tileSize + ctx.offsetX;
                double destY = (y - startY) * ctx.tileSize + ctx.offsetY;
                g2.drawImage(tileImage, (int) destX, (int) destY, ctx.tileSize, ctx.tileSize, null);
                image.flush();
            } catch (Exception e) {
                log.warn("Failed loading image " + url);
            }//from w  ww .j  ava2 s . c  om
        }
    }
    return image;
}

From source file:com.fileOperations.ImageToPDF.java

/**
 * create PDF from image and scales it accordingly to fit in a single page
 *
 * @param folderPath String/*from   ww w.  j a  va2  s.  c o  m*/
 * @param imageFileName String
 * @return String new filename
 */
public static String createPDFFromImageNoDelete(String folderPath, String imageFileName) {
    String pdfFile = FilenameUtils.removeExtension(imageFileName) + ".pdf";
    String image = folderPath + imageFileName;
    PDImageXObject pdImage = null;
    File imageFile = null;
    FileInputStream fileStream = null;
    BufferedImage bim = null;

    File attachmentLocation = new File(folderPath);
    if (!attachmentLocation.exists()) {
        attachmentLocation.mkdirs();
    }

    // the document
    PDDocument doc = null;
    PDPageContentStream contentStream = null;

    try {
        doc = new PDDocument();
        PDPage page = new PDPage(PDRectangle.LETTER);
        float margin = 72;
        float pageWidth = page.getMediaBox().getWidth() - 2 * margin;
        float pageHeight = page.getMediaBox().getHeight() - 2 * margin;

        if (image.toLowerCase().endsWith(".jpg")) {
            imageFile = new File(image);
            fileStream = new FileInputStream(image);
            pdImage = JPEGFactory.createFromStream(doc, fileStream);
            //            } else if ((image.toLowerCase().endsWith(".tif")
            //                    || image.toLowerCase().endsWith(".tiff"))
            //                    && TIFFCompression(image) == COMPRESSION_GROUP4) {
            //                imageFile = new File(image);
            //                pdImage = CCITTFactory.createFromFile(doc, imageFile);
        } else if (image.toLowerCase().endsWith(".gif") || image.toLowerCase().endsWith(".bmp")
                || image.toLowerCase().endsWith(".png")) {
            imageFile = new File(image);
            bim = ImageIO.read(imageFile);
            pdImage = LosslessFactory.createFromImage(doc, bim);
        }

        if (pdImage != null) {
            if (pdImage.getWidth() > pdImage.getHeight()) {
                page.setRotation(270);
                PDRectangle rotatedPage = new PDRectangle(page.getMediaBox().getHeight(),
                        page.getMediaBox().getWidth());
                page.setMediaBox(rotatedPage);
                pageWidth = page.getMediaBox().getWidth() - 2 * margin;
                pageHeight = page.getMediaBox().getHeight() - 2 * margin;
            }
            Dimension pageSize = new Dimension((int) pageWidth, (int) pageHeight);
            Dimension imageSize = new Dimension(pdImage.getWidth(), pdImage.getHeight());
            Dimension scaledDim = PDFBoxTools.getScaledDimension(imageSize, pageSize);
            float startX = page.getMediaBox().getLowerLeftX() + margin;
            float startY = page.getMediaBox().getUpperRightY() - margin - scaledDim.height;

            doc.addPage(page);
            contentStream = new PDPageContentStream(doc, page);
            contentStream.drawImage(pdImage, startX, startY, scaledDim.width, scaledDim.height);
            contentStream.close();
            doc.save(folderPath + pdfFile);
        }
    } catch (IOException ex) {
        ExceptionHandler.Handle(ex);
        return "";
    } finally {
        if (doc != null) {
            try {
                doc.close();
            } catch (IOException ex) {
                ExceptionHandler.Handle(ex);
                return "";
            }
        }
    }
    if (fileStream != null) {
        try {
            fileStream.close();
        } catch (IOException ex) {
            ExceptionHandler.Handle(ex);
            return "";
        }
    }
    if (bim != null) {
        bim.flush();
    }
    return pdfFile;
}

From source file:com.fileOperations.ImageToPDF.java

/**
 * create PDF from image and scales it accordingly to fit in a single page
 *
 * @param folderPath String//from  w w w. j  a  v  a  2 s . c o m
 * @param imageFileName String
 * @return String new filename
 */
public static String createPDFFromImage(String folderPath, String imageFileName) {
    String pdfFile = FilenameUtils.removeExtension(imageFileName) + ".pdf";
    String image = folderPath + imageFileName;
    PDImageXObject pdImage = null;
    File imageFile = null;
    FileInputStream fileStream = null;
    BufferedImage bim = null;

    File attachmentLocation = new File(folderPath);
    if (!attachmentLocation.exists()) {
        attachmentLocation.mkdirs();
    }

    // the document
    PDDocument doc = null;
    PDPageContentStream contentStream = null;

    try {
        doc = new PDDocument();
        PDPage page = new PDPage(PDRectangle.LETTER);
        float margin = 72;
        float pageWidth = page.getMediaBox().getWidth() - 2 * margin;
        float pageHeight = page.getMediaBox().getHeight() - 2 * margin;

        if (image.toLowerCase().endsWith(".jpg")) {
            imageFile = new File(image);
            fileStream = new FileInputStream(image);
            pdImage = JPEGFactory.createFromStream(doc, fileStream);
            //            } else if ((image.toLowerCase().endsWith(".tif")
            //                    || image.toLowerCase().endsWith(".tiff"))
            //                    && TIFFCompression(image) == COMPRESSION_GROUP4) {
            //                imageFile = new File(image);
            //                pdImage = CCITTFactory.createFromFile(doc, imageFile);
        } else if (image.toLowerCase().endsWith(".gif") || image.toLowerCase().endsWith(".bmp")
                || image.toLowerCase().endsWith(".png")) {
            imageFile = new File(image);
            bim = ImageIO.read(imageFile);
            pdImage = LosslessFactory.createFromImage(doc, bim);
        }

        if (pdImage != null) {
            if (pdImage.getWidth() > pdImage.getHeight()) {
                page.setRotation(270);
                PDRectangle rotatedPage = new PDRectangle(page.getMediaBox().getHeight(),
                        page.getMediaBox().getWidth());
                page.setMediaBox(rotatedPage);
                pageWidth = page.getMediaBox().getWidth() - 2 * margin;
                pageHeight = page.getMediaBox().getHeight() - 2 * margin;
            }
            Dimension pageSize = new Dimension((int) pageWidth, (int) pageHeight);
            Dimension imageSize = new Dimension(pdImage.getWidth(), pdImage.getHeight());
            Dimension scaledDim = PDFBoxTools.getScaledDimension(imageSize, pageSize);
            float startX = page.getMediaBox().getLowerLeftX() + margin;
            float startY = page.getMediaBox().getUpperRightY() - margin - scaledDim.height;

            doc.addPage(page);
            contentStream = new PDPageContentStream(doc, page);
            contentStream.drawImage(pdImage, startX, startY, scaledDim.width, scaledDim.height);
            contentStream.close();
            doc.save(folderPath + pdfFile);
        }
    } catch (IOException ex) {
        ExceptionHandler.Handle(ex);
        return "";
    } finally {
        if (doc != null) {
            try {
                doc.close();
            } catch (IOException ex) {
                ExceptionHandler.Handle(ex);
                return "";
            }
        }
    }
    if (fileStream != null) {
        try {
            fileStream.close();
        } catch (IOException ex) {
            ExceptionHandler.Handle(ex);
            return "";
        }
    }
    if (bim != null) {
        bim.flush();
    }
    if (imageFile != null) {
        imageFile.delete();
    }
    return pdfFile;
}

From source file:edu.harvard.iq.dvn.core.web.servlet.FileDownloadServlet.java

private boolean generateImageThumb(StudyFile file) {

    String fileLocation = file.getFileSystemLocation();
    if (fileLocation == null || fileLocation.trim().equals("")) {
        return false;
    }//from w  w w .  j  av  a 2s  .  c  o  m
    String thumbFileLocation = fileLocation + ".thumb";

    // see if the thumb is already generated and saved:

    if (new File(thumbFileLocation).exists()) {
        return true;
    }

    // let's attempt to generate the thumb:

    // the default size of the thumbnail is 64 pixels horizontally.
    // The number 64 was picked arbitrarily; if a different size is 
    // desired, it can be configured via the dvn.image.thumbnail.size 
    // JVM option.

    Long thumbSize = Long.valueOf(64);

    String thumbSizeOption = System.getProperty("dvn.image.thumbnail.size");

    if (thumbSizeOption != null) {
        Long thumbSizeOptionValue = null;
        try {
            thumbSizeOptionValue = new Long(thumbSizeOption);
        } catch (NumberFormatException nfe) {
            // if the supplied option value is invalid/unparseable, we
            // ignore it and fall back to the default value. 
        }
        if (thumbSizeOptionValue != null && thumbSizeOptionValue.longValue() > 0) {
            thumbSize = thumbSizeOptionValue;
        }
    }

    // it is also possible to configure the thumbnail size for a 
    // specific dataverse: 

    VDC vdc = file.getStudy().getOwner();

    if (vdc != null) {
        thumbSizeOption = System.getProperty("dvn.image.thumbnail.size." + vdc.getAlias());

        if (thumbSizeOption != null) {
            Long thumbSizeOptionValue = null;
            try {
                thumbSizeOptionValue = new Long(thumbSizeOption);
            } catch (NumberFormatException nfe) {
                // if the supplied option value is invalid/unparseable, we
                // ignore it and fall back to the default value. 
            }
            if (thumbSizeOptionValue != null && thumbSizeOptionValue.longValue() > 0) {
                thumbSize = thumbSizeOptionValue;
            }
        }
    }

    // This is the default location of the "convert" executable from the
    // ImageMagick package. If it's installed in a different locaiton, 
    // it can be configured via the dvn.image.convert.exec JVM option. 

    String imageMagickConvertExec = "/usr/bin/convert";

    String imageMagickConvertExecOption = System.getProperty("dvn.image.convrt.exec");

    if (imageMagickConvertExecOption != null) {
        if (!imageMagickConvertExecOption.trim().equals("")) {
            imageMagickConvertExec = imageMagickConvertExecOption.trim();
        }
    }

    if (new File(imageMagickConvertExec).exists()) {
        String sizeOption = " -size " + thumbSize + "x" + thumbSize + " ";

        String ImageMagickCommandLine = imageMagickConvertExec + sizeOption + fileLocation + " -resize "
                + thumbSize + " -flatten png:" + thumbFileLocation;
        int exitValue = 1;

        try {
            Runtime runtime = Runtime.getRuntime();
            Process process = runtime.exec(ImageMagickCommandLine);
            exitValue = process.waitFor();
        } catch (Exception e) {
            exitValue = 1;
        }

        if (exitValue == 0) {
            return true;
        }
    }

    // For whatever reason, creating the thumbnail with ImageMagick
    // has failed.
    // Let's try again, this time with Java's standard Image
    // library:

    try {
        BufferedImage fullSizeImage = ImageIO.read(new File(fileLocation));

        if (fullSizeImage == null) {
            return false;
        }

        double scaleFactor = (thumbSize.doubleValue()) / (double) fullSizeImage.getWidth(null);
        int thumbHeight = (int) (fullSizeImage.getHeight(null) * scaleFactor);

        // We are willing to spend a few extra CPU cycles to generate
        // better-looking thumbnails, hence the SCALE_SMOOTH flag. 
        // SCALE_FAST would trade quality for speed. 

        java.awt.Image thumbImage = fullSizeImage.getScaledInstance(thumbSize.intValue(), thumbHeight,
                java.awt.Image.SCALE_SMOOTH);

        ImageWriter writer = null;
        Iterator iter = ImageIO.getImageWritersByFormatName("png");
        if (iter.hasNext()) {
            writer = (ImageWriter) iter.next();
        } else {
            return false;
        }

        BufferedImage lowRes = new BufferedImage(thumbSize.intValue(), thumbHeight, BufferedImage.TYPE_INT_RGB);
        lowRes.getGraphics().drawImage(thumbImage, 0, 0, null);

        ImageOutputStream ios = ImageIO.createImageOutputStream(new File(thumbFileLocation));
        writer.setOutput(ios);

        // finally, save thumbnail image:
        writer.write(lowRes);
        writer.dispose();

        ios.close();
        thumbImage.flush();
        fullSizeImage.flush();
        lowRes.flush();
        return true;
    } catch (Exception e) {
        // something went wrong, returning "false":
        dbgLog.info("ImageIO: caught an exception while trying to generate a thumbnail for " + fileLocation);

        return false;
    }
}

From source file:net.sqs2.omr.session.logic.PageImageRenderer.java

private static void copyImage(BufferedImage src, BufferedImage image) {
    Graphics2D g = (Graphics2D) image.getGraphics();
    int w = image.getWidth();
    int h = image.getHeight();
    g.drawImage(src, 0, 0, w, h, null);/*from www .  j  a v  a2s .  c om*/
    src.flush();
}

From source file:net.tourbook.photo.internal.manager.PhotoImageLoader.java

private void disposeTrackedImages() {

    for (final BufferedImage awtImage : _trackedAWTImages) {
        if (awtImage != null) {
            awtImage.flush();
        }//  w  w w .j a v a 2 s. c  om
    }
    _trackedAWTImages.clear();

    for (final Image swtImage : _trackedSWTImages) {
        if (swtImage != null) {
            swtImage.dispose();
        }
    }
    _trackedSWTImages.clear();
}

From source file:org.eclipse.birt.chart.device.g2d.G2dRendererBase.java

protected java.awt.Image createImageFromModel(Fill imageModel) throws ChartException {

    java.awt.Image img = null;// ww  w .  j  a va  2s.com
    if (imageModel instanceof EmbeddedImage) {
        try {
            byte[] data = Base64.decodeBase64(((EmbeddedImage) imageModel).getData().getBytes());

            img = createImage(data);
        } catch (Exception ilex) {
            throw new ChartException(ChartDeviceExtensionPlugin.ID, ChartException.RENDERING, ilex);
        }
    } else if (imageModel instanceof PatternImage) {
        PatternImage pi = (PatternImage) imageModel;
        byte[] data = PatternImageUtil.createImageData(pi, ByteColorModel.RGBA);
        BufferedImage bimg = new BufferedImage(8, 8, BufferedImage.TYPE_4BYTE_ABGR);
        img = bimg;
        WritableRaster raster = bimg.getRaster();
        raster.setDataElements(0, 0, 8, 8, data);
        bimg.flush();
    } else if (imageModel instanceof org.eclipse.birt.chart.model.attribute.Image) {
        if (((org.eclipse.birt.chart.model.attribute.Image) imageModel).getSource() == ImageSourceType.STATIC) {
            try {
                final String sUrl = ((org.eclipse.birt.chart.model.attribute.Image) imageModel).getURL();
                img = (java.awt.Image) _ids.loadImage(SecurityUtil.newURL(sUrl));
            } catch (ChartException ilex) {
                throw new ChartException(ChartDeviceExtensionPlugin.ID, ChartException.RENDERING, ilex);
            } catch (MalformedURLException muex) {
                throw new ChartException(ChartDeviceExtensionPlugin.ID, ChartException.RENDERING, muex);
            }
        }
    }

    return img;

}