Example usage for javax.imageio ImageIO write

List of usage examples for javax.imageio ImageIO write

Introduction

In this page you can find the example usage for javax.imageio ImageIO write.

Prototype

public static boolean write(RenderedImage im, String formatName, OutputStream output) throws IOException 

Source Link

Document

Writes an image using an arbitrary ImageWriter that supports the given format to an OutputStream .

Usage

From source file:ddf.catalog.transformer.OverlayMetacardTransformer.java

private BinaryContent createBinaryContent(BufferedImage image) throws CatalogTransformerException {
    try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
        ImageIO.write(image, PNG, baos);
        return new BinaryContentImpl(new ByteArrayInputStream(baos.toByteArray()), MIME_TYPE);
    } catch (IOException e) {
        throw new CatalogTransformerException(e);
    }// www .  j a v a2 s .  com
}

From source file:org.drools.planner.benchmark.core.statistic.memoryuse.MemoryUseProblemStatistic.java

protected void writeGraphStatistic() {
    XYSeriesCollection seriesCollection = new XYSeriesCollection();
    for (SingleBenchmark singleBenchmark : problemBenchmark.getSingleBenchmarkList()) {
        MemoryUseSingleStatistic singleStatistic = (MemoryUseSingleStatistic) singleBenchmark
                .getSingleStatistic(problemStatisticType);
        XYSeries usedSeries = new XYSeries(singleBenchmark.getSolverBenchmark().getName() + " used");
        XYSeries maxSeries = new XYSeries(singleBenchmark.getSolverBenchmark().getName() + " max");
        for (MemoryUseSingleStatisticPoint point : singleStatistic.getPointList()) {
            long timeMillisSpend = point.getTimeMillisSpend();
            MemoryUseMeasurement memoryUseMeasurement = point.getMemoryUseMeasurement();
            usedSeries.add(timeMillisSpend, memoryUseMeasurement.getUsedMemory());
            maxSeries.add(timeMillisSpend, memoryUseMeasurement.getMaxMemory());
        }//from  w  w w  .j  ava2  s .  c o  m
        seriesCollection.addSeries(usedSeries);
        seriesCollection.addSeries(maxSeries);
    }
    NumberAxis xAxis = new NumberAxis("Time spend");
    xAxis.setNumberFormatOverride(new MillisecondsSpendNumberFormat());
    NumberAxis yAxis = new NumberAxis("Memory");
    yAxis.setAutoRangeIncludesZero(false);
    XYItemRenderer renderer = new XYAreaRenderer2();
    XYPlot plot = new XYPlot(seriesCollection, xAxis, yAxis, renderer);
    plot.setOrientation(PlotOrientation.VERTICAL);
    JFreeChart chart = new JFreeChart(problemBenchmark.getName() + " memory use statistic",
            JFreeChart.DEFAULT_TITLE_FONT, plot, true);
    BufferedImage chartImage = chart.createBufferedImage(1024, 768);
    graphStatisticFile = new File(problemBenchmark.getProblemReportDirectory(),
            problemBenchmark.getName() + "MemoryUseStatistic.png");
    OutputStream out = null;
    try {
        out = new FileOutputStream(graphStatisticFile);
        ImageIO.write(chartImage, "png", out);
    } catch (IOException e) {
        throw new IllegalArgumentException("Problem writing graphStatisticFile: " + graphStatisticFile, e);
    } finally {
        IOUtils.closeQuietly(out);
    }
}

From source file:com.cognifide.aet.job.common.comparators.layout.utils.ImageComparisonTest.java

private InputStream imageToStream(BufferedImage image) throws IOException {
    ByteArrayOutputStream imageStream = new ByteArrayOutputStream();
    try {//from   w w w.  j  a v a2  s . c o m
        ImageIO.write(image, "png", imageStream);
        return new ByteArrayInputStream(imageStream.toByteArray());
    } finally {
        IOUtils.closeQuietly(imageStream);
    }
}

