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:com.esofthead.mycollab.mobile.module.project.ui.ProjectCommentInputView.java

private void saveContentsToRepo(String attachmentPath) {
    if (MapUtils.isNotEmpty(fileStores)) {
        for (Map.Entry<String, File> entry : fileStores.entrySet()) {
            try {
                String fileName = entry.getKey();
                File file = entry.getValue();
                String fileExt = "";
                int index = fileName.lastIndexOf(".");
                if (index > 0) {
                    fileExt = fileName.substring(index + 1, fileName.length());
                }//from   www  .  ja  v  a 2s.  c  om

                if ("jpg".equalsIgnoreCase(fileExt) || "png".equalsIgnoreCase(fileExt)) {
                    try {
                        BufferedImage bufferedImage = ImageIO.read(file);
                        int imgHeight = bufferedImage.getHeight();
                        int imgWidth = bufferedImage.getWidth();

                        BufferedImage scaledImage;

                        float scale;
                        float destWidth = 974;
                        float destHeight = 718;

                        float scaleX = Math.min(destHeight / imgHeight, 1);
                        float scaleY = Math.min(destWidth / imgWidth, 1);
                        scale = Math.min(scaleX, scaleY);
                        scaledImage = ImageUtil.scaleImage(bufferedImage, scale);

                        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
                        ImageIO.write(scaledImage, fileExt, outStream);

                        resourceService.saveContent(
                                MobileAttachmentUtils.constructContent(fileName, attachmentPath),
                                AppContext.getUsername(), new ByteArrayInputStream(outStream.toByteArray()),
                                AppContext.getAccountId());
                    } catch (IOException e) {
                        LOG.error("Error in upload file", e);
                        resourceService.saveContent(
                                MobileAttachmentUtils.constructContent(fileName, attachmentPath),
                                AppContext.getUsername(), new FileInputStream(file), AppContext.getAccountId());
                    }
                } else {
                    resourceService.saveContent(
                            MobileAttachmentUtils.constructContent(fileName, attachmentPath),
                            AppContext.getUsername(), new FileInputStream(file), AppContext.getAccountId());
                }

            } catch (FileNotFoundException e) {
                LOG.error("Error when attach content in UI", e);
            }
        }
    }
}

From source file:com.amour.imagecrawler.ImagesManager.java

private void saveFileToDisk(String imageUrl, String destinationFileDir, Images imagedetails,
        BufferedImage imBuff) throws IOException {
    String fileName = FilenameUtils.getName(imageUrl);
    /* Path path = Paths.get(imageUrl);
     String fileName = path.getFileName().toString();*/
    String destinationFile = IO_Utils.pathCombine(destinationFileDir, fileName);
    imagedetails.setImageondisk(destinationFile.getBytes());
    File outputfile = new File(destinationFile);
    ImageIO.write(imBuff, IO_Utils.getFileExtension(outputfile), outputfile);
}

From source file:org.n52.io.PreRenderingTask.java

public void writePrerenderedGraphToOutputStream(String timeseriesId, String interval,
        ServletOutputStream outputStream) {
    try {/*www  . ja v a2 s .c  o  m*/
        BufferedImage image = loadImage(timeseriesId, interval);
        if (image == null) {
            ResourceNotFoundException ex = new ResourceNotFoundException("Could not find image on server.");
            ex.addHint("Perhaps the image is being rendered at the moment. Try again later.");
            throw ex;
        }
        ImageIO.write(image, "png", outputStream);
    } catch (IOException e) {
        LOGGER.error("Error while loading pre rendered image", e);
    }
}

From source file:com.mirth.connect.server.util.DICOMMessageUtil.java

public static byte[] convertDICOMToByteArray(String imageType, ImmutableConnectorMessage message,
        int sliceIndex, boolean autoThreshold) {
    if (imageType.equalsIgnoreCase("jpg") || imageType.equalsIgnoreCase("jpeg")) {
        return dicomToJpg(sliceIndex, message, autoThreshold);
    }/*from w ww.  jav  a 2  s .c o  m*/

    ByteArrayInputStream bais = new ByteArrayInputStream(getDICOMRawBytes(message));
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    try {
        DICOM dicom = new DICOM(bais);
        // run() is required to create the dicom object. The argument serves multiple purposes. If it is null or empty, it opens a dialog to select a dicom file.
        // Otherwise, if dicom.show() is called, it is the title of the dialog. Since we are not showing any dialogs here, we just need to pass a non-null, non-empty string.
        dicom.run("DICOM");

        ImageStack imageStack = dicom.getImageStack();

        if (sliceIndex >= 1 && sliceIndex <= imageStack.getSize()) {
            ImageIO.write(imageStack.getProcessor(sliceIndex).getBufferedImage(), imageType, baos);
            return baos.toByteArray();
        } else {
            logger.error(
                    "Image slice " + sliceIndex + " not found for message " + message.getMessageId() + ".");
        }
    } catch (IOException e) {
        logger.error("Error Converting DICOM image", e);
    } finally {
        IOUtils.closeQuietly(bais);
        IOUtils.closeQuietly(baos);
    }

    return null;
}

From source file:net.daimonin.client3d.editor.main.Editor3D.java

/**
* Builds a single PNG out of all ImageSetImages, considering their calculated
* coordinates.//  w w w.j a  va 2 s . c  o m
* 
* @param fileNameImageSet Name of resulting PNG.
* @param dimension [width, height] of the resulting PNG. where 0 is maximum
*          compression, 1 is no compression at all.
* @throws IOException IOException.
*/
private static void writeImageSet(final String fileNameImageSet, final int[] dimension) throws IOException {

    BufferedImage bigImg = new BufferedImage(dimension[0], dimension[1], BufferedImage.TYPE_INT_ARGB);
    Graphics2D big = bigImg.createGraphics();
    for (int i = 0; i < images.size(); i++) {
        if (images.get(i).getBorderSize() > 0) {
            ParameterBlock params = new ParameterBlock();
            params.addSource(images.get(i).getImage());
            params.add(images.get(i).getBorderSize()); // left pad
            params.add(images.get(i).getBorderSize()); // right pad
            params.add(images.get(i).getBorderSize()); // top pad
            params.add(images.get(i).getBorderSize()); // bottom pad
            params.add(new BorderExtenderConstant(new double[] { images.get(i).getBorderColor().getRed(),
                    images.get(i).getBorderColor().getGreen(), images.get(i).getBorderColor().getBlue(),
                    BORDERCOLORMAX }));

            big.drawImage(JAI.create("border", params).getAsBufferedImage(), images.get(i).getPosX(),
                    images.get(i).getPosY(), null);

        } else {
            big.drawImage(images.get(i).getImage(), images.get(i).getPosX(), images.get(i).getPosY(), null);
        }
    }

    big.dispose();
    ImageIO.write(bigImg, "png", new File(fileNameImageSet));
    printInfo(System.getProperty("user.dir") + "/" + imageset + " created");
}

From source file:com.reydentx.core.common.PhotoUtils.java

public static byte[] scaleBufferedImage(boolean isPNG, BufferedImage originalImage, int x, int y, int width,
        int height) {
    byte[] imageFinal = null;
    try {//  ww  w .j a v  a 2 s .  co  m
        if (originalImage != null) {
            int type = (originalImage.getType() == 0) ? BufferedImage.TYPE_INT_ARGB : originalImage.getType();
            BufferedImage resizedImage = new BufferedImage(width, height, type);
            Graphics2D g = resizedImage.createGraphics();
            ByteArrayOutputStream outstream = new ByteArrayOutputStream();
            g.drawImage(originalImage, x, y, width, height, null);
            g.dispose();

            if (isPNG) {
                ImageIO.write(resizedImage, "png", outstream);
            } else {
                ImageIO.write(resizedImage, "jpg", outstream);
            }
            imageFinal = outstream.toByteArray();
        }
    } catch (IOException ex) {
    }
    return imageFinal;
}

From source file:com.db.comserv.main.utilities.HttpCaller.java

@Override
@edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "DM_DEFAULT_ENCODING")
public HttpResult runRequest(String type, String methodType, URL url, List<Map<String, String>> headers,
        String requestBody, String sslByPassOption, int connTimeOut, int readTimeout, HttpServletRequest req)
        throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException,
        UnsupportedEncodingException, IOException, UnknownHostException, URISyntaxException {

    StringBuffer response = new StringBuffer();
    HttpResult httpResult = new HttpResult();
    boolean gzip = false;
    final long startNano = System.nanoTime();
    try {//from   ww  w  .  ja v  a 2 s .co m
        URL encodedUrl = new URL(Utility.encodeUrl(url.toString()));
        HttpURLConnection con = (HttpURLConnection) encodedUrl.openConnection();
        TrustModifier.relaxHostChecking(con, sslByPassOption);

        // connection timeout 5s
        con.setConnectTimeout(connTimeOut);

        // read timeout 10s
        con.setReadTimeout(readTimeout * getQueryCost(req));

        methodType = methodType.toUpperCase();
        con.setRequestMethod(methodType);

        sLog.debug("Performing '{}' to '{}'", methodType, ServletUtil.filterUrl(url.toString()));

        // Get headers & set request property
        for (int i = 0; i < headers.size(); i++) {
            Map<String, String> header = headers.get(i);
            con.setRequestProperty(header.get("headerKey").toString(), header.get("headerValue").toString());
            sLog.debug("Setting Header '{}' with value '{}'", header.get("headerKey").toString(),
                    ServletUtil.filterHeaderValue(header.get("headerKey").toString(),
                            header.get("headerValue").toString()));
        }

        if (con.getRequestProperty("Accept-Encoding") == null) {
            con.setRequestProperty("Accept-Encoding", "gzip");
        }

        if (requestBody != null && !requestBody.equals("")) {
            con.setDoOutput(true);
            DataOutputStream wr = new DataOutputStream(con.getOutputStream());
            wr.write(Utility.toUtf8Bytes(requestBody));
            wr.flush();
            wr.close();

        }

        // push response
        BufferedReader in = null;
        String inputLine;

        List<String> contentEncoding = con.getHeaderFields().get("Content-Encoding");
        if (contentEncoding != null) {
            for (String val : contentEncoding) {
                if ("gzip".equalsIgnoreCase(val)) {
                    sLog.debug("Gzip enabled response");
                    gzip = true;
                    break;
                }
            }
        }

        sLog.debug("Response: '{} {}' with headers '{}'", con.getResponseCode(), con.getResponseMessage(),
                ServletUtil.buildHeadersForLog(con.getHeaderFields()));

        if (con.getResponseCode() != 200 && con.getResponseCode() != 201) {
            if (con.getErrorStream() != null) {
                if (gzip) {
                    in = new BufferedReader(
                            new InputStreamReader(new GZIPInputStream(con.getErrorStream()), "UTF-8"));
                } else {
                    in = new BufferedReader(new InputStreamReader(con.getErrorStream(), "UTF-8"));
                }
            }
        } else {
            String[] urlParts = url.toString().split("\\.");
            if (urlParts.length > 1) {
                String ext = urlParts[urlParts.length - 1];
                if (ext.equalsIgnoreCase("png") || ext.equalsIgnoreCase("jpg") || ext.equalsIgnoreCase("jpeg")
                        || ext.equalsIgnoreCase("gif")) {
                    BufferedImage imBuff;
                    if (gzip) {
                        imBuff = ImageIO.read(new GZIPInputStream(con.getInputStream()));
                    } else {
                        BufferedInputStream bfs = new BufferedInputStream(con.getInputStream());
                        imBuff = ImageIO.read(bfs);
                    }
                    BufferedImage newImage = new BufferedImage(imBuff.getWidth(), imBuff.getHeight(),
                            BufferedImage.TYPE_3BYTE_BGR);

                    // converting image to greyScale
                    int width = imBuff.getWidth();
                    int height = imBuff.getHeight();
                    for (int i = 0; i < height; i++) {
                        for (int j = 0; j < width; j++) {
                            Color c = new Color(imBuff.getRGB(j, i));
                            int red = (int) (c.getRed() * 0.21);
                            int green = (int) (c.getGreen() * 0.72);
                            int blue = (int) (c.getBlue() * 0.07);
                            int sum = red + green + blue;
                            Color newColor = new Color(sum, sum, sum);
                            newImage.setRGB(j, i, newColor.getRGB());
                        }
                    }

                    ByteArrayOutputStream out = new ByteArrayOutputStream();
                    ImageIO.write(newImage, "jpg", out);
                    byte[] bytes = out.toByteArray();

                    byte[] encodedBytes = Base64.encodeBase64(bytes);
                    String base64Src = new String(encodedBytes);
                    int imageSize = ((base64Src.length() * 3) / 4) / 1024;
                    int initialImageSize = imageSize;
                    int maxImageSize = Integer.parseInt(properties.getValue("Reduced_Image_Size"));
                    float quality = 0.9f;
                    if (!(imageSize <= maxImageSize)) {
                        //This means that image size is greater and needs to be reduced.
                        sLog.debug("Image size is greater than " + maxImageSize + " , compressing image.");
                        while (!(imageSize < maxImageSize)) {
                            base64Src = compress(base64Src, quality);
                            imageSize = ((base64Src.length() * 3) / 4) / 1024;
                            quality = quality - 0.1f;
                            DecimalFormat df = new DecimalFormat("#.0");
                            quality = Float.parseFloat(df.format(quality));
                            if (quality <= 0.1) {
                                break;
                            }
                        }
                    }
                    sLog.debug("Initial image size was : " + initialImageSize + " Final Image size is : "
                            + imageSize + "Url is : " + url + "quality is :" + quality);
                    String src = "data:image/" + urlParts[urlParts.length - 1] + ";base64,"
                            + new String(base64Src);
                    JSONObject joResult = new JSONObject();
                    joResult.put("Image", src);
                    out.close();
                    httpResult.setResponseCode(con.getResponseCode());
                    httpResult.setResponseHeader(con.getHeaderFields());
                    httpResult.setResponseBody(joResult.toString());
                    httpResult.setResponseMsg(con.getResponseMessage());
                    return httpResult;
                }
            }

            if (gzip) {
                in = new BufferedReader(
                        new InputStreamReader(new GZIPInputStream(con.getInputStream()), "UTF-8"));
            } else {
                in = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
            }
        }
        if (in != null) {
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
        }

        httpResult.setResponseCode(con.getResponseCode());
        httpResult.setResponseHeader(con.getHeaderFields());
        httpResult.setResponseBody(response.toString());
        httpResult.setResponseMsg(con.getResponseMessage());

    } catch (Exception e) {
        sLog.error("Failed to received HTTP response after timeout", e);

        httpResult.setTimeout(true);
        httpResult.setResponseCode(500);
        httpResult.setResponseMsg("Internal Server Error Timeout");
        return httpResult;
    }

    return httpResult;
}

From source file:ispok.pres.bb.NewVisitor.java

/**
 *
 * @return//from w w  w . j  a  v  a 2 s.c o m
 */
public String addVisitor() {

    PostalCodeDto postalCodeDto = new PostalCodeDto(postalCode);
    postalCodeService.savePostalCode(postalCodeDto);

    CityDto cityDto = new CityDto(city);
    cityService.saveCity(cityDto);

    RegionDto regionDto = new RegionDto(region);
    regionService.saveRegion(regionDto);

    DomicileDto domicileDto = new DomicileDto();
    domicileDto.setAddress1(address);
    domicileDto.setCityId(cityDto.getId());
    domicileDto.setPostalCodeId(postalCodeDto.getId());
    logger.debug("Country: {}", countryId);
    domicileDto.setCountryId(countryId);
    domicileDto.setRegionId(regionDto.getId());

    domicileService.saveDomicile(domicileDto);

    VisitorDto visitorDto = new VisitorDto();
    visitorDto.setFirstName(firstName);
    visitorDto.setLastName(lastName);
    visitorDto.setBirthDate(birthDate);
    visitorDto.setNin(nin);
    visitorDto.setNickname(nickname);
    visitorDto.setTelephone(telephone);
    visitorDto.setEmail(email);
    visitorDto.setSex(sex);
    visitorDto.setPassword(password);
    visitorDto.setBonusPoints(0);
    logger.debug("Citizenship: {}", citizenshipId);
    if (citizenshipId == null) {
        citizenshipId = countryId;
    }
    visitorDto.setCitizenshipId(citizenshipId);
    visitorDto.setDomicileId(domicileDto.getId());

    try {
        logger.trace("Read photo file");
        logger.debug("Photo name: {}", photoFile.getFileName());

        BufferedImage originalPhotoImage = ImageIO.read(photoFile.getInputstream());

        int width = originalPhotoImage.getWidth();
        int height = originalPhotoImage.getHeight();
        float scaleFactorNormalize;
        float scaleFactorThumb;
        if (height > width) {
            scaleFactorThumb = (float) 200 / height;
            scaleFactorNormalize = (float) 500 / height;
        } else {
            scaleFactorThumb = (float) 200 / width;
            scaleFactorNormalize = (float) 500 / width;
        }

        logger.debug("Scale factor for normalized photo: {}", scaleFactorNormalize);
        logger.debug("Scale factor for photo thumbnail: {}", scaleFactorThumb);

        //            Image scaledImage = bi.getScaledInstance((int) (width * scaleFactor), (int) (height * scaleFactor), Image.SCALE_SMOOTH);
        //            BufferedImage resizedImage = new BufferedImage((int) (width * scaleFactor), (int) (height * scaleFactor), bi.getType());
        //            Graphics2D g = resizedImage.createGraphics();
        //            g.drawImage(scaledImage, 0, 0, new Color(0, 0, 0), null);
        //            g.dispose();
        //
        //            BufferedImage resizedImage = bi.getScaledInstance(width, height, width)
        //            AffineTransform at = AffineTransform.getScaleInstance(scaleFactor, scaleFactor);
        //            AffineTransformOp ato = new AffineTransformOp(at, null);
        //            Graphics2D g = bi.createGraphics();
        //            g.drawImage(bi, ato, 0, 0);
        //            g.dispose();
        //
        int normalizedWidth = (int) (width * scaleFactorNormalize);
        int normalizeHeight = (int) (height * scaleFactorNormalize);

        logger.debug("Normalized Width: {}", normalizedWidth);
        logger.debug("Normalized Height: {}", normalizeHeight);

        int thumbWidth = (int) (width * scaleFactorThumb);
        int thumbHeight = (int) (height * scaleFactorThumb);

        logger.debug("Thumb width: {}", thumbWidth);
        logger.debug("Thumb height: {}", thumbHeight);

        BufferedImage normalizedPhotoImage = ImageUtil.resizeImage(originalPhotoImage, normalizedWidth,
                normalizeHeight);

        logger.debug("Width of normalized photo: {}", normalizedPhotoImage.getWidth());
        logger.debug("Height of normalized photo: {}", normalizedPhotoImage.getHeight());

        BufferedImage thumbPhotoImage = ImageUtil.resizeImage(originalPhotoImage, thumbWidth, thumbHeight);

        logger.debug("Width of thumb photo: {}", thumbPhotoImage.getWidth());
        logger.debug("Height of thumb photo: {}", thumbPhotoImage.getHeight());

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(normalizedPhotoImage, "png", baos);
        baos.flush();

        normalizedPhotoData = baos.toByteArray();

        baos = new ByteArrayOutputStream();
        ImageIO.write(thumbPhotoImage, "png", baos);
        baos.flush();

        thumbPhotoData = baos.toByteArray();

    } catch (IOException ex) {
        logger.catching(ex);
    }

    if (photoFile != null) {
        visitorDto.setPhoto(normalizedPhotoData);
    } else {
        visitorDto.setPhoto(new byte[0]);
    }

    if ("".equals(password)) {
        password = RandomString.getRandomString(6);
    }

    visitorService.addVisitor(visitorDto);
    id = visitorDto.getId();

    return "/admin/management/visitors/confirmNew.xhtml";
}

From source file:de.fau.amos.ChartRenderer.java

/**
 * /*from w  ww .j a  v  a 2 s.co  m*/
 * Reads Information from request and returns respective chart (.png-type) in response
 * 
 * @param request Request from website. Contains info about what should be displayed in chart.
 * @param response Contains .png-file with ready-to-use chart.
 * 
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    response.setContentType("image/png");

    ServletOutputStream os = response.getOutputStream();

    //<img src="../ChartRenderer?selectedChartType=<%=chartType%>&time=<%out.println(time+(timeGranularity==3?"&endTime="+endTime:""));%>&timeGranularity=<%=timeGranularity%>&countType=<%=countType%>&groupParameters=<%out.println(ChartPreset.createParameterString(request));%>" />

    JFreeChart chart = null;

    // Parameters from URL
    String chartType = request.getParameter("selectedChartType");
    if (chartType != null) {
        chartType = chartType.trim();
    } else {
        chartType = "";
    }
    String startTime = request.getParameter("startTime");
    String endTime = request.getParameter("endTime");
    String timeGranularity = request.getParameter("timeGranularity");
    String stringTimeGranularity = timeGranularityToString(timeGranularity);
    String countType = countTypeToString(request.getParameter("countType"));
    String groupLocationParameters = encodeGroupParameters(request.getParameter("groupLocationParameters"));
    String groupFormatParameters = encodeGroupParameters(request.getParameter("groupFormatParameters"));
    String unit = request.getParameter("unit");

    int width = 100;
    try {
        width = Integer.parseInt(request.getParameter("w"));
    } catch (NumberFormatException e) {
    }
    int height = 100;
    try {
        height = Integer.parseInt(request.getParameter("h"));
    } catch (NumberFormatException e) {
    }

    if (chartType.equals("1")) {
        //show time chart
        // Create TimeSeriesCollection from URL-Parameters. This includes the SQL Query
        TimeSeriesCollection dataset = null;
        dataset = createTimeCollection(stringTimeGranularity, startTime, endTime, countType,
                groupLocationParameters, unit);

        // Create Chart from TimeSeriesCollection and do graphical modifications.
        if (timeGranularity.equals("0")) {
            chart = createTimeLineChart(dataset, timeGranularity, startTime, unit);
        } else {
            chart = createTimeBarChart(dataset, timeGranularity, startTime, unit);
        }
    } else if (chartType.equals("2")) {

        //show location-format chart
        DefaultCategoryDataset dataset = createLocationFormatCollection(startTime, endTime, countType,
                groupLocationParameters, groupFormatParameters, unit, chartType);
        chart = createLocationFormatChart(dataset, unit);

    } else if (chartType.equals("3")) {

        //show location-format chart
        DefaultCategoryDataset dataset = createLocationFormatCollection(startTime, endTime, countType,
                groupLocationParameters, groupFormatParameters, unit, chartType);
        chart = createLocationFormatChart(dataset, unit);

    } else if (chartType.equals("forecast")) {

        TimeSeriesCollection dataset = createForecastCollection(request.getParameter("forecastYear"),
                request.getParameter("forecastPlant"), request.getParameter("forecastMethod"),
                request.getParameter("forecastUnits"));
        chart = createForecastChart(dataset, "2004-01-01 00:00:00", "1");
    }

    //create Image and clear output stream
    RenderedImage chartImage = chart.createBufferedImage(width, height);
    ImageIO.write(chartImage, "png", os);
    os.flush();
    os.close();

}

From source file:gda.device.scannable.keyence.Keyence.java

private String writeImage(BufferedImage image) throws IOException {
    String fileName = PathConstructor.createFromDefaultProperty() + "/" + getName() + "-"
            + dateFormat.format(new Date()) + "." + imageFormat;
    File imageFile = new File(fileName);
    ImageIO.write(image, imageFormat, imageFile);
    return fileName;
}