Example usage for java.awt.image BufferedImage getWidth

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

Introduction

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

Prototype

public int getWidth() 

Source Link

Document

Returns the width of the BufferedImage .

Usage

From source file:guru.bubl.service.resources.vertex.VertexImageResource.java

private byte[] resizeImageToMaxWidth(File image, Integer width) {
    try {/*from w w  w  .  j a v a 2  s.  c  o  m*/
        BufferedImage originalImage = ImageIO.read(image);
        originalImage = originalImage.getWidth() > width
                ? Scalr.resize(originalImage, Scalr.Method.QUALITY, Scalr.Mode.FIT_TO_WIDTH, width, width)
                : ImageIO.read(image);
        //To save with original ratio uncomment next line and comment the above.
        //originalImage= Scalr.resize(originalImage, 153, 128);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(originalImage, "png", baos);
        baos.flush();
        byte[] imageInByte = baos.toByteArray();
        baos.close();
        return imageInByte;
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.xlrnet.tibaija.tools.fontgen.FontgenApplication.java

private Symbol importFile(Path path, Font font, String fontIdentifier) throws IOException, ImageReadException {
    LOGGER.info("Importing file {} ...", path.toAbsolutePath());

    BufferedImage image = Imaging.getBufferedImage(Files.newInputStream(path));
    int width = image.getWidth();
    int height = image.getHeight();
    int finalWidth = width / 2;
    int finalHeight = height / 2;

    if (width % 2 != 0 || height % 2 != 0) {
        LOGGER.warn("Width and height must be multiple of 2");
        return null;
    }//from  w  w w.ja  va2  s.  co  m

    Symbol symbol = new Symbol();
    PixelState[][] pixelStates = new PixelState[finalHeight][finalWidth];
    Raster imageData = image.getData();

    for (int y = 0; y < finalHeight; y++) {
        for (int x = 0; x < finalWidth; x++) {
            int sample = imageData.getSample(x * 2, y * 2, 0);
            PixelState pixelState = sample == 0 ? PixelState.ON : PixelState.OFF;
            pixelStates[y][x] = pixelState;
        }
    }

    symbol.setData(pixelStates);
    return symbol;
}

From source file:jadx.core.utils.android.Res9patchStreamDecoder.java

public void decode(InputStream in, OutputStream out) throws JadxException {
    try {/*  w  w  w . jav a 2 s . c o m*/
        byte[] data = IOUtils.toByteArray(in);

        BufferedImage im = ImageIO.read(new ByteArrayInputStream(data));
        int w = im.getWidth(), h = im.getHeight();

        BufferedImage im2 = new BufferedImage(w + 2, h + 2, BufferedImage.TYPE_INT_ARGB);
        im2.createGraphics().drawImage(im, 1, 1, w, h, null);

        NinePatch np = getNinePatch(data);
        drawHLine(im2, h + 1, np.padLeft + 1, w - np.padRight);
        drawVLine(im2, w + 1, np.padTop + 1, h - np.padBottom);

        int[] xDivs = np.xDivs;
        for (int i = 0; i < xDivs.length; i += 2) {
            drawHLine(im2, 0, xDivs[i] + 1, xDivs[i + 1]);
        }

        int[] yDivs = np.yDivs;
        for (int i = 0; i < yDivs.length; i += 2) {
            drawVLine(im2, 0, yDivs[i] + 1, yDivs[i + 1]);
        }

        ImageIO.write(im2, "png", out);
    } catch (IOException | NullPointerException ex) {
        throw new JadxException(ex.toString());
    }
}

From source file:com.github.pitzcarraldo.dissimilar.Dissimilar.java

/**
 * Calculate the PSNR between two files/*from   w  w  w .  ja v a2  s  .  c o m*/
 * @param pOne first image to compare
 * @param pTwo second image to compare
 * @return calculated psnr
 */
public static double calcPSNR(final File pOne, final File pTwo) {
    BufferedImage imageOne = null;
    try {
        imageOne = Imaging.getBufferedImage(pOne);
    } catch (IOException e) {
        printError(pOne, false, false, pTwo, false);
        return -1;
    } catch (NullPointerException e) {
        printError(pOne, false, false, pTwo, false);
        return -1;
    } catch (ImageReadException e) {
        printError(pOne, false, false, pTwo, false);
        return -1;
    }

    //getRGB only returns 8 bits per component, so what about 16-bit images? 
    final int[] oneA = imageOne.getRGB(0, 0, imageOne.getWidth(), imageOne.getHeight(), null, 0,
            imageOne.getWidth());
    final boolean greyscale = (imageOne.getType() == BufferedImage.TYPE_BYTE_GRAY
            || imageOne.getType() == BufferedImage.TYPE_USHORT_GRAY);
    imageOne = null;

    BufferedImage imageTwo = null;
    try {
        imageTwo = Imaging.getBufferedImage(pTwo);
    } catch (IOException e) {
        printError(pOne, true, true, pTwo, false);
        return -1;
    } catch (NullPointerException e) {
        printError(pOne, true, true, pTwo, false);
        return -1;
    } catch (ImageReadException e) {
        printError(pOne, true, true, pTwo, false);
        return -1;
    }

    //getRGB only returns 8 bits per component, so what about 16-bit images? 
    final int[] twoA = imageTwo.getRGB(0, 0, imageTwo.getWidth(), imageTwo.getHeight(), null, 0,
            imageTwo.getWidth());
    imageTwo = null;

    final double psnr = calcPSNR(oneA, twoA, greyscale);

    return psnr;
}

From source file:edu.ku.brc.util.thumbnails.ImageThumbnailGenerator.java

/**
 * Creates a thumbnail of the given image bytes.
 * //from   ww  w  . ja  v  a  2s  .c om
 * @param originalImageData the bytes of the input file
 * @param doHighQuality higher quality thumbnail (slower)
 * @return the bytes of the output file
 * @throws IOException if any IO errors occur during generation or storing the output
 */
public byte[] generateThumbnail(final byte[] originalImageData, final boolean doHighQuality)
        throws IOException {
    ByteArrayInputStream inputStr = new ByteArrayInputStream(originalImageData);
    if (inputStr != null) {
        BufferedImage orig = ImageIO.read(inputStr);
        if (orig != null) {
            if (orig.getHeight() < maxSize.getHeight() && orig.getWidth() < maxSize.getWidth()) {
                // there's no need to do anything since the original is already under the max size
                return originalImageData;
            }

            byte[] scaledImgData = GraphicsUtils.scaleImage(orig, maxSize.height, maxSize.width, true,
                    doHighQuality);
            return scaledImgData;
        }
    }
    return null;
}

From source file:com.github.pitzcarraldo.dissimilar.Dissimilar.java

/**
 * Calculate the SSIM between two files/*from w ww  .  ja  v a2 s.co m*/
 * @param pOne first image to compare
 * @param pTwo second image to compare
 * @param pHeatMapFilename ssim heat map image filename (can be null)
 * @param pMin list for return value - ssim minimum (can be null)
 * @param pVariance list for return value - ssim variance (can be null)
 * @return calculated ssim
 */
public static double calcSSIM(final File pOne, final File pTwo, final String pHeatMapFilename,
        List<Double> pMin, List<Double> pVariance) {

    BufferedImage imageOne = null;
    try {
        imageOne = Imaging.getBufferedImage(pOne);
    } catch (IOException e) {
        printError(pOne, false, false, pTwo, false);
        return -1;
    } catch (NullPointerException e) {
        printError(pOne, false, false, pTwo, false);
        return -1;
    } catch (ImageReadException e) {
        printError(pOne, false, false, pTwo, false);
        return -1;
    }

    //getRGB only returns 8 bits per component, so what about 16-bit images? 
    final int[] oneA = imageOne.getRGB(0, 0, imageOne.getWidth(), imageOne.getHeight(), null, 0,
            imageOne.getWidth());
    final int width = imageOne.getWidth();
    final int height = imageOne.getHeight();
    final boolean greyscale = (imageOne.getType() == BufferedImage.TYPE_BYTE_GRAY
            || imageOne.getType() == BufferedImage.TYPE_USHORT_GRAY);
    imageOne = null;

    BufferedImage imageTwo = null;
    try {
        imageTwo = Imaging.getBufferedImage(pTwo);
    } catch (IOException e) {
        printError(pOne, true, true, pTwo, false);
        return -1;
    } catch (NullPointerException e) {
        printError(pOne, true, true, pTwo, false);
        return -1;
    } catch (ImageReadException e) {
        printError(pOne, true, true, pTwo, false);
        return -1;
    }

    //getRGB only returns 8 bits per component, so what about 16-bit images? 
    final int[] twoA = imageTwo.getRGB(0, 0, imageTwo.getWidth(), imageTwo.getHeight(), null, 0,
            imageTwo.getWidth());
    imageTwo = null;

    final double ssim = calcSSIM(oneA, twoA, width, height, greyscale, pHeatMapFilename, pMin, pVariance);

    return ssim;
}

From source file:brut.androlib.res.decoder.Res9patchStreamDecoder.java

@Override
public void decode(InputStream in, OutputStream out) throws AndrolibException {
    try {//from  w w w.  j  av a2 s  .co  m
        byte[] data = IOUtils.toByteArray(in);

        BufferedImage im = ImageIO.read(new ByteArrayInputStream(data));
        int w = im.getWidth(), h = im.getHeight();

        ImageTypeSpecifier its = ImageTypeSpecifier.createFromRenderedImage(im);
        BufferedImage im2 = its.createBufferedImage(w + 2, h + 2);

        im2.getRaster().setRect(1, 1, im.getRaster());
        NinePatch np = getNinePatch(data);
        drawHLine(im2, h + 1, np.padLeft + 1, w - np.padRight);
        drawVLine(im2, w + 1, np.padTop + 1, h - np.padBottom);

        int[] xDivs = np.xDivs;
        for (int i = 0; i < xDivs.length; i += 2) {
            drawHLine(im2, 0, xDivs[i] + 1, xDivs[i + 1]);
        }

        int[] yDivs = np.yDivs;
        for (int i = 0; i < yDivs.length; i += 2) {
            drawVLine(im2, 0, yDivs[i] + 1, yDivs[i + 1]);
        }

        ImageIO.write(im2, "png", out);
    } catch (IOException ex) {
        throw new AndrolibException(ex);
    } catch (NullPointerException ex) {
        // In my case this was triggered because a .png file was
        // containing a html document instead of an image.
        // This could be more verbose and try to MIME ?
        throw new AndrolibException(ex);
    }
}

From source file:com.flexive.shared.media.impl.FxMediaNativeEngine.java

/**
 * Scale an image and return the dimensions (width and height) as int array
 *
 * @param original  original file//from  w w w . j a  v  a2  s.  c om
 * @param scaled    scaled file
 * @param extension extension
 * @param width     desired width
 * @param height    desired height
 * @return actual width ([0]) and height ([1]) of scaled image
 * @throws FxApplicationException on errors
 */
public static int[] scale(File original, File scaled, String extension, int width, int height)
        throws FxApplicationException {
    if (HEADLESS && FxMediaImageMagickEngine.IM_AVAILABLE && ".GIF".equals(extension)) {
        //native headless engine can't handle gif transparency ... so if we have IM we use it, else
        //transparent pixels will be black
        return FxMediaImageMagickEngine.scale(original, scaled, extension, width, height);
    }
    BufferedImage bi;
    try {
        bi = ImageIO.read(original);
    } catch (Exception e) {
        LOG.info("Failed to read " + original.getName() + " using ImageIO, trying sanselan");
        try {
            bi = Sanselan.getBufferedImage(original);
        } catch (Exception e1) {
            throw new FxApplicationException(LOG, "ex.media.readFallback.error", original.getName(), extension,
                    e.getMessage(), e1.getMessage());
        }
    }
    BufferedImage bi2 = scale(bi, width, height);

    String eMsg;
    boolean fallback;
    try {
        fallback = !ImageIO.write(bi2, extension.substring(1), scaled);
        eMsg = "No ImageIO writer found.";
    } catch (Exception e) {
        eMsg = e.getMessage();
        fallback = true;
    }
    if (fallback) {
        try {
            Sanselan.writeImage(bi2, scaled, getImageFormatByExtension(extension), new HashMap());
        } catch (Exception e1) {
            throw new FxApplicationException(LOG, "ex.media.write.error", scaled.getName(), extension,
                    eMsg + ", " + e1.getMessage());
        }
    }
    return new int[] { bi2.getWidth(), bi2.getHeight() };
}

From source file:edu.cornell.mannlib.vitro.webapp.controller.freemarker.ImageUploadThumbnailer.java

private CropRectangle limitCropRectangleToImageBounds(BufferedImage image, CropRectangle crop) {

    int imageWidth = image.getWidth();
    int imageHeight = image.getHeight();

    // Ensure that x and y are at least zero, but not big enough to push the
    // crop rectangle out of the image.
    int greatestX = imageWidth - MINIMUM_CROP_SIZE;
    int greatestY = imageHeight - MINIMUM_CROP_SIZE;
    int x = Math.max(0, Math.min(greatestX, Math.abs(crop.x)));
    int y = Math.max(0, Math.min(greatestY, Math.abs(crop.y)));

    // Ensure that width and height are at least as big as the minimum, but
    // no so big as to extend beyond the image.
    int greatestW = imageWidth - x;
    int greatestH = imageHeight - y;
    int w = Math.max(MINIMUM_CROP_SIZE, Math.min(greatestW, crop.width));
    int h = Math.max(MINIMUM_CROP_SIZE, Math.min(greatestH, crop.height));

    return new CropRectangle(x, y, h, w);
}

From source file:ddf.catalog.transformer.OverlayMetacardTransformerTest.java

@Test
public void testOverlaySquishedHeight() throws Exception {
    final MetacardImpl metacard = getMetacard();
    metacard.setLocation("POLYGON ((0 0, 1 0, 1 -0.1, 0 -0.1, 0 0))");
    final BinaryContent content = transform(metacard, null);

    final BufferedImage originalImage = getImage(getImageBytes());
    final BufferedImage overlayImage = getImage(content.getByteArray());

    assertThat(overlayImage.getWidth(), equalTo(originalImage.getWidth()));
    assertThat(overlayImage.getHeight(), lessThan(originalImage.getHeight()));
}