Example usage for java.awt.image BufferedImage getType

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

Introduction

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

Prototype

public int getType() 

Source Link

Document

Returns the image type.

Usage

From source file:ro.nextreports.engine.exporter.ResultExporter.java

protected byte[] getScaledImage(InputStream is, String name, int width, int height) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {/*from w w  w.  j ava 2 s. c  om*/
        BufferedImage img = ImageIO.read(is);

        if ((img.getWidth() == width) && (img.getHeight() == height)) {
            // original width and height                
            ImageIO.write(img, "png", baos);
        } else {
            int type = img.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : img.getType();
            BufferedImage scaledImg = new BufferedImage(width, height, type);
            Graphics2D gScaledImg = scaledImg.createGraphics();

            gScaledImg.setComposite(AlphaComposite.Src);
            gScaledImg.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                    RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            gScaledImg.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);

            gScaledImg.drawImage(img, 0, 0, width, height, null);

            ImageIO.write(scaledImg, "png", baos);
        }
    } catch (IOException ex) {
        ex.printStackTrace();
        LOG.error(ex.getMessage(), ex);
        throw new IOException("Image '" + name + "' could not be scaled.");
    } finally {
        is.close();
    }
    return baos.toByteArray();
}

From source file:se.dibbler.backend.generics.DibblerImageUtil.java

private static Response<Integer> getImageType(BufferedImage image) {
    try {/*from  w w w. j  av a2s . c o m*/
        Integer type = image.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : image.getType();
        return Response.success(type);
    } catch (Exception e) {
        LOG.error("[ ERROR when getting image type ] [ MESSAGE : {}]", e.getMessage());
        return Response.error(GenericError.FILE_HANDLING);
    }
}

From source file:se.llbit.chunky.resources.Texture.java

public void setTexture(BufferedImage newImage) {
    if (newImage.getType() == BufferedImage.TYPE_INT_ARGB) {
        image = newImage;//  www  .ja va2  s .  c o  m
    } else {
        // convert to ARGB
        image = new BufferedImage(newImage.getWidth(), newImage.getHeight(), BufferedImage.TYPE_INT_ARGB);
        Graphics g = image.createGraphics();
        g.drawImage(newImage, 0, 0, null);
        g.dispose();
    }

    // gamma correct the texture
    avgColorLinear = new float[] { 0, 0, 0, 0 };

    DataBufferInt dataBuffer = (DataBufferInt) image.getRaster().getDataBuffer();
    int[] data = dataBuffer.getData();
    width = image.getWidth();
    height = image.getHeight();
    linear = new float[width * height][4];
    for (int y = 0; y < height; ++y) {
        for (int x = 0; x < width; ++x) {
            int index = width * y + x;
            Color.getRGBAComponents(data[index], linear[index]);
            linear[index][0] = (float) FastMath.pow(linear[index][0], Scene.DEFAULT_GAMMA);
            linear[index][1] = (float) FastMath.pow(linear[index][1], Scene.DEFAULT_GAMMA);
            linear[index][2] = (float) FastMath.pow(linear[index][2], Scene.DEFAULT_GAMMA);
            avgColorLinear[0] += linear[index][3] * linear[index][0];
            avgColorLinear[1] += linear[index][3] * linear[index][1];
            avgColorLinear[2] += linear[index][3] * linear[index][2];
            avgColorLinear[3] += linear[index][3];
        }
    }

    if (PersistentSettings.getSingleColorTextures()) {
        float[] avgColorFlat = { 0, 0, 0 };
        if (avgColorLinear[3] > 0.001) {
            avgColorFlat[0] = avgColorLinear[0] / avgColorLinear[3];
            avgColorFlat[1] = avgColorLinear[1] / avgColorLinear[3];
            avgColorFlat[2] = avgColorLinear[2] / avgColorLinear[3];
        }
        for (int y = 0; y < height; ++y) {
            for (int x = 0; x < width; ++x) {
                int index = width * y + x;
                linear[index][0] = avgColorFlat[0];
                linear[index][1] = avgColorFlat[1];
                linear[index][2] = avgColorFlat[2];
                linear[index][3] = 1;
            }
        }
    }

    avgColorLinear[0] /= width * height;
    avgColorLinear[1] /= width * height;
    avgColorLinear[2] /= width * height;
    avgColorLinear[3] /= width * height;

    avgColor = Color.getRGBA(FastMath.pow(avgColorLinear[0], 1 / Scene.DEFAULT_GAMMA),
            FastMath.pow(avgColorLinear[1], 1 / Scene.DEFAULT_GAMMA),
            FastMath.pow(avgColorLinear[2], 1 / Scene.DEFAULT_GAMMA), avgColorLinear[3]);
}