From source file:com.cognifide.aet.job.common.collectors.screen.ScreenCollector.java

private byte[] bufferedImageToByteArray(BufferedImage bufferedImage) throws ProcessingException {
    try (ByteArrayOutputStream temporaryStream = new ByteArrayOutputStream()) {
        ImageIO.write(bufferedImage, PNG_FORMAT, temporaryStream);
        temporaryStream.flush();//ww w  .j  a  va 2  s.co  m
        return temporaryStream.toByteArray();
    } catch (IOException e) {
        throw new ProcessingException("Unable to convert screenshot part to byte Array", e);
    }
}

From source file:itemrender.client.rendering.FBOHelper.java

public String getBase64() {
    // Bind framebuffer texture
    GlStateManager.bindTexture(textureID);

    GL11.glPixelStorei(GL11.GL_PACK_ALIGNMENT, 1);
    GL11.glPixelStorei(GL11.GL_UNPACK_ALIGNMENT, 1);

    int width = GL11.glGetTexLevelParameteri(GL11.GL_TEXTURE_2D, 0, GL11.GL_TEXTURE_WIDTH);
    int height = GL11.glGetTexLevelParameteri(GL11.GL_TEXTURE_2D, 0, GL11.GL_TEXTURE_HEIGHT);

    IntBuffer texture = BufferUtils.createIntBuffer(width * height);
    GL11.glGetTexImage(GL11.GL_TEXTURE_2D, 0, GL12.GL_BGRA, GL12.GL_UNSIGNED_INT_8_8_8_8_REV, texture);

    int[] texture_array = new int[width * height];
    texture.get(texture_array);//w w  w. j  a va  2 s.  c  o m

    BufferedImage image = new BufferedImage(renderTextureSize, renderTextureSize, BufferedImage.TYPE_INT_ARGB);
    image.setRGB(0, 0, renderTextureSize, renderTextureSize, texture_array, 0, width);

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {
        ImageIO.write(image, "PNG", out);
    } catch (IOException e) {
        // Do nothing
    }

    return Base64.encodeBase64String(out.toByteArray());
}

From source file:kihira.tails.client.gui.GuiExport.java

@Override
protected void actionPerformed(GuiButton button) {
    //Export to file
    if (button.id == 0 || button.id == 1 || button.id == 2) {
        AbstractClientPlayer player = this.mc.thePlayer;
        File file;/*  w  w w .  j  a  v a2s.co m*/

        this.exportMessage = "";
        this.exportLoc = null;
        if (button.id == 0)
            file = new File(System.getProperty("user.home"));
        else if (button.id == 1)
            file = new File(System.getProperty("user.dir"));
        else {
            JFileChooser fileChooser = new JFileChooser(new File(System.getProperty("user.dir")));
            fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            if (fileChooser.showSaveDialog(Display.getParent()) == JFileChooser.APPROVE_OPTION) {
                file = fileChooser.getSelectedFile();
            } else
                return;
        }

        if (file.exists() && file.canWrite()) {
            this.exportLoc = file.toURI();
            file = new File(file, File.separatorChar + player.getCommandSenderName() + ".png");

            if (!file.exists()) {
                try {
                    file.createNewFile();
                } catch (IOException e) {
                    setExportMessage(
                            EnumChatFormatting.DARK_RED + String.format("Failed to create skin file! %s", e));
                    e.printStackTrace();
                }
            }

            BufferedImage image = TextureHelper.writePartsDataToSkin(this.partsData, player);
            if (image != null) {
                try {
                    ImageIO.write(image, "png", file);
                } catch (IOException e) {
                    setExportMessage(
                            EnumChatFormatting.DARK_RED + String.format("Failed to save skin file! %s", e));
                    e.printStackTrace();
                }
            } else {
                setExportMessage(
                        EnumChatFormatting.DARK_RED + String.format("Failed to export skin, image was null!"));
                file.delete();
            }
        }

        if (Strings.isNullOrEmpty(this.exportMessage)) {
            savePartsData();
            this.openFolderButton.visible = true;
            setExportMessage(EnumChatFormatting.GREEN + I18n.format("tails.export.success", file));
        }
    }
    if (button.id == 3 && this.exportLoc != null) {
        try {
            Desktop.getDesktop().browse(this.exportLoc);
        } catch (IOException e) {
            setExportMessage(
                    EnumChatFormatting.DARK_RED + String.format("Failed to open export location: %s", e));
            e.printStackTrace();
        }
    }

    //Upload
    if (button.id == 10) {
        final BufferedImage image = TextureHelper.writePartsDataToSkin(this.partsData, this.mc.thePlayer);
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                exportMessage = I18n.format("tails.uploading");
                new ImgurUpload().uploadImage(image);
            }
        };
        runnable.run();
    }
}

