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.pdfhow.diff.UploadServlet.java

/**
 * Handles the HTTP <code>GET</code> method.
 *
 * @param request/*from w ww .j av  a  2  s.  c  o  m*/
 *            servlet request
 * @param response
 *            servlet response
 * @throws ServletException
 *             if a servlet-specific error occurs
 * @throws IOException
 *             if an I/O error occurs
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (request.getParameter("getfile") != null && !request.getParameter("getfile").isEmpty()) {
        File file = new File(
                request.getServletContext().getRealPath("/") + "imgs/" + request.getParameter("getfile"));
        if (file.exists()) {
            int bytes = 0;
            ServletOutputStream op = response.getOutputStream();

            response.setContentType(getMimeType(file));
            response.setContentLength((int) file.length());
            response.setHeader("Content-Disposition", "inline; filename=\"" + file.getName() + "\"");

            byte[] bbuf = new byte[1024];
            DataInputStream in = new DataInputStream(new FileInputStream(file));

            while ((in != null) && ((bytes = in.read(bbuf)) != -1)) {
                op.write(bbuf, 0, bytes);
            }

            in.close();
            op.flush();
            op.close();
        }
    } else if (request.getParameter("delfile") != null && !request.getParameter("delfile").isEmpty()) {
        File file = new File(
                request.getServletContext().getRealPath("/") + "imgs/" + request.getParameter("delfile"));
        if (file.exists()) {
            file.delete(); // TODO:check and report success
        }
    } else if (request.getParameter("getthumb") != null && !request.getParameter("getthumb").isEmpty()) {
        File file = new File(
                request.getServletContext().getRealPath("/") + "imgs/" + request.getParameter("getthumb"));
        if (file.exists()) {
            System.out.println(file.getAbsolutePath());
            String mimetype = getMimeType(file);
            if (mimetype.endsWith("png") || mimetype.endsWith("jpeg") || mimetype.endsWith("jpg")
                    || mimetype.endsWith("gif")) {
                BufferedImage im = ImageIO.read(file);
                if (im != null) {
                    BufferedImage thumb = Scalr.resize(im, 75);
                    ByteArrayOutputStream os = new ByteArrayOutputStream();
                    if (mimetype.endsWith("png")) {
                        ImageIO.write(thumb, "PNG", os);
                        response.setContentType("image/png");
                    } else if (mimetype.endsWith("jpeg")) {
                        ImageIO.write(thumb, "jpg", os);
                        response.setContentType("image/jpeg");
                    } else if (mimetype.endsWith("jpg")) {
                        ImageIO.write(thumb, "jpg", os);
                        response.setContentType("image/jpeg");
                    } else {
                        ImageIO.write(thumb, "GIF", os);
                        response.setContentType("image/gif");
                    }
                    ServletOutputStream srvos = response.getOutputStream();
                    response.setContentLength(os.size());
                    response.setHeader("Content-Disposition", "inline; filename=\"" + file.getName() + "\"");
                    os.writeTo(srvos);
                    srvos.flush();
                    srvos.close();
                }
            }
        } // TODO: check and report success
    } else {
        PrintWriter writer = response.getWriter();
        writer.write("call POST with multipart form data");
    }
}

From source file:net.acesinc.convergentui.BaseFilter.java

protected void writeResponse(BufferedImage image, MediaType type) throws Exception {
    RequestContext context = RequestContext.getCurrentContext();
    // there is no body to send
    if (image == null) {
        return;/*from  www  . j  a  v a 2s . c o m*/
    }
    HttpServletResponse servletResponse = context.getResponse();
    //        servletResponse.setCharacterEncoding("UTF-8");
    servletResponse.setContentType(type.toString());

    ByteArrayOutputStream tmp = new ByteArrayOutputStream();
    ImageIO.write(image, type.getSubtype(), tmp);
    tmp.close();
    Integer contentLength = tmp.size();

    servletResponse.setContentLength(contentLength);

    OutputStream outStream = servletResponse.getOutputStream();
    ByteArrayOutputStream os = new ByteArrayOutputStream();

    ImageIO.write(image, type.getSubtype(), os);
    InputStream is = new ByteArrayInputStream(os.toByteArray());

    try {
        writeResponse(is, outStream);
    } finally {
        try {
            if (is != null) {
                is.close();
            }
            outStream.flush();
            outStream.close();
        } catch (IOException ex) {
        }
    }
}

From source file:apiserver.model.Document.java