From source file:se.llbit.chunky.world.SkymapTexture.java

@Override
public void setTexture(BufferedImage newImage) {

    if (newImage.getType() == BufferedImage.TYPE_INT_ARGB) {
        image = newImage;// w  ww . j a v a2s . c om
    } else {
        // convert to ARGB
        image = new BufferedImage(newImage.getWidth(), newImage.getHeight(), BufferedImage.TYPE_INT_ARGB);
        Graphics g = image.createGraphics();
        g.drawImage(newImage, 0, 0, null);
        g.dispose();
    }

    DataBufferInt dataBuffer = (DataBufferInt) image.getRaster().getDataBuffer();
    data = dataBuffer.getData();

    width = image.getWidth();
    height = image.getHeight();
    avgColor = ImageTools.calcAvgColor(image);

    Log.info("Preprocessing skymap texture");
    long start = System.currentTimeMillis();

    // gamma correct the texture

    int segX = 4;
    int segY = 4;
    if (width < segX)
        segX = 1;
    if (height < segY)
        segY = 1;
    TexturePreprocessor[][] preprocessor = new TexturePreprocessor[segX][segY];
    int w = width / segX;
    int h = height / segY;
    for (int i = 0; i < segX; ++i) {
        int x0 = w * i;
        int x1 = x0 + w - 1;
        if ((i + 1) == segX)
            x1 = width - 1;
        for (int j = 0; j < segY; ++j) {
            int y0 = h * j;
            int y1 = y0 + h - 1;
            if ((j + 1) == segY)
                y1 = height - 1;
            preprocessor[i][j] = new TexturePreprocessor(x0, x1, y0, y1);
            preprocessor[i][j].start();
        }
    }

    for (int i = 0; i < segX; ++i) {
        for (int j = 0; j < segY; ++j) {
            try {
                preprocessor[i][j].join();
            } catch (InterruptedException e) {
            }
        }
    }

    long time = System.currentTimeMillis() - start;

    Log.info("Skymap preprocessing took " + time + "ms");

}

From source file:servlets.cadastrarPatrimonioServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from  w  w  w.  ja  v a  2s.c o  m*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, Exception {
    response.setContentType("text/plain");
    PrintWriter out = response.getWriter();
    try {
        /* TODO output your page here. You may use following sample code. */
        String foto = "";
        String tipo = "";
        String titulo = "";
        String desc = "";
        String estado = "";
        int cat = 0;
        int subCat = 0;
        int itenSubCat = 0;
        String palavra = "";
        int idUsuario = 0;
        String finalidade = "patrimonio";

        ArrayList<ParametrosPagina> lst = new ArrayList<ParametrosPagina>();
        HttpSession session = request.getSession();
        UsuarioEntidade Logado = (UsuarioEntidade) session.getAttribute("UsuarioLogado");
        ServletFileUpload uploadHandler = new ServletFileUpload(new DiskFileItemFactory());

        PrintWriter writer = response.getWriter();

        StringBuilder json = new StringBuilder();

        List<FileItem> items = uploadHandler.parseRequest(request);
        for (FileItem item : items) {
            if (item.isFormField()) //pegando os atributosd da pagina pelo MULTIPART form data
            {
                ParametrosPagina p = new ParametrosPagina();
                p.setName(item.getFieldName());
                p.setValor(item.getString());
                lst.add(p);
            }
        }
        json.setLength(1);
        for (FileItem item : items) {

            if (!item.isFormField()) {

                JSONObject jsonObj = new JSONObject();
                jsonObj.put("name", item.getName());
                jsonObj.put("size", item.getSize());
                jsonObj.put("url", DESTINATION_DIR_PATH + "/" + item.getName());
                jsonObj.put("deleteUrl", DESTINATION_DIR_PATH + "/" + item.getName());
                jsonObj.put("deleteType", "DELETE");
                JSONArray jsonArray = new JSONArray();
                jsonArray.put(jsonObj);

                //CRIANDO MD5   PELO Id DO Usuario
                MD5 md5 = new MD5();
                String MD5 = md5.criarMD5ParaPrefixoFoto(Logado.getIdUsuario().toString());
                String nome = MD5 + "_" + item.getName();

                //LEMBRETE: limitar numero de imagensa para 5
                String path = getServletContext().getInitParameter("uploadDirectory2");
                foto = "/fotos_patriomonios/" + nome;
                File file = new File(path, nome);

                System.out.println(path);
                item.write(file);
                //                    writer.write(jsonArray.toString());
                jsonArray.write(writer);

                //redefiniNDO tamanho DA imagem
                BufferedImage originalImage = ImageIO.read(new File(path + nome));
                int type = originalImage.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : originalImage.getType();

                BufferedImage resizeImageHintJpg = RedefinirTamanhoImagem.resizeImageWithHint(originalImage,
                        type, finalidade);
                ImageIO.write(resizeImageHintJpg, "jpg", new File(path + nome));

                BufferedImage resizeImageHintPng = RedefinirTamanhoImagem.resizeImageWithHint(originalImage,
                        type, finalidade);
                ImageIO.write(resizeImageHintPng, "png", new File(path + nome));
                ////////////////
                for (ParametrosPagina p : lst) {

                    if (p.getName().equals("txt_titulo")) {
                        titulo = p.getValor();
                    }
                    if (p.getName().equals("txt_descricao")) {
                        desc = p.getValor();
                    }
                    if (p.getName().equals("txt_estado")) {
                        estado = p.getValor();
                    }
                    if (p.getName().equals("txt_categoria")) {
                        cat = Integer.parseInt(p.getValor());
                    }
                    if (p.getName().equals("txt_subcategoria")) {
                        subCat = Integer.parseInt(p.getValor());
                    }
                    if (p.getName().equals("txt_itens_subcategoria")) {
                        itenSubCat = Integer.parseInt(p.getValor());
                    }
                    if (p.getName().equals("txt_palavrachave")) {
                        palavra = p.getValor();
                    }
                    if (p.getName().equals("id_usuario")) {
                        idUsuario = Integer.parseInt(p.getValor());
                    }
                    if (p.getName().equals("txt_tipo")) {
                        tipo = p.getValor();
                    }
                }

                PatrimonioEntidade pat = new PatrimonioEntidade();

                if (foto == null) {
                    foto = "/img/foto_default_produto.png";
                }
                pat.setFoto(foto);

                pat.setTitulo(titulo);
                pat.setDescricao(desc);
                pat.setEstadoConservacao(estado);
                pat.setIdCategoria(cat);
                pat.setIdSubcategoria(subCat);
                pat.setIdItensSubcat(itenSubCat);
                pat.setPalavraChave(palavra);
                pat.setIdUsuario(idUsuario);
                pat.setTipo(Short.parseShort(tipo));
                ControladorPatrimonio.cadastrarPatrimonio(pat);
                response.sendRedirect("cadastrar_patrimonio.jsp?msg=1");

            }
        }
    } catch (PersistenciaException e) {
        response.sendRedirect("cadastrar_patrimonio.jsp?msg=2&excep=" + e.getMessage());

    } catch (SQLException e) {
        System.out.println(e);
        response.sendRedirect("cadastrar_patrimonio.jsp?msg=3");
    } catch (Exception e) {
        System.out.println(e);
        response.sendRedirect("cadastrar_patrimonio.jsp?msg=4&" + e);
    } finally {

        out.close();
    }
}

From source file:servlets.EditarPerfiFotoUploadlServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from ww  w.  j  a  v  a2 s  .c  om
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, Exception {
    response.setContentType("text/plain");
    PrintWriter out = response.getWriter();
    try {
        /* TODO output your page here. You may use following sample code. */
        int idUsuario = 0;
        String finalidade = "fotoPerfil";

        ArrayList<ParametrosPagina> lst = new ArrayList<ParametrosPagina>();
        HttpSession session = request.getSession();
        UsuarioEntidade Logado = (UsuarioEntidade) session.getAttribute("UsuarioLogado");
        ServletFileUpload uploadHandler = new ServletFileUpload(new DiskFileItemFactory());

        PrintWriter writer = response.getWriter();

        StringBuilder json = new StringBuilder();

        List<FileItem> items = uploadHandler.parseRequest(request);
        for (FileItem item : items) {
            if (item.isFormField()) //pegando os atributosd da pagina pelo MULTIPART form data
            {
                ParametrosPagina p = new ParametrosPagina();
                p.setName(item.getFieldName());
                p.setValor(item.getString());
                lst.add(p);
            }
        }

        json.setLength(1);
        for (FileItem item : items) {

            if (!item.isFormField()) {

                JSONObject jsonObj = new JSONObject();
                jsonObj.put("name", item.getName());
                jsonObj.put("size", item.getSize());
                jsonObj.put("url", DESTINATION_DIR_PATH + "/" + item.getName());
                jsonObj.put("deleteUrl", DESTINATION_DIR_PATH + "/" + item.getName());
                jsonObj.put("deleteType", "DELETE");
                JSONArray jsonArray = new JSONArray();
                jsonArray.put(jsonObj);

                //CRIANDO MD5   PELO Id DO Usuario
                MD5 md5 = new MD5();
                String MD5 = md5.criarMD5ParaEnviarLink(Logado.getIdUsuario().toString());
                String nome = MD5 + "_" + item.getName();

                //LEMBRETE: limitar numero de imagensa para 5
                //                    String path = request.getServletContext().getRealPath("/") + "fotos_usuarios/";

                String path = getServletContext().getInitParameter("uploadDirectory");
                String foto = "/fotos_usuarios/" + nome;
                File file = new File(path, nome);

                System.out.println(path);
                item.write(file);

                jsonArray.write(writer);

                //redefiniNDO tamanho DA imagem
                BufferedImage originalImage = ImageIO.read(new File(path + nome));
                int type = originalImage.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : originalImage.getType();

                BufferedImage resizeImageHintJpg = RedefinirTamanhoImagem.resizeImageWithHint(originalImage,
                        type, finalidade);
                ImageIO.write(resizeImageHintJpg, "jpg", new File(path + nome));

                BufferedImage resizeImageHintPng = RedefinirTamanhoImagem.resizeImageWithHint(originalImage,
                        type, finalidade);
                ImageIO.write(resizeImageHintPng, "png", new File(path + nome));
                ////////////////
                for (ParametrosPagina p : lst) {

                    if (p.getName().equals("id_usuario")) {
                        idUsuario = Integer.parseInt(p.getValor());
                    }
                }

                if (foto == null) {
                    foto = "/img/foto_default.png";
                }
                String nomeAdmin = AdminDAO.pegarNomeAdmin();
                String emailAdmin = AdminDAO.pegarEmailAdmin();
                ControladorUsuario.cadastrarFotoUsuario(idUsuario, foto, nomeAdmin, emailAdmin);

                response.sendRedirect("editar_perfil.jsp?msg=5");

            }
        }
    } catch (PersistenciaException e) {
        response.sendRedirect("editar_perfil.jsp?msg=2&excep=" + e.getMessage());

    } catch (SQLException e) {
        System.out.println(e);
        response.sendRedirect("editar_perfil.jsp?msg=3");
    } catch (Exception e) {
        System.out.println(e);
        response.sendRedirect("editar_perfil.jsp?msg=4" + e);
    } finally {

        out.close();
    }
}

From source file:ucar.unidata.idv.ui.ImageGenerator.java

/**
 * Scale the given {@code source} {@link Image}.
 *
 * @param source Source image.// www. ja  v  a2 s . c  o m
 * @param width New width.
 * @param height New height.
 *
 * @return Scaled {@code source} image (uses bilinear interpolation).
 */
public static BufferedImage getScaledImage(Image source, int width, int height) {
    // convert the given Image into a BufferedImage if needed--makes things a
    // little easier.
    BufferedImage image;
    if (source instanceof BufferedImage) {
        image = (BufferedImage) source;
    } else {
        image = new BufferedImage(source.getWidth(null), source.getHeight(null), BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = image.createGraphics();
        g.drawImage(source, 0, 0, null);
        g.dispose();
    }

    int imageWidth = image.getWidth();
    int imageHeight = image.getHeight();
    double scaleX = (double) width / imageWidth;
    double scaleY = (double) height / imageHeight;
    AffineTransform scaleTransform = AffineTransform.getScaleInstance(scaleX, scaleY);
    BufferedImageOp op = new AffineTransformOp(scaleTransform, AffineTransformOp.TYPE_BILINEAR);
    return op.filter(image, new BufferedImage(width, height, image.getType()));
}

From source file:util.ui.UiUtilities.java

/**
 * Scales an image to a specific size and returns an BufferedImage
 *
 * @param img/* w  ww.java2 s. com*/
 *          Scale this IMage
 * @param width
 *          new width
 * @param height
 *          new height
 * @return Scaled BufferedImage
 *
 * @since 2.5
 */
public static BufferedImage scaleIconToBufferedImage(BufferedImage img, int width, int height) {
    return scaleIconToBufferedImage(img, width, height, img.getType());
}

From source file:VASSAL.tools.image.ImageIOImageLoaderTest.java

@Test
public void testLoadOk() throws IOException {
    final ImageTypeConverter mconv = new MemoryImageTypeConverter();
    final ImageIOImageLoader loader = new ImageIOImageLoader(mconv);

    final BufferedImage actual = read(loader, jpg);

    assertEquals(BufferedImage.TYPE_INT_RGB, actual.getType());
    assertImageContentEquals(src, actual);
}

From source file:VASSAL.tools.image.ImageIOImageLoaderTest.java

@Test
public void testLoadType2tRNSBug() throws IOException {
    final String efile = "test/VASSAL/tools/image/non-type2-tRNS.png";
    final String afile = "test/VASSAL/tools/image/type2-tRNS.png";

    final ImageTypeConverter mconv = new MemoryImageTypeConverter();
    final ImageIOImageLoader loader = new ImageIOImageLoader(mconv);

    final BufferedImage expected = ImageIO.read(new File(efile));
    final BufferedImage actual = read(loader, afile);

    assertEquals(BufferedImage.TYPE_INT_ARGB, actual.getType());

    // We check that:
    // (1) the images have the same fully-transparent pixels, and
    // (2) all other pixels are identical
    final int w = expected.getWidth();
    final int h = expected.getHeight();
    for (int x = 0; x < w; ++x) {
        for (int y = 0; y < h; ++y) {
            final int ep = expected.getRGB(x, y);
            final int ap = actual.getRGB(x, y);

            if ((ep & 0xff000000) == 0 && (ap & 0xff000000) == 0) {
                // color components of fully-transparent pixels don't matter
                continue;
            }//from w  w  w. j ava  2s  . c  om

            assertEquals(ep, ap);
        }
    }
}