From source file:com.frochr123.fabqr.FabQRFunctions.java

public static void uploadFabQRProject(String name, String email, String projectName, int licenseIndex,
        String tools, String description, String location, BufferedImage imageReal, BufferedImage imageScheme,
        PlfFile plfFile, String lasercutterName, String lasercutterMaterial) throws Exception {
    // Check for valid situation, otherwise abort
    if (MainView.getInstance() == null || VisicutModel.getInstance() == null
            || VisicutModel.getInstance().getPlfFile() == null || !isFabqrActive()
            || getFabqrPrivateURL() == null || getFabqrPrivateURL().isEmpty()
            || MaterialManager.getInstance() == null || MappingManager.getInstance() == null
            || VisicutModel.getInstance().getSelectedLaserDevice() == null) {
        throw new Exception("FabQR upload exception: Critical error");
    }//  w  w  w  .  j a v a  2  s.  c  om

    // Check valid data
    if (name == null || email == null || projectName == null || projectName.length() < 3 || licenseIndex < 0
            || tools == null || tools.isEmpty() || description == null || description.isEmpty()
            || location == null || location.isEmpty() || imageScheme == null || plfFile == null
            || lasercutterName == null || lasercutterName.isEmpty() || lasercutterMaterial == null
            || lasercutterMaterial.isEmpty()) {
        throw new Exception("FabQR upload exception: Invalid input data");
    }

    // Convert images to byte data for PNG, imageReal is allowed to be empty
    byte[] imageSchemeBytes = null;
    ByteArrayOutputStream imageSchemeOutputStream = new ByteArrayOutputStream();
    PreviewImageExport.writePngToOutputStream(imageSchemeOutputStream, imageScheme);
    imageSchemeBytes = imageSchemeOutputStream.toByteArray();

    if (imageSchemeBytes == null) {
        throw new Exception("FabQR upload exception: Error converting scheme image");
    }

    byte[] imageRealBytes = null;

    if (imageReal != null) {
        // Need to convert image, ImageIO.write messes up the color space of the original input image
        BufferedImage convertedImage = new BufferedImage(imageReal.getWidth(), imageReal.getHeight(),
                BufferedImage.TYPE_3BYTE_BGR);
        ColorConvertOp op = new ColorConvertOp(null);
        op.filter(imageReal, convertedImage);

        ByteArrayOutputStream imageRealOutputStream = new ByteArrayOutputStream();
        ImageIO.write(convertedImage, "jpg", imageRealOutputStream);
        imageRealBytes = imageRealOutputStream.toByteArray();
    }

    // Extract all URLs from used QR codes
    List<String> referencesList = new LinkedList<String>();
    List<PlfPart> plfParts = plfFile.getPartsCopy();

    for (PlfPart plfPart : plfParts) {
        if (plfPart.getQRCodeInfo() != null && plfPart.getQRCodeInfo().getQRCodeSourceURL() != null
                && !plfPart.getQRCodeInfo().getQRCodeSourceURL().trim().isEmpty()) {
            // Process url, if it is URL of a FabQR system, remove download flag and point to project page instead
            // Use regex to check for FabQR system URL structure
            String qrCodeUrl = plfPart.getQRCodeInfo().getQRCodeSourceURL().trim();

            // Check for temporary URL structure of FabQR system
            Pattern fabQRUrlTemporaryPattern = Pattern
                    .compile("^https{0,1}://.*?" + "/" + FABQR_TEMPORARY_MARKER + "/" + "([a-z]|[0-9]){7,7}$");

            // Do not include link if it is just temporary
            if (fabQRUrlTemporaryPattern.matcher(qrCodeUrl).find()) {
                continue;
            }

            // Check for download URL structure of FabQR system
            // Change URL to point to project page instead
            Pattern fabQRUrlDownloadPattern = Pattern
                    .compile("^https{0,1}://.*?" + "/" + FABQR_DOWNLOAD_MARKER + "/" + "([a-z]|[0-9]){7,7}$");

            if (fabQRUrlDownloadPattern.matcher(qrCodeUrl).find()) {
                qrCodeUrl = qrCodeUrl.replace("/" + FABQR_DOWNLOAD_MARKER + "/", "/");
            }

            // Add URL if it is not yet in list
            if (!referencesList.contains(qrCodeUrl)) {
                referencesList.add(qrCodeUrl);
            }
        }
    }

    String references = "";

    for (String ref : referencesList) {
        // Add comma for non first entries
        if (!references.isEmpty()) {
            references = references + ",";
        }

        references = references + ref;
    }

    // Get bytes for PLF file
    byte[] plfFileBytes = null;
    ByteArrayOutputStream plfFileOutputStream = new ByteArrayOutputStream();
    VisicutModel.getInstance().savePlfToStream(MaterialManager.getInstance(), MappingManager.getInstance(),
            plfFileOutputStream);
    plfFileBytes = plfFileOutputStream.toByteArray();

    if (plfFileBytes == null) {
        throw new Exception("FabQR upload exception: Error saving PLF file");
    }

    // Begin uploading data
    String uploadUrl = getFabqrPrivateURL() + FABQR_API_UPLOAD_PROJECT;

    // Create HTTP client and cusomized config for timeouts
    CloseableHttpClient httpClient = HttpClients.createDefault();
    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(FABQR_UPLOAD_TIMEOUT)
            .setConnectTimeout(FABQR_UPLOAD_TIMEOUT).setConnectionRequestTimeout(FABQR_UPLOAD_TIMEOUT).build();

    // Create HTTP Post request and entity builder
    HttpPost httpPost = new HttpPost(uploadUrl);
    httpPost.setConfig(requestConfig);
    MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();

    // Insert file uploads
    multipartEntityBuilder.addBinaryBody("imageScheme", imageSchemeBytes, ContentType.APPLICATION_OCTET_STREAM,
            "imageScheme.png");
    multipartEntityBuilder.addBinaryBody("inputFile", plfFileBytes, ContentType.APPLICATION_OCTET_STREAM,
            "inputFile.plf");

    // Image real is allowed to be null, if it is not, send it
    if (imageRealBytes != null) {
        multipartEntityBuilder.addBinaryBody("imageReal", imageRealBytes, ContentType.APPLICATION_OCTET_STREAM,
                "imageReal.png");
    }

    // Prepare content type for text data, especially needed for correct UTF8 encoding
    ContentType contentType = ContentType.create("text/plain", Consts.UTF_8);

    // Insert text data
    multipartEntityBuilder.addTextBody("name", name, contentType);
    multipartEntityBuilder.addTextBody("email", email, contentType);
    multipartEntityBuilder.addTextBody("projectName", projectName, contentType);
    multipartEntityBuilder.addTextBody("licenseIndex", new Integer(licenseIndex).toString(), contentType);
    multipartEntityBuilder.addTextBody("tools", tools, contentType);
    multipartEntityBuilder.addTextBody("description", description, contentType);
    multipartEntityBuilder.addTextBody("location", location, contentType);
    multipartEntityBuilder.addTextBody("lasercutterName", lasercutterName, contentType);
    multipartEntityBuilder.addTextBody("lasercutterMaterial", lasercutterMaterial, contentType);
    multipartEntityBuilder.addTextBody("references", references, contentType);

    // Assign entity to this post request
    HttpEntity httpEntity = multipartEntityBuilder.build();
    httpPost.setEntity(httpEntity);

    // Set authentication information
    String encodedCredentials = Helper.getEncodedCredentials(FabQRFunctions.getFabqrPrivateUser(),
            FabQRFunctions.getFabqrPrivatePassword());
    if (!encodedCredentials.isEmpty()) {
        httpPost.addHeader("Authorization", "Basic " + encodedCredentials);
    }

    // Send request
    CloseableHttpResponse res = httpClient.execute(httpPost);

    // React to possible server side errors
    if (res.getStatusLine() == null || res.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
        throw new Exception("FabQR upload exception: Server sent wrong HTTP status code: "
                + new Integer(res.getStatusLine().getStatusCode()).toString());
    }

    // Close everything correctly
    res.close();
    httpClient.close();
}

