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:blusunrize.immersiveengineering.client.render.IEShaderLayerCompositeTexture.java

@Override
public void loadTexture(IResourceManager resourceManager) {
    this.deleteGlTexture();
    IResource iresource = null;/*w  w w .j av  a2s .  co  m*/
    BufferedImage bufferedimage;
    BufferedImage scaledImage;
    label255: {
        try {
            iresource = resourceManager.getResource(this.canvasTexture);
            BufferedImage canvasImage = TextureUtil.readBufferedImage(iresource.getInputStream());
            int imageType = canvasImage.getType();
            if (imageType == 0)
                imageType = 6;
            int canvasWidth = canvasImage.getWidth();
            int canvasHeight = canvasImage.getHeight();

            bufferedimage = new BufferedImage(canvasWidth, canvasHeight, imageType);
            int layer = 0;

            while (true) {
                if (layer >= 17 || layer >= this.layers.length)
                    break label255;

                IResource iresource1 = null;

                try {
                    String texPath = this.layers[layer].getTexture().getPath();

                    if (!texPath.startsWith("textures/"))
                        texPath = "textures/" + texPath;
                    if (!texPath.endsWith(".png"))
                        texPath += ".png";
                    String texture = this.layers[layer].getTexture().getNamespace() + ":" + texPath;
                    int colour = this.layers[layer].getColour();

                    iresource1 = resourceManager.getResource(new ResourceLocation(texture));
                    BufferedImage texureImage = TextureUtil.readBufferedImage(iresource1.getInputStream());

                    scaledImage = new BufferedImage(canvasWidth, canvasHeight, imageType);

                    float[] mod = { (colour >> 16 & 255) / 255f, (colour >> 8 & 255) / 255f,
                            (colour & 255) / 255f, (colour >> 24 & 255) / 255f };

                    IntFunction<Integer> uInterpolate = uIn -> uIn;
                    IntFunction<Integer> vInterpolate = vIn -> vIn;

                    int bufImg2Size = Math.min(texureImage.getWidth(), texureImage.getHeight());

                    int uMin = 0;
                    int vMin = 0;
                    int uMax = canvasWidth;
                    int vMax = canvasHeight;

                    final double[] texBounds = this.layers[layer].getTextureBounds();
                    if (texBounds != null) {
                        final double uOffset = texBounds[0] * canvasWidth;
                        final double vOffset = texBounds[1] * canvasHeight;
                        final double uScale = bufImg2Size / ((texBounds[2] - texBounds[0]) * canvasWidth);
                        final double vScale = bufImg2Size / ((texBounds[3] - texBounds[1]) * canvasHeight);
                        uInterpolate = uIn -> (int) Math.round((uIn - uOffset) * uScale);
                        vInterpolate = vIn -> (int) Math.round((vIn - vOffset) * vScale);
                        uMin = (int) uOffset;
                        vMin = (int) vOffset;
                        uMax = (int) (texBounds[2] * canvasWidth);
                        vMax = (int) (texBounds[3] * canvasHeight);
                    }

                    try {
                        for (int v = vMin; v < vMax; ++v)
                            for (int u = uMin; u < uMax; ++u) {
                                int interU = uInterpolate.apply(u) % bufImg2Size;
                                int interV = vInterpolate.apply(v) % bufImg2Size;

                                int iRGB = texureImage.getRGB(interU, interV);

                                float[] rgb = { (iRGB >> 16 & 255) / 255f, (iRGB >> 8 & 255) / 255f,
                                        (iRGB & 255) / 255f, (iRGB >> 24 & 255) / 255f };
                                if ((iRGB & -16777216) != 0) {
                                    int iNoise = canvasImage.getRGB(u, v);
                                    float[] noise = { (iNoise >> 16 & 255) / 255f, (iNoise >> 8 & 255) / 255f,
                                            (iNoise & 255) / 255f, (iNoise >> 24 & 255) / 255f };

                                    for (int m = 0; m < 4; m++)
                                        rgb[m] = rgb[m] * mod[m] * noise[m];
                                    int[] irgb = { (int) (rgb[0] * 255), (int) (rgb[1] * 255),
                                            (int) (rgb[2] * 255), (int) (rgb[3] * 255) };

                                    int i2 = (irgb[0] << 16) + (irgb[1] << 8) + (irgb[2]) + (irgb[3] << 24);
                                    scaledImage.setRGB(u, v, i2);
                                }
                            }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    bufferedimage.getGraphics().drawImage(scaledImage, 0, 0, null);
                } finally {
                    IOUtils.closeQuietly(iresource1);
                }

                ++layer;
            }
        } catch (IOException ioexception) {
            IELogger.error("Couldn't load layered image", ioexception);
        } finally {
            IOUtils.closeQuietly(iresource);
        }

        return;
    }
    TextureUtil.uploadTextureImage(this.getGlTextureId(), bufferedimage);
}

From source file:client.ServiceRequester.java

public HttpEntity<byte[]> createRequestHeaders(BufferedImage image) {
    byte[] imageBytes = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
    MultiValueMap<String, String> headers = new LinkedMultiValueMap<String, String>();

    headers.add("imageType", String.valueOf(image.getType()));
    headers.add("imageWidth", String.valueOf(image.getWidth()));
    headers.add("imageHeight", String.valueOf(image.getHeight()));

    return new HttpEntity<byte[]>(imageBytes, headers);
}

From source file:ImageOpByRomain.java

/**
 * <p>//from www  .j a va 2s.  c  o m
 * Returns an array of pixels, stored as integers, from a
 * <code>BufferedImage</code>. The pixels are grabbed from a rectangular
 * area defined by a location and two dimensions. Calling this method on an
 * image of type different from <code>BufferedImage.TYPE_INT_ARGB</code> and
 * <code>BufferedImage.TYPE_INT_RGB</code> will unmanage the image.
 * </p>
 * 
 * @param img
 *            the source image
 * @param x
 *            the x location at which to start grabbing pixels
 * @param y
 *            the y location at which to start grabbing pixels
 * @param w
 *            the width of the rectangle of pixels to grab
 * @param h
 *            the height of the rectangle of pixels to grab
 * @param pixels
 *            a pre-allocated array of pixels of size w*h; can be null
 * @return <code>pixels</code> if non-null, a new array of integers
 *         otherwise
 * @throws IllegalArgumentException
 *             is <code>pixels</code> is non-null and of length &lt; w*h
 */
public static int[] getPixels(BufferedImage img, int x, int y, int w, int h, int[] pixels) {
    if (w == 0 || h == 0) {
        return new int[0];
    }

    if (pixels == null) {
        pixels = new int[w * h];
    } else if (pixels.length < w * h) {
        throw new IllegalArgumentException("pixels array must have a length" + " >= w*h");
    }

    int imageType = img.getType();
    if (imageType == BufferedImage.TYPE_INT_ARGB || imageType == BufferedImage.TYPE_INT_RGB) {
        Raster raster = img.getRaster();
        return (int[]) raster.getDataElements(x, y, w, h, pixels);
    }

    // Unmanages the image
    return img.getRGB(x, y, w, h, pixels, 0, w);
}

From source file:com.teasoft.teavote.controller.ElectionInfoController.java

@RequestMapping(value = "api/teavote/election-info", method = RequestMethod.POST)
@ResponseBody/*from w w w .  java 2 s  .c  o m*/
public JSONResponse saveElectionInfo(@RequestParam("logo") MultipartFile file,
        @RequestParam("commissioner") String commissioner, @RequestParam("orgName") String orgName,
        @RequestParam("electionDate") String electionDate, @RequestParam("startTime") String startTime,
        @RequestParam("endTime") String endTime, @RequestParam("pollingStation") String pollingStation,
        @RequestParam("startTimeInMillis") String startTimeInMillis,
        @RequestParam("endTimeInMillis") String endTimeInMillis, HttpServletRequest request) throws Exception {

    JSONResponse jSONResponse = new JSONResponse();
    //Candidate candidate = new Candidate();
    Map<String, String> errorMessages = new HashMap<>();

    if (!file.isEmpty()) {
        BufferedImage image = ImageIO.read(file.getInputStream());
        Integer width = image.getWidth();
        Integer height = image.getHeight();

        if (Math.abs(width - height) > MAX_IMAGE_DIM_DIFF) {
            errorMessages.put("image", "Invalid Image Dimension - Max abs(Width - height) must be 50 or less");
        } else {
            //Resize image
            BufferedImage originalImage = ImageIO.read(file.getInputStream());
            int type = originalImage.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : originalImage.getType();

            BufferedImage resizeImagePng = resizeImage(originalImage, type);
            ConfigLocation configLocation = new ConfigLocation();
            //String rootPath = request.getSession().getServletContext().getRealPath("/");
            File serverFile = new File(configLocation.getConfigPath() + File.separator + "teavote-logo.jpg");

            switch (file.getContentType()) {
            case "image/png":
                ImageIO.write(resizeImagePng, "png", serverFile);
                break;
            case "image/jpeg":
                ImageIO.write(resizeImagePng, "jpg", serverFile);
                break;
            default:
                ImageIO.write(resizeImagePng, "png", serverFile);
                break;
            }
        }
    } else {
        //            errorMessages.put("image", "File Empty");
    }

    //Load properties
    Properties prop = appProp.getProperties();
    ConfigLocation configLocation = new ConfigLocation();
    prop.load(configLocation.getExternalProperties());

    prop.setProperty("teavote.orgName", orgName);
    prop.setProperty("teavote.commissioner", commissioner);
    prop.setProperty("teavote.electionDate", electionDate);
    prop.setProperty("teavote.startTime", startTime);
    prop.setProperty("teavote.endTime", endTime);
    prop.setProperty("teavote.pollingStation", pollingStation);
    prop.setProperty("teavote.startTimeInMillis", startTimeInMillis);
    prop.setProperty("teavote.endTimeInMillis", endTimeInMillis);

    File f = new File(configLocation.getConfigPath() + File.separator + "application.properties");
    OutputStream out = new FileOutputStream(f);
    DefaultPropertiesPersister p = new DefaultPropertiesPersister();
    p.store(prop, out, "Header Comment");

    if (errorMessages.isEmpty()) {
        return new JSONResponse(true, 0, null, Enums.JSONResponseMessage.SUCCESS.toString());
    }

    return new JSONResponse(false, 0, errorMessages, Enums.JSONResponseMessage.SERVER_ERROR.toString());
}

From source file:bachelorthesis.ocr.domain.DomainFacade.java

private Captcha createCaptcha(String buildString, int width, int height) throws RuntimeException {
    try {//from ww  w .  j a  v  a 2  s .  co  m
        CaptchaBuilder captchaBuilder = new CaptchaBuilder(40, 50, buildString);
        Captcha c = captchaBuilder.buildCaptcha();
        BufferedImage img = c.getImage();

        // check if size == the default size (40*50) if not scale
        if (width != 40 || height != 50) {
            BufferedImage resized = new BufferedImage(width, height, img.getType());
            Graphics2D g = resized.createGraphics();
            g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            g.drawImage(img, 0, 0, width, height, 0, 0, img.getWidth(), img.getHeight(), null);
            g.dispose();

            //build new CAPTCHA WITH THE NEW IMAGE SIZE
            c = new Captcha(c.getBuildSequence(), c.getAnswer(), c.isCaseSensative(), img, new Date());
        }

        return c;

    } catch (ParseException ex) {
        Logger.getLogger(DomainFacade.class.getName()).log(Level.SEVERE, null, ex);
        throw new RuntimeException("error creating CAPTCHA");
    }
}

From source file:com.ackpdfbox.app.imageio.TIFFUtil.java

/**
 * Updates the given ImageIO metadata with Sun's custom TIFF tags, as described in
 * the <a href="https://svn.apache.org/repos/asf/xmlgraphics/commons/tags/commons-1_3_1/src/java/org/apache/xmlgraphics/image/writer/imageio/ImageIOTIFFImageWriter.java">org.apache.xmlgraphics.image.writer.ImageIOTIFFImageWriter
 * sources</a>, /*from w ww.  j a va 2s . co  m*/
 * the <a href="http://download.java.net/media/jai-imageio/javadoc/1.0_01/com/sun/media/imageio/plugins/tiff/package-summary.html">com.sun.media.imageio.plugins.tiff
 * package javadoc</a>
 * and the <a href="http://partners.adobe.com/public/developer/tiff/index.html">TIFF
 * specification</a>.
 *
 * @param image buffered image which will be written
 * @param metadata ImageIO metadata
 * @param dpi image dots per inch
 * @throws IIOInvalidTreeException if something goes wrong
 */
static void updateMetadata(IIOMetadata metadata, BufferedImage image, int dpi) throws IIOInvalidTreeException {
    debugLogMetadata(metadata, SUN_TIFF_FORMAT);

    if (!SUN_TIFF_FORMAT.equals(metadata.getNativeMetadataFormatName())) {
        LOG.debug("Using unknown TIFF image writer: " + metadata.getNativeMetadataFormatName());
        return;
    }

    IIOMetadataNode root = new IIOMetadataNode(SUN_TIFF_FORMAT);
    IIOMetadataNode ifd;
    if (root.getElementsByTagName("TIFFIFD").getLength() == 0) {
        ifd = new IIOMetadataNode("TIFFIFD");
        ifd.setAttribute("tagSets", tagSetClassName);
        root.appendChild(ifd);
    } else {
        ifd = (IIOMetadataNode) root.getElementsByTagName("TIFFIFD").item(0);
    }

    // standard metadata does not work, so we set the DPI manually
    ifd.appendChild(createRationalField(282, "XResolution", dpi, 1));
    ifd.appendChild(createRationalField(283, "YResolution", dpi, 1));
    ifd.appendChild(createShortField(296, "ResolutionUnit", 2)); // Inch

    ifd.appendChild(createLongField(278, "RowsPerStrip", image.getHeight()));
    ifd.appendChild(createAsciiField(305, "Software", "PDFBOX"));

    if (image.getType() == BufferedImage.TYPE_BYTE_BINARY && image.getColorModel().getPixelSize() == 1) {
        // set PhotometricInterpretation WhiteIsZero
        // because of bug in Windows XP preview
        ifd.appendChild(createShortField(262, "PhotometricInterpretation", 0));
    }

    metadata.mergeTree(SUN_TIFF_FORMAT, root);

    debugLogMetadata(metadata, SUN_TIFF_FORMAT);
}

From source file:com.aegon.pdf2tiff.TIFFUtil.java

/**
 * Updates the given ImageIO metadata with Sun's custom TIFF tags.
 * {@see https://svn.apache.org/repos/asf/xmlgraphics/commons/tags/commons-1_3_1/src/java/org/
 *       apache/xmlgraphics/image/writer/imageio/ImageIOTIFFImageWriter.java}
 * {@see http://download.java.net/media/jai-imageio/javadoc/1.0_01/com/sun/media/imageio/
 *       plugins/tiff/package-summary.html}
 * {@see http://partners.adobe.com/public/developer/tiff/index.html}
 * @param image buffered image which will be written
 * @param metadata ImageIO metadata/*w  w w.j  ava2  s  . com*/
 * @param dpi image dots per inch
 */
public static void updateMetadata(IIOMetadata metadata, BufferedImage image, int dpi) {
    debugLogMetadata(metadata, SUN_TIFF_FORMAT);

    if (!SUN_TIFF_FORMAT.equals(metadata.getNativeMetadataFormatName())) {
        LOG.debug("Using unknown TIFF image writer: " + metadata.getNativeMetadataFormatName());
        return;
    }

    IIOMetadataNode root = new IIOMetadataNode(SUN_TIFF_FORMAT);
    IIOMetadataNode ifd;
    if (root.getElementsByTagName("TIFFIFD").getLength() == 0) {
        ifd = new IIOMetadataNode("TIFFIFD");
        ifd.setAttribute("tagSets", "com.sun.media.imageio.plugins.tiff.BaselineTIFFTagSet");
        root.appendChild(ifd);
    } else {
        ifd = (IIOMetadataNode) root.getElementsByTagName("TIFFIFD").item(0);
    }

    // standard metadata does not work, so we set the DPI manually
    ifd.appendChild(createRationalField(282, "XResolution", dpi, 1));
    ifd.appendChild(createRationalField(283, "YResolution", dpi, 1));
    ifd.appendChild(createShortField(296, "ResolutionUnit", 2)); // Inch

    ifd.appendChild(createLongField(278, "RowsPerStrip", image.getHeight()));
    ifd.appendChild(createAsciiField(305, "Software", "PDFBOX"));

    if (image.getType() == BufferedImage.TYPE_BYTE_BINARY && image.getColorModel().getPixelSize() == 1) {
        // set PhotometricInterpretation WhiteIsZero
        // because of bug in Windows XP preview
        ifd.appendChild(createShortField(262, "PhotometricInterpretation", 0));
    }

    try {
        metadata.mergeTree(SUN_TIFF_FORMAT, root);
    } catch (IIOInvalidTreeException e) {
        // should never happen
        throw new RuntimeException(e);
    }

    debugLogMetadata(metadata, SUN_TIFF_FORMAT);
}

From source file:com.salesmanager.core.util.ProductImageUtil.java

public BufferedImage resize(BufferedImage image, int width, int height) {
    int type = image.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : image.getType();
    BufferedImage resizedImage = new BufferedImage(width, height, type);
    Graphics2D g = resizedImage.createGraphics();
    g.setComposite(AlphaComposite.Src);
    g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
    g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g.drawImage(image, 0, 0, width, height, null);
    g.dispose();//www .j a v a  2s  .  c o  m
    return resizedImage;
}

From source file:apiserver.services.images.services.jhlabs.MaskFilterService.java

public Object doFilter(Message<?> message) throws MessageConfigException {
    MaskJob props = (MaskJob) message.getPayload();

    Object maskImage = props.getMask();

    try {//from   w  ww . j  av  a2s  . co m
        BufferedImage bufferedImage = props.getBufferedImage();
        if (bufferedImage == null) {
            throw new MessageConfigException(MessageConfigException.MISSING_PROPERTY);
        }

        BufferedImage destImage = new BufferedImage(bufferedImage.getWidth(), bufferedImage.getHeight(),
                bufferedImage.getType());

        //run filter
        ApplyMaskFilter filter = new ApplyMaskFilter();
        filter.setDestination(destImage);

        filter.setMaskImage(bufferedImage);

        BufferedImage outFile = filter.filter(bufferedImage, null);

        props.setBufferedImage(outFile);
        return message;
    } catch (Throwable e) {
        //log.error(e.getMessage(), e);
        throw new RuntimeException(e);
    }
}

From source file:de.thm.arsnova.util.ImageUtils.java

/**
 * Rescales an image represented by a Base64-encoded {@link String}
 *
 * @param originalImageString//from w w w  .j a  v  a  2s.  c  om
 *            The original image represented by a Base64-encoded
 *            {@link String}
 * @param width
 *            the new width
 * @param height
 *            the new height
 * @return The rescaled Image as Base64-encoded {@link String}, returns null
 *         if the passed-on image isn't in a valid format (a Base64-Image).
 */
String createCover(String originalImageString, final int width, final int height) {
    if (!isBase64EncodedImage(originalImageString)) {
        return null;
    } else {
        final String[] imgInfo = extractImageInfo(originalImageString);

        // imgInfo isn't null and contains two fields, this is checked by "isBase64EncodedImage"-Method
        final String extension = imgInfo[0];
        final String base64String = imgInfo[1];

        byte[] imageData = Base64.decodeBase64(base64String);
        try (final ByteArrayInputStream bais = new ByteArrayInputStream(imageData);
                final ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            BufferedImage originalImage = ImageIO.read(bais);
            BufferedImage newImage = new BufferedImage(width, height, originalImage.getType());
            Graphics2D g = newImage.createGraphics();

            final double ratio = ((double) originalImage.getWidth()) / ((double) originalImage.getHeight());

            int x = 0, y = 0, w = width, h = height;
            if (originalImage.getWidth() > originalImage.getHeight()) {
                final int newWidth = (int) Math.round((float) height * ratio);
                x = -(newWidth - width) >> 1;
                w = newWidth;
            } else if (originalImage.getWidth() < originalImage.getHeight()) {
                final int newHeight = (int) Math.round((float) width / ratio);
                y = -(newHeight - height) >> 1;
                h = newHeight;
            }
            g.drawImage(originalImage, x, y, w, h, null);
            g.dispose();

            StringBuilder result = new StringBuilder();
            result.append(IMAGE_PREFIX_START);
            result.append(extension);
            result.append(IMAGE_PREFIX_MIDDLE);

            ImageIO.write(newImage, extension, baos);

            baos.flush();

            result.append(Base64.encodeBase64String(baos.toByteArray()));

            return result.toString();
        } catch (IOException e) {
            logger.error(e.getLocalizedMessage());
            return null;
        }
    }
}