Example usage for java.awt.image BufferedImage BufferedImage

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

Introduction

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

Prototype

public BufferedImage(int width, int height, int imageType) 

Source Link

Document

Constructs a BufferedImage of one of the predefined image types.

Usage

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

/**
 * Masks out white colour/*  www. j av  a2s  .c  om*/
 * @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:com.formkiq.core.service.conversion.PdfToPngFormatConverter.java

/**
 * Merge Buffered Images together.// ww  w.ja  v a  2s. c  o m
 * @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:herramientas.Ecualizacion_histograma.java

public BufferedImage ecualizacion() {
    BufferedImage resultado = new BufferedImage(img.getWidth(), img.getHeight(), img.getType());

    int[] datos_ec = new int[256];
    int[] datos_ac = new int[256];

    datos_ac[0] = datos[0];//w  ww . ja  va  2  s.  com
    for (int i = 1; i < 256; i++) {
        datos_ac[i] = datos[i] + datos_ac[i - 1];
    }

    int size = img.getWidth() * img.getHeight();
    int m = 256; //2^8, Imgenes de 8 bits.

    double factor = (double) m / size;

    for (int i = 0; i < 256; i++) {
        //            datos_ec[i] = Math.max(0, ((int) Math.round((m / size) * datos_ac[i]) - 1));

        datos_ec[i] = Math.max(0, ((int) Math.round(factor * datos_ac[i]) - 1));

        //            System.out.println((Math.round((m / size) * datos_ac[i])) - 1);
        //            System.out.println(datos_ec[i]);
    }

    for (int i = 0; i < resultado.getWidth(); i++) {
        for (int j = 0; j < resultado.getHeight(); j++) {
            int viejo = new Color(img.getRGB(i, j)).getRed();
            int nuevo = datos_ec[viejo];
            resultado.setRGB(i, j, new Color(nuevo, nuevo, nuevo).getRGB());
        }
    }
    return resultado;
}

From source file:de.ailis.wlandsuite.WebExtract.java

/**
 * Extracts the tilesets.//  w  w w  .  j av a  2 s  .c  o  m
 *
 * @param sourceDirectory
 *            The input directory
 * @param targetDirectory
 *            The output directory
 * @throws IOException
 *             When file operation fails.
 */

private void extractTilesets(final File sourceDirectory, final File targetDirectory) throws IOException {
    // Extract tilesets
    final File imagesDirectory = new File(targetDirectory, "images");
    imagesDirectory.mkdirs();
    for (int gameId = 1; gameId <= 2; gameId++) {
        final String filename = "allhtds" + gameId;

        log.info("Reading " + filename);
        final InputStream stream = new FileInputStream(new File(sourceDirectory, filename));
        try {
            final Htds htds = Htds.read(stream);

            int tilesetId = 0;
            log.info("Writing tileset " + tilesetId);
            for (final HtdsTileset tileset : htds.getTilesets()) {
                final List<Pic> tiles = tileset.getTiles();
                final int scale = this.scaleFilter.getScaleFactor();
                final BufferedImage out;
                final int outType = this.scaleFilter.getImageType();
                if (outType == -1)
                    out = new EgaImage(10 * 16 * scale,
                            (int) Math.ceil((double) tiles.size() / 10) * 16 * scale);
                else
                    out = new BufferedImage(10 * 16 * scale,
                            (int) Math.ceil((double) tiles.size() / 10) * 16 * scale, outType);
                final Graphics2D g = out.createGraphics();
                int i = 0;
                for (final Pic tile : tileset.getTiles()) {
                    g.drawImage(this.scaleFilter.scale(tile), i % 10 * 16 * scale, i / 10 * 16 * scale, null);
                    i++;
                }

                ImageIO.write(out, "png", new File(imagesDirectory, "tileset" + gameId + tilesetId + ".png"));
                tilesetId++;
            }
        } finally {
            stream.close();
        }
    }
}

From source file:vazkii.psi.client.core.helper.SharingHelper.java

public static String takeScreenshot() throws Exception {
    Minecraft mc = Minecraft.getMinecraft();

    ScaledResolution res = new ScaledResolution(mc);
    int screenWidth = mc.displayWidth;
    int screenHeight = mc.displayHeight;

    int scale = res.getScaleFactor();
    int width = 380 * scale;
    int height = 200 * scale;

    int left = screenWidth / 2 - width / 2;
    int top = screenHeight / 2 - height / 2;

    int i = width * height;

    if (pixelBuffer == null || pixelBuffer.capacity() < i) {
        pixelBuffer = BufferUtils.createIntBuffer(i);
        pixelValues = new int[i];
    }/*from   w w w  .  j  ava 2s .com*/

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

    GL11.glReadPixels(left, top, width, height, GL12.GL_BGRA, GL12.GL_UNSIGNED_INT_8_8_8_8_REV,
            (IntBuffer) pixelBuffer);

    pixelBuffer.get(pixelValues);
    TextureUtil.processPixelValues(pixelValues, width, height);
    BufferedImage bufferedimage = null;

    bufferedimage = new BufferedImage(width, height, 1);
    bufferedimage.setRGB(0, 0, width, height, pixelValues, 0, width);

    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    ImageIO.write(bufferedimage, "png", stream);
    byte[] bArray = stream.toByteArray();
    String base64 = Base64.getEncoder().encodeToString(bArray);
    return base64;
}