From source file:com.krawler.esp.handlers.FileUploadHandler.java

public final void imgResize(String sourcePath, int Width, int Height, String destPath, boolean isCompany,
        boolean ori) throws IOException {
    try {/*w  w w  . j  av a 2s  .c o  m*/
        String ext = getImageExt();
        String type = "jpeg";
        int typeRGB = BufferedImage.TYPE_INT_RGB;
        Image sourceImage = new ImageIcon(Toolkit.getDefaultToolkit().getImage(sourcePath)).getImage();
        if (isCompany) {
            ext = getCompanyImageExt();
            type = "PNG";
            typeRGB = BufferedImage.TYPE_INT_ARGB;
            int imageWidth = sourceImage.getWidth(null);
            int imageHeight = sourceImage.getHeight(null);
            if (ori) {
                Width = imageWidth;
                Height = imageHeight;
            } else {
                Width = imageWidth < Width ? imageWidth : Width;
                Height = imageHeight < Height ? imageHeight : Height;
                float imageRatio = ((float) imageWidth / (float) imageHeight);
                float framemageratio = ((float) Width / (float) Height);
                if (imageRatio > framemageratio) {
                    float value = Width / imageRatio;
                    Height = (int) value;

                } else {
                    float value = Height * imageRatio;
                    Width = (int) value;
                }
            }
        }

        BufferedImage resizedImage = this.scaleImage(sourceImage, Width, Height, typeRGB);
        ImageIO.write(resizedImage, type, new File(destPath + ext));
    } catch (Exception e) {
        Logger.getInstance(FileUploadHandler.class).error(e, e);
    }
}

From source file:com.liusoft.dlog4j.util.ImageUtils.java

/**
 * ???/*from w  ww . j  a v a2s  . c  o m*/
 * ?????
 * 3: 180
 * 6: 90
 * 8: 27090
 * @param img_fn
 * @param orient
 * @throws IOException 
 */
public static boolean rotateImage(String img_fn, int orient, String dest_fn) throws IOException {
    double radian = 0;
    switch (orient) {
    case 3:
        radian = 180.0;
        break;
    case 6:
        radian = 90.0;
        break;
    case 8:
        radian = 270.0;
        break;
    default:
        return false;
    }
    BufferedImage old_img = (BufferedImage) ImageIO.read(new File(img_fn));
    int width = old_img.getWidth();
    int height = old_img.getHeight();

    BufferedImage new_img = new BufferedImage(height, width, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2d = new_img.createGraphics();

    AffineTransform origXform = g2d.getTransform();
    AffineTransform newXform = (AffineTransform) (origXform.clone());
    // center of rotation is center of the panel
    double xRot = 0;
    double yRot = 0;
    switch (orient) {
    case 3:
        xRot = width / 2.0;
        yRot = height / 2.0;
    case 6:
        xRot = height / 2.0;
        yRot = xRot;
        break;
    case 8:
        xRot = width / 2.0;
        yRot = xRot;
        break;
    default:
        return false;
    }
    newXform.rotate(Math.toRadians(radian), xRot, yRot);

    g2d.setTransform(newXform);
    // draw image centered in panel
    g2d.drawImage(old_img, 0, 0, null);
    // Reset to Original
    g2d.setTransform(origXform);

    FileOutputStream out = new FileOutputStream(dest_fn);
    try {
        ImageIO.write(new_img, "JPG", out);
    } finally {
        out.close();
    }
    return true;
}

From source file:net.mindengine.galen.utils.GalenUtils.java

public static File makeFullScreenshot(WebDriver driver) throws IOException, InterruptedException {
    // scroll up first
    scrollVerticallyTo(driver, 0);/*from  w w w . ja  va2s.c o  m*/
    byte[] bytes = ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES);
    BufferedImage image = ImageIO.read(new ByteArrayInputStream(bytes));
    int capturedWidth = image.getWidth();
    int capturedHeight = image.getHeight();

    long longScrollHeight = (Long) ((JavascriptExecutor) driver).executeScript(
            "return Math.max(" + "document.body.scrollHeight, document.documentElement.scrollHeight,"
                    + "document.body.offsetHeight, document.documentElement.offsetHeight,"
                    + "document.body.clientHeight, document.documentElement.clientHeight);");

    Double devicePixelRatio = ((Number) ((JavascriptExecutor) driver)
            .executeScript(JS_RETRIEVE_DEVICE_PIXEL_RATIO)).doubleValue();

    int scrollHeight = (int) longScrollHeight;

    File file = File.createTempFile("screenshot", ".png");

    int adaptedCapturedHeight = (int) (((double) capturedHeight) / devicePixelRatio);

    BufferedImage resultingImage;

    if (Math.abs(adaptedCapturedHeight - scrollHeight) > 40) {
        int scrollOffset = adaptedCapturedHeight;

        int times = scrollHeight / adaptedCapturedHeight;
        int leftover = scrollHeight % adaptedCapturedHeight;

        final BufferedImage tiledImage = new BufferedImage(capturedWidth,
                (int) (((double) scrollHeight) * devicePixelRatio), BufferedImage.TYPE_INT_RGB);
        Graphics2D g2dTile = tiledImage.createGraphics();
        g2dTile.drawImage(image, 0, 0, null);

        int scroll = 0;
        for (int i = 0; i < times - 1; i++) {
            scroll += scrollOffset;
            scrollVerticallyTo(driver, scroll);
            BufferedImage nextImage = ImageIO.read(
                    new ByteArrayInputStream(((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES)));
            g2dTile.drawImage(nextImage, 0, (i + 1) * capturedHeight, null);
        }
        if (leftover > 0) {
            scroll += scrollOffset;
            scrollVerticallyTo(driver, scroll);
            BufferedImage nextImage = ImageIO.read(
                    new ByteArrayInputStream(((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES)));
            BufferedImage lastPart = nextImage.getSubimage(0,
                    nextImage.getHeight() - (int) (((double) leftover) * devicePixelRatio),
                    nextImage.getWidth(), leftover);
            g2dTile.drawImage(lastPart, 0, times * capturedHeight, null);
        }

        scrollVerticallyTo(driver, 0);

        resultingImage = tiledImage;
    } else {
        resultingImage = image;
    }

    if (GalenConfig.getConfig().shouldAutoresizeScreenshots()) {
        resultingImage = GalenUtils.resizeScreenshotIfNeeded(driver, resultingImage);
    }

    ImageIO.write(resultingImage, "png", file);
    return file;
}