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:ch.sportchef.business.event.control.EventImageService.java

public void uploadImage(@NotNull final Long eventId, @NotNull final byte[] image) throws IOException {
    final File file = new File(IMAGE_UPLOAD_PATH, String.format("%d%s", eventId, FILE_EXTENSION)); //NON-NLS
    file.createNewFile();/*from   w  ww . j a  v  a2s . c om*/
    try (final BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(file), 8192)) {
        outputStream.write(image);
    }

    final String averageColor;
    final BufferedImage inputImage = ImageIO.read(file);
    final BufferedImage outputImage = ImageResizer.resizeAndCrop(inputImage, IMAGE_WIDTH, IMAGE_HEIGHT);
    ImageIO.write(outputImage, FILE_TYPE, file);
    averageColor = AverageColorCalculator.getAverageColorAsHex(outputImage);
    inputImage.flush();
    outputImage.flush();

    final Event event = eventService.findByEventId(eventId).get();
    final Event eventToUpdate = EventBuilder.fromEvent(event).withCssBackgroundColor(averageColor)
            .buildWithVersion();
    eventService.update(eventToUpdate);
}

From source file:dk.dma.msinm.web.wms.WmsProxyServlet.java

/**
 * Main GET method//w w  w .j a v a 2  s.com
 * @param request servlet request
 * @param response servlet response
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {

    // Cache for a day
    WebUtils.cache(response, CACHE_TIMEOUT);

    // Check that the WMS provider has been defined using system properties
    if (StringUtils.isBlank(wmsServiceName) || StringUtils.isBlank(wmsProvider) || StringUtils.isBlank(wmsLogin)
            || StringUtils.isBlank(wmsPassword)) {
        response.sendRedirect(BLANK_IMAGE);
        return;
    }

    @SuppressWarnings("unchecked")
    Map<String, String[]> paramMap = request.getParameterMap();
    String params = paramMap.entrySet().stream().map(p -> String.format("%s=%s", p.getKey(), p.getValue()[0]))
            .collect(Collectors.joining("&"));
    params += String.format("&SERVICENAME=%s&LOGIN=%s&PASSWORD=%s", wmsServiceName, wmsLogin, wmsPassword);

    String url = wmsProvider + "?" + params;
    log.trace("Loading image " + url);

    try {
        BufferedImage image = ImageIO.read(new URL(url));
        if (image != null) {
            image = transformWhiteToTransparent(image);

            OutputStream out = response.getOutputStream();
            ImageIO.write(image, "png", out);
            image.flush();
            out.close();
            return;
        }
    } catch (Exception e) {
        log.trace("Failed loading WMS image for URL " + url);
    }

    // Fall back to return a blank image
    response.sendRedirect(BLANK_IMAGE);
}

From source file:dk.dma.msiproxy.web.WmsProxyServlet.java

/**
 * Main GET method//from   w w w.  j  a  va 2  s  .  co m
 * @param request servlet request
 * @param response servlet response
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {

    // Cache for a day
    WebUtils.cache(response, CACHE_TIMEOUT);

    // Check that the WMS provider has been defined using system properties
    if (StringUtils.isBlank(wmsServiceName) || StringUtils.isBlank(wmsProvider) || StringUtils.isBlank(wmsLogin)
            || StringUtils.isBlank(wmsPassword)) {
        response.sendRedirect(BLANK_IMAGE);
        return;
    }

    @SuppressWarnings("unchecked")
    Map<String, String[]> paramMap = (Map<String, String[]>) request.getParameterMap();
    String params = paramMap.entrySet().stream().map(p -> String.format("%s=%s", p.getKey(), p.getValue()[0]))
            .collect(Collectors.joining("&"));
    params += String.format("&SERVICENAME=%s&LOGIN=%s&PASSWORD=%s", wmsServiceName, wmsLogin, wmsPassword);

    String url = wmsProvider + "?" + params;
    log.trace("Loading image " + url);

    try {
        BufferedImage image = ImageIO.read(new URL(url));
        if (image != null) {
            image = transformWhiteToTransparent(image);

            OutputStream out = response.getOutputStream();
            ImageIO.write(image, "png", out);
            image.flush();
            out.close();
            return;
        }
    } catch (Exception e) {
        log.trace("Failed loading WMS image for URL " + url);
    }

    // Fall back to return a blank image
    response.sendRedirect(BLANK_IMAGE);
}

From source file:com.funambol.foundation.util.MediaUtils.java

/**
 * Creates the thumbnail./*from  w w w  .j  ava 2 s .  co  m*/
 *
 * @param imageFile the image file
 * @param thumbFile the empty thumbnail file
 * @param thumbX the width of the thumbnail
 * @param thumbY the height of the thumbnail
 * @param imageName the image file name with extension
 * @param tolerance the percentage of tolerance before creating a thumbnail
 * @return true is the thumbnail has been created, false otherwise
 * @throws IOException if an error occurs
 */
private static boolean createThumbnail(File imageFile, File thumbFile, int thumbX, int thumbY, String imageName,
        double tolerance) throws IOException {

    FileInputStream fileis = null;
    ImageInputStream imageis = null;

    Iterator readers = null;

    try {

        readers = ImageIO.getImageReadersByFormatName(imageName.substring(imageName.lastIndexOf('.') + 1));
        if (readers == null || (!readers.hasNext())) {
            throw new IOException("File not supported");
        }

        ImageReader reader = (ImageReader) readers.next();

        fileis = new FileInputStream(imageFile);
        imageis = ImageIO.createImageInputStream(fileis);
        reader.setInput(imageis, true);

        // Determines thumbnail height, width and quality
        int thumbWidth = thumbX;
        int thumbHeight = thumbY;

        double thumbRatio = (double) thumbWidth / (double) thumbHeight;
        int imageWidth = reader.getWidth(0);
        int imageHeight = reader.getHeight(0);

        //
        // Don't create the thumbnail if the original file is smaller
        // than required size increased by % tolerance
        //
        if (imageWidth <= (thumbWidth * (1 + tolerance / 100))
                && imageHeight <= (thumbHeight * (1 + tolerance / 100))) {

            return false;
        }

        double imageRatio = (double) imageWidth / (double) imageHeight;
        if (thumbRatio < imageRatio) {
            thumbHeight = (int) (thumbWidth / imageRatio);
        } else {
            thumbWidth = (int) (thumbHeight * imageRatio);
        }

        ImageReadParam param = reader.getDefaultReadParam();
        param.setSourceSubsampling(3, 3, 0, 0);

        BufferedImage bi = reader.read(0, param);

        Image thumb = bi.getScaledInstance(thumbWidth, thumbHeight, Image.SCALE_SMOOTH);

        BufferedImage thumbImage = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB);
        Graphics2D graphics2D = thumbImage.createGraphics();
        graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        graphics2D.drawImage(thumb, 0, 0, thumbWidth, thumbHeight, null);

        FileOutputStream fileOutputStream = new FileOutputStream(thumbFile);
        ImageIO.write(thumbImage, "jpg", fileOutputStream);

        thumb.flush();
        thumbImage.flush();
        fileOutputStream.flush();
        fileOutputStream.close();
        graphics2D.dispose();

    } finally {
        if (fileis != null) {
            fileis.close();
        }
        if (imageis != null) {
            imageis.close();
        }
    }

    return true;
}

From source file:dk.dma.msinm.web.wms.WmsProxyServlet.java

/**
 * Masks out white colour/*  ww  w  .java  2  s  . c  o m*/
 * @param image the image to mask out
 * @return the resulting image
 */
private BufferedImage transformWhiteToTransparent(BufferedImage image) {

    BufferedImage dest = image;
    if (image.getType() != BufferedImage.TYPE_INT_ARGB) {
        dest = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2 = dest.createGraphics();
        g2.drawImage(image, 0, 0, null);
        g2.dispose();

        image.flush();
    }

    // Mask out the white pixels
    final int width = image.getWidth();
    int[] imgData = new int[width];

    for (int y = 0; y < dest.getHeight(); y++) {
        // fetch a line of data from each image
        dest.getRGB(0, y, width, 1, imgData, 0, 1);
        // apply the mask
        for (int x = 0; x < width; x++) {
            for (Color col : MASKED_COLORS) {
                int colDist = Math.abs(col.getRed() - (imgData[x] >> 16 & 0x000000FF))
                        + Math.abs(col.getGreen() - (imgData[x] >> 8 & 0x000000FF))
                        + Math.abs(col.getBlue() - (imgData[x] & 0x000000FF));
                if (colDist <= COLOR_DIST) {
                    imgData[x] = 0x00FFFFFF & imgData[x];
                }
            }
        }
        // replace the data
        dest.setRGB(0, y, width, 1, imgData, 0, 1);
    }
    return dest;
}

From source file:de.inren.service.picture.PictureModificationServiceImpl.java

private BufferedImage scaleImage(File orginal, final int max) throws IOException {
    // Load the image.
    BufferedImage originalImage = ImageIO.read(orginal);

    // Figure out the new dimensions.
    final int w = originalImage.getWidth();
    final int h = originalImage.getHeight();
    final double maxOriginal = Math.max(w, h);
    final double scaling = max / maxOriginal;

    final int newW = (int) Math.round(scaling * w);
    final int newH = (int) Math.round(scaling * h);

    // If we need to scale down by more than 2x, scale to double the
    // eventual size and then scale again. This provides much higher
    // quality results.
    if (scaling < 0.5f) {
        final BufferedImage newImg = new BufferedImage(newW * 2, newH * 2, BufferedImage.TYPE_INT_RGB);
        final Graphics2D gfx = newImg.createGraphics();
        gfx.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        gfx.drawImage(originalImage, 0, 0, newW * 2, newH * 2, null);
        gfx.dispose();//from   w ww.  j av a2  s  . c om
        newImg.flush();
        originalImage = newImg;
    }

    // Scale it.
    BufferedImage newImg = new BufferedImage(newW, newH, BufferedImage.TYPE_INT_RGB);
    final Graphics2D gfx = newImg.createGraphics();
    gfx.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
    gfx.drawImage(originalImage, 0, 0, newW, newH, null);
    gfx.dispose();
    newImg.flush();
    originalImage.flush();

    return newImg;
}

From source file:net.filterlogic.util.imaging.ToTIFF.java

/**
 * //w  w  w .  j a v  a  2  s .c  o m
 * @param fileName
 */
public void test6(String fileName) {
    try {
        File f = new File(fileName);

        ImageInputStream imageInputStream = ImageIO.createImageInputStream(f);
        java.util.Iterator readers = ImageIO.getImageReaders(imageInputStream);
        ImageReader reader1 = (ImageReader) readers.next();
        ImageInputStream iis = ImageIO.createImageInputStream(new FileInputStream(f));
        reader1.setInput(iis);

        int number = reader1.getNumImages(true);
        Iterator writers = ImageIO.getImageWritersByFormatName("tiff");
        ImageWriter writer = (ImageWriter) writers.next();

        ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
        ImageOutputStream ios = null;
        BufferedImage img = null;

        for (int i = 0; i < number; i++) {
            img = reader1.read(i);
            ios = ImageIO.createImageOutputStream(byteOut);
            writer.setOutput(ios);
            writer.write(img);
            ios.flush();
            img.flush();
            byteOut.flush();
        }

    } catch (Exception e) {
        System.out.println(e.toString());
    }

}

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);
                }/* w  w w  . j ava  2 s  .  c o m*/
            }
        }
    }

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

    return buffer.toByteArray();
}

From source file:codes.thischwa.c5c.impl.LocalConnector.java

@Override
public StreamContent resize(InputStream imageIn, String imageExt, Dimension dim) throws IOException {
    BufferedImage img = null;
    BufferedImage newImg = null;//from  w w  w  .  ja v  a  2s  .c  o  m
    try {
        img = ImageIO.read(imageIn);
        newImg = Scalr.resize(img, Scalr.Method.BALANCED, Scalr.Mode.AUTOMATIC, dim.width, dim.height);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(newImg, imageExt, baos);
        baos.flush();
        return buildStreamContent(new ByteArrayInputStream(baos.toByteArray()), baos.size());
    } catch (IllegalArgumentException | ImagingOpException e) {
        throw new IOException(e);
    } finally {
        if (img != null)
            img.flush();
        if (newImg != null)
            newImg.flush();
    }
}

From source file:net.filterlogic.util.imaging.ToTIFF.java

/**
 * Convert multipage TIFF to single page TIFF.
 * @param srcFiles Array of source files to convert.
 * @param destPath Folder to store single page TIFFs in.
 * @param archivePath Path to move source TIFF files to after single page TIFFs created.
 * @param pattern Pattern of single page TIFF file names.  Java NumberFormatter used with page number to create file name.
 * @param multipage Set to true if source TIFFs should be coverted to multi-page TIFF.
 * @param dpi DPI to set TIFFs to./*from   w  w  w  .  ja  v  a 2s .  c  om*/
 * @return Returns a list of files in destination path.
 * @throws net.filterlogic.util.imaging.OpenCaptureImagingException
 */
public static List toTIFF(String[] srcFiles, String destPath, String archivePath, String pattern,
        boolean multipage, int dpi) throws OpenCaptureImagingException {
    String pathSep = System.getProperty("file.separator");
    boolean jaiSupport = true;

    int pageCount = 0;
    int fileNameCount = 0;

    byte[] imageData = null;

    // make sure destpath has trailing slash.
    if (destPath.lastIndexOf(pathSep) != destPath.length() - 1)
        destPath += pathSep;

    // create path if doesn't exist
    if (!Path.ValidatePath(destPath))
        if (!Path.createPath(destPath))
            throw new OpenCaptureImagingException(
                    "Unable to create destination path for imported images [" + destPath + "]");

    // make sure archivePath has trailing slash
    if (archivePath.lastIndexOf(pathSep) != archivePath.length() - 1)
        archivePath += pathSep;

    if (!Path.ValidatePath(archivePath))
        if (!Path.createPath(archivePath))
            throw new OpenCaptureImagingException(
                    "Unable to create archive path for imported images [" + archivePath + "]");

    // set a default pattern if one not passed.
    if (pattern.trim().length() < 1)
        pattern = "#";

    NumberFormat formatter = new DecimalFormat(pattern);

    ArrayList<String> list = new ArrayList<String>();

    for (int i = 0; i < srcFiles.length; i++) {
        try {

            File f = new File(srcFiles[i]);
            imageData = null;

            ImageIO.setUseCache(false);
            ImageInputStream imageInputStream = ImageIO.createImageInputStream(f);
            java.util.Iterator readers = ImageIO.getImageReaders(imageInputStream);

            ImageReader reader1 = null;

            if (readers.hasNext()) {
                reader1 = (ImageReader) readers.next();
                jaiSupport = true;
            } else
                jaiSupport = false;

            if (jaiSupport) {
                //ImageInputStream iis = ImageIO.createImageInputStream(new FileInputStream(f));
                reader1.setInput(imageInputStream);

                pageCount = reader1.getNumImages(true);
            } else {
                String newFileName = bigEndian2LittleEndian(f.getAbsolutePath());

                if (imageInputStream != null) {
                    imageInputStream.flush();
                    imageInputStream.close();

                    reader1.setInput(imageInputStream);
                    pageCount = reader1.getNumImages(true);

                }

                imageInputStream = ImageIO.createImageInputStream(new File(newFileName));

                readers = ImageIO.getImageReaders(imageInputStream);

            }
            //                Iterator writers = ImageIO.getImageWritersByFormatName("tiff");
            //                ImageWriter writer = (ImageWriter)writers.next();

            //ImageWriteParam param = writer.getDefaultWriteParam();

            //param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);

            //String[] legalTypes = param.getCompressionTypes();

            //param.setCompressionType("PackBits");

            //ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
            ImageOutputStream ios = null;
            BufferedImage img = null;

            // break out each page to single file
            for (int t = 0; t < pageCount; t++) {

                // format filenumber
                String tifName = destPath + formatter.format(fileNameCount) + ".tif";

                while (new File(tifName).exists()) {
                    tifName = destPath + formatter.format(++fileNameCount) + ".tif";
                }

                FileOutputStream file = new FileOutputStream(new File(tifName));

                if (jaiSupport) {
                    img = reader1.read(t);
                    IIOImage iioimg = reader1.readAll(t, null);
                    //ios = ImageIO.createImageOutputStream(file);
                    //IIOMetadata iiom = getMetadata(writer, img, null, 200);
                } else {
                    img = loadTIFF(imageData, t);
                }
                TIFFEncodeParam tep = setEncoder(TIFFEncodeParam.COMPRESSION_PACKBITS, 200);

                ImageEncoder encoder = ImageCodec.createImageEncoder("TIFF", file, tep);

                encoder.encode(img);
                //boolean ok = ImageIO.write(img, "tiff", ios);
                //writer.setOutput(ios);
                //writer.write(iiom, iioimg, null);

                img.flush();

                //ios.flush();
                //ios.close();
                // ios = null;
                //iioimg = null;
                //iiom = null;
                img = null;
                //writer.dispose();
                //byteOut.flush();
                file.close();

                file = null;

                //System.out.println("Add file!");

                list.add(tifName);
            }

            if (jaiSupport) {
                reader1.dispose();
            }

            readers = null;

            //                writer.dispose();
            //                writers = null;

            imageInputStream.flush();
            imageInputStream.close();
            imageInputStream = null;

            f = null;

            // move file with overwrite
            if (!net.filterlogic.io.FileAccess.Move(srcFiles[i], archivePath, true))
                throw new Exception("Unable to move input file to archive path [" + srcFiles[i] + "] to ["
                        + archivePath + "]");

        } catch (Exception e) {
            throw new OpenCaptureImagingException(e.toString());
        }
    }

    return list;
}