From source file:de.darkblue.bongloader2.utils.ToolBox.java

public static BufferedImage grayScaleAlpha(BufferedImage original) {

    int alpha, red, green, blue;
    int newPixel;

    BufferedImage avg_gray = new BufferedImage(original.getWidth(), original.getHeight(), original.getType());
    int[] avgLUT = new int[766];
    for (int i = 0; i < avgLUT.length; i++) {
        avgLUT[i] = (int) (i / 3);
    }//from w w  w. j  av a2 s  .co m

    for (int x = 0; x < original.getWidth(); x++) {
        for (int y = 0; y < original.getHeight(); y++) {

            // Get pixels by R, G, B
            int color = original.getRGB(x, y);
            alpha = color & 0xFF000000;

            red = (color >> 16) & 0xFF;
            green = (color >> 8) & 0xFF;
            blue = color & 0xFF;

            newPixel = red + green + blue;
            newPixel = avgLUT[newPixel];
            // Return back to original format
            newPixel = newPixel | (newPixel << 8) | (newPixel << 16) | alpha;

            // Write pixels into image
            avg_gray.setRGB(x, y, newPixel);

        }
    }

    return avg_gray;

}

From source file:net.mindengine.oculus.frontend.web.controllers.project.ProjectEditController.java

private static BufferedImage resize(BufferedImage image, int width, int height) {
    BufferedImage resizedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g = resizedImage.createGraphics();
    g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);

    g.drawImage(image, 0, 0, width, height, null);
    g.dispose();/*from w  ww  . jav  a2 s  . c o m*/
    return resizedImage;
}

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);//ww w. j a  v a2  s . co  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:common.utils.ImageUtils.java

/**
  * resize input image to new dinesions(only smaller) and save it to file
  * @param image input image for scaling
  * @param scale_factor factor for scaling image
 * @param rez writes resulting image to a file
 * @throws IOException/* w w w.  ja  v  a 2s .  c  o m*/
  */
public static void saveScaledImageWidth(BufferedImage image, double scale_factor, OutputStream rez)
        throws IOException {
    //long time_resize = System.currentTimeMillis();
    if (scale_factor == 1) {
        writeImage(image, 1, rez);
    } else {
        int width = (int) (scale_factor * image.getWidth());
        int height = (int) (scale_factor * image.getHeight());
        //BufferedImage scaled_bi = new BufferedImage( image.getWidth(), image.getHeight(), image.getType() );
        int type = image.getType();
        BufferedImage scaled_bi;
        if (type == BufferedImage.TYPE_CUSTOM) {
            scaled_bi = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
        } else {
            scaled_bi = new BufferedImage(width, height, type);
        }

        Graphics2D g2 = scaled_bi.createGraphics();

        //g2.drawImage(image, at, null);
        g2.drawImage(image.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, null);
        writeImage(scaled_bi, 1, rez);

        g2.dispose();
    }
    //time_resize = System.currentTimeMillis() - time_resize;
    //System.out.print("time_resize=" + (time_resize) + "; ");
}

From source file:com.klwork.common.utils.WebUtils.java

/**
 * ???// w  w w. j  ava 2 s.com
 * @param request
 * @param response
 */
public static void VerificationCode(HttpServletRequest request, HttpServletResponse response) throws Exception {
    response.setHeader("Pragma", "No-cache");
    response.setHeader("Cache-Control", "no-cache");
    response.setDateHeader("Expires", 0);
    // 
    int width = 60, height = 20;
    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

    // ?
    Graphics g = image.getGraphics();

    // ??
    Random random = new Random();

    // 
    g.setColor(getRandColor(200, 250));
    g.fillRect(0, 0, width, height);

    // 
    g.setFont(new Font("Times New Roman", Font.PLAIN, 18));

    // 
    // g.setColor(new Color());
    // g.drawRect(0,0,width-1,height-1);

    // ?155?????
    g.setColor(getRandColor(160, 200));
    for (int i = 0; i < 155; i++) {
        int x = random.nextInt(width);
        int y = random.nextInt(height);
        int xl = random.nextInt(12);
        int yl = random.nextInt(12);
        g.drawLine(x, y, x + xl, y + yl);
    }

    String base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQUSTUVWXYZ0123456789";
    // ????(4?)
    String sRand = "";
    for (int i = 0; i < 4; i++) {
        int start = random.nextInt(base.length());
        String rand = base.substring(start, start + 1);
        sRand = sRand.concat(rand);
        // ??
        g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));
        g.drawString(rand, 13 * i + 6, 16);
    }

    // ??SESSION
    request.getSession().setAttribute("entrymrand", sRand);

    // 
    g.dispose();
    OutputStream out = response.getOutputStream();
    // ?
    ImageIO.write(image, "JPEG", out);

    out.flush();
    out.close();
}