public void setFile(Object file) throws IOException {
    // if byte[] write to tmp file and then cache that.
    if (file instanceof FileByteWrapper) {
        String[] nameParts = ((FileByteWrapper) file).getName().split("\\.");
        File tmpFile = File.createTempFile(nameParts[0], "." + nameParts[1]);
        //convert array of bytes into file
        FileOutputStream fs = new FileOutputStream(tmpFile);
        fs.write(((FileByteWrapper) file).getBytes());
        fs.close();/*from  w w  w  .  j  ava2 s .  c  o m*/
        tmpFile.deleteOnExit();
        file = tmpFile;
    }

    if (file instanceof File) {
        if (!((File) file).exists() || ((File) file).isDirectory()) {
            throw new IOException("Invalid File Reference");
        }

        fileName = ((File) file).getName();
        this.file = file;
        this.setFileName(fileName);
        this.contentType = MimeType.getMimeType(fileName);

        byte[] bytes = FileUtils.readFileToByteArray(((File) file));
        this.setFileBytes(bytes);
        this.setSize(new Integer(bytes.length).longValue());
    } else if (file instanceof MultipartFile) {
        fileName = ((MultipartFile) file).getOriginalFilename();
        this.setContentType(MimeType.getMimeType(((MultipartFile) file).getContentType()));
        this.setFileName(((MultipartFile) file).getOriginalFilename());
        this.setFileBytes(((MultipartFile) file).getBytes());
        this.setSize(new Integer(this.getFileBytes().length).longValue());
    } else if (file instanceof BufferedImage) {
        if (fileName == null) {
            fileName = UUID.randomUUID().toString();
        }

        // Convert buffered reader to byte array
        String _mime = this.getContentType().name();

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ImageIO.write((BufferedImage) file, _mime, byteArrayOutputStream);
        byteArrayOutputStream.flush();
        byte[] imageBytes = byteArrayOutputStream.toByteArray();
        byteArrayOutputStream.close();
        this.setFileBytes(imageBytes);
    }

}

From source file:de.steilerdev.myVerein.server.model.GridFSRepository.java

public GridFSFile storeClubLogo(MultipartFile clubLogoFile) throws MongoException {
    if (!clubLogoFile.getContentType().startsWith("image")) {
        logger.warn("Trying to store a club logo, which is not an image");
        throw new MongoException("The file needs to be an image");
    } else if (!(clubLogoFile.getContentType().equals("image/jpeg")
            || clubLogoFile.getContentType().equals("image/png"))) {
        logger.warn("Trying to store an incompatible image " + clubLogoFile.getContentType());
        throw new MongoException("The used image is not compatible, please use only PNG or JPG files");
    } else {/*from w ww .  j  a v  a 2 s .  c om*/
        File clubLogoTempFile = null;
        try {
            clubLogoTempFile = File.createTempFile("tempClubLogo", "png");
            clubLogoTempFile.deleteOnExit();
            if (clubLogoFile.getContentType().equals("image/png")) {
                logger.debug("No need to convert club logo");
                clubLogoFile.transferTo(clubLogoTempFile);
            } else {
                logger.info("Converting club logo file to png");
                //Reading, converting and writing club logo
                ImageIO.write(ImageIO.read(clubLogoFile.getInputStream()), clubLogoFileFormat,
                        clubLogoTempFile);
            }

            //Deleting current file
            deleteCurrentClubLogo();

            try (FileInputStream clubLogoStream = new FileInputStream(clubLogoTempFile)) {
                logger.debug("Saving club logo");
                //Saving file
                return gridFS.store(clubLogoStream, clubLogoFileName, clubLogoFileFormatMIME);
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new MongoException("Unable to store file");
        } finally {
            if (clubLogoTempFile != null) {
                clubLogoTempFile.delete();
            }
        }
    }
}

From source file:org.jtheque.movies.services.impl.MoviesService.java

@Override
public void saveImage(Movie movie, BufferedImage image) {
    String folder = moviesModule.getThumbnailFolderPath();

    String imageName = FileUtils.getFreeName(folder, movie.getTitle() + ".png");

    try {/*from ww w.jav a  2 s  .c om*/
        ImageIO.write(image, "png", new File(folder + imageName));

        movie.setImage(imageName);
    } catch (IOException e) {
        LoggerFactory.getLogger(getClass()).error(e.getMessage(), e);
    }
}

From source file:iqq.app.module.QQCacheModule.java

@IMEventHandler(IMEventType.USER_FACE_UPDATE)
protected void processIMUserFaceUpdate(final IMEvent event) throws URISyntaxException {
    tasks.submit(new Runnable() {
        public void run() {
            QQUser user = (QQUser) event.getTarget();
            String hash = getUserHash(user);
            File file = resources.getFile("user/" + uin + "/face/" + hash + ".png");
            try {
                ImageIO.write(user.getFace(), "png", file);
            } catch (IOException e) {
                LOG.warn("cache user face error!", e);
            }/*from  w  w  w.j  a v  a2  s. com*/
        }
    });
}

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

public void saveToFile(File file) {
    // 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);/*from w  w  w .j  ava 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);

    file.mkdirs();
    try {
        ImageIO.write(image, "png", file);
    } catch (Exception e) {
        // Do nothing
    }
}

From source file:com.formkiq.core.service.conversion.PdfToPngFormatConverter.java

/**
 * Merge Buffered Images together./* ww w.ja  v  a  2  s .  com*/
 * @param buffImages {@link BufferedImage}
 * @return {@link ConversionResult}
 * @throws IOException IOException
 */
private ConversionResult merge(final BufferedImage[] buffImages) throws IOException {

    ConversionResult result = new ConversionResult();

    int cols = 1;
    int rows = buffImages.length;

    int type = buffImages[0].getType();
    int width = buffImages[0].getWidth();
    int height = buffImages[0].getHeight();

    BufferedImage bi = new BufferedImage(width * cols, height * rows, type);

    int num = 0;
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            bi.createGraphics().drawImage(buffImages[num], width * j, height * i, null);
            num++;
        }
    }

    ByteArrayOutputStream os = new ByteArrayOutputStream();
    try {
        ImageIO.write(bi, "png", os);
    } finally {
        os.close();
    }

    result.setDatawidth(width * cols);
    result.setDataheight(height * rows);
    result.setData(os.toByteArray());
    return result;
}

From source file:com.modwiz.sponge.statue.utils.skins.SkinResolverService.java

private MinecraftSkin getSkin0(UUID profileID, boolean forceRefresh) {
    if (forceRefresh) {
        skinCache.remove(profileID);//from  w  w  w .j  a va2s  .  c  o  m
    }

    if (!skinCache.containsKey(profileID)) {
        JSONObject fullProfile = skinLoader.getFullProfile(profileID);
        if (fullProfile == null) {
            skinCache.put(profileID, null);
            return null;
        }

        MinecraftSkin skin = skinLoader.extractSkin(profileID, fullProfile);

        if (skin != null) {
            try {
                ImageIO.write(skin.texture, "png", new File(cacheDir, skin.uuid.toString() + ".png"));
                JsonObject skinData = new JsonObject();

                skinData.addProperty("type", skin.type.name());
                skinData.addProperty("uuid", skin.uuid.toString());
                skinData.addProperty("timestamp", skin.timestamp);

                Files.write(Paths.get(cacheDir.getAbsolutePath(), skin.uuid.toString() + ".json"),
                        skinData.toString().getBytes());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        skinCache.put(profileID, skin);
        return skin;
    }

    return skinCache.get(profileID);
}

From source file:net.roboconf.doc.generator.internal.GraphUtils.java

/**
 * Writes a graph as a PNG image./*  w  ww  . j  av a  2s.  c o  m*/
 * @param outputFile the output file
 * @param selectedComponent the component to highlight
 * @param layout the layout
 * @param graph the graph
 * @param edgeShapeTransformer the transformer for edge shapes (straight line, curved line, etc)
 * @throws IOException if something went wrong
 */
public static void writeGraph(File outputFile, Component selectedComponent, Layout<AbstractType, String> layout,
        Graph<AbstractType, String> graph,
        AbstractEdgeShapeTransformer<AbstractType, String> edgeShapeTransformer, Map<String, String> options)
        throws IOException {

    VisualizationImageServer<AbstractType, String> vis = new VisualizationImageServer<AbstractType, String>(
            layout, layout.getSize());

    vis.setBackground(Color.WHITE);
    vis.getRenderContext().setEdgeLabelTransformer(new NoStringLabeller());
    vis.getRenderContext().setEdgeShapeTransformer(edgeShapeTransformer);

    vis.getRenderContext().setVertexLabelTransformer(new ToStringLabeller<AbstractType>());
    vis.getRenderContext().setVertexShapeTransformer(new VertexShape());
    vis.getRenderContext().setVertexFontTransformer(new VertexFont());

    Color defaultBgColor = decode(options.get(DocConstants.OPTION_IMG_BACKGROUND_COLOR),
            DocConstants.DEFAULT_BACKGROUND_COLOR);
    Color highlightBgcolor = decode(options.get(DocConstants.OPTION_IMG_HIGHLIGHT_BG_COLOR),
            DocConstants.DEFAULT_HIGHLIGHT_BG_COLOR);
    vis.getRenderContext().setVertexFillPaintTransformer(
            new VertexColor(selectedComponent, defaultBgColor, highlightBgcolor));

    Color defaultFgColor = decode(options.get(DocConstants.OPTION_IMG_FOREGROUND_COLOR),
            DocConstants.DEFAULT_FOREGROUND_COLOR);
    vis.getRenderContext().setVertexLabelRenderer(new MyVertexLabelRenderer(selectedComponent, defaultFgColor));
    vis.getRenderer().getVertexLabelRenderer().setPosition(Position.CNTR);

    BufferedImage image = (BufferedImage) vis.getImage(
            new Point2D.Double(layout.getSize().getWidth() / 2, layout.getSize().getHeight() / 2),
            new Dimension(layout.getSize()));

    ImageIO.write(image, "png", outputFile);
}