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:com.trailmagic.image.util.ReplaceImageManifestation.java

public void replaceManifestations(final String ownerName, final String rollName, final String importDir) {
    hibernateTemplate.execute(new HibernateCallback() {
        public Object doInHibernate(Session session) {
            try {
                User owner = userRepository.getByScreenName(ownerName);
                ImageGroup roll = imageGroupRepository.getRollByOwnerAndName(owner, rollName);
                s_log.info("Processing roll: " + roll.getName());
                for (ImageFrame frame : roll.getFrames()) {
                    Image image = frame.getImage();
                    for (ImageManifestation mf : image.getManifestations()) {

                        String filename = importDir + File.separator + mf.getName();
                        File srcFile = new File(filename);
                        s_log.info("Importing " + srcFile.getPath());
                        if (srcFile.length() > Integer.MAX_VALUE) {
                            s_log.info("File is too big...skipping " + srcFile.getPath());
                            throw new RuntimeException("File too big");
                        }/*w  w w  .j  a v a2s.  c  o m*/

                        // first read the file to get the size
                        FileInputStream fis = new FileInputStream(srcFile);
                        BufferedImage bi = ImageIO.read(fis);
                        mf.setHeight(bi.getHeight());
                        mf.setWidth(bi.getWidth());
                        s_log.info("New size is " + mf.getHeight() + "x" + mf.getWidth());
                        session.saveOrUpdate(mf);
                        fis.close();

                        fis = new FileInputStream(srcFile);
                        HeavyImageManifestation heavyMf = imfFactory.getHeavyById(mf.getId());
                        heavyMf.setData(Hibernate.createBlob(fis));
                        session.saveOrUpdate(heavyMf);

                        // open the file again to get the size :(

                        s_log.info("ImageManifestation saved: " + heavyMf.getName() + " (" + heavyMf.getId()
                                + ")" + "...flushing session and evicting " + "manifestation.");

                        synchronized (session) {
                            session.flush();
                            session.evict(heavyMf);
                        }

                        // looks like fis has to be open for the flush
                        fis.close();

                    }
                }
            } catch (Exception e) {
                s_log.error("Error replacing manifestations ", e);
            }
            return null;
        }
    });
}

From source file:edu.emory.library.tast.images.ThumbnailServlet.java

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    // location of images
    String baseUrl = AppConfig.getConfiguration().getString(AppConfig.IMAGES_URL);
    baseUrl = StringUtils.trimEnd(baseUrl, '/');

    // image name and size
    String imageFileName = request.getParameter("i");
    int thumbnailWidth = Integer.parseInt(request.getParameter("w"));
    int thumbnailHeight = Integer.parseInt(request.getParameter("h"));

    // image dir//w w  w  .  j av  a2  s.  co m
    String imagesDir = AppConfig.getConfiguration().getString(AppConfig.IMAGES_DIRECTORY);

    // create the thumbnail name
    String thumbnailFileName = FilenameUtils.getBaseName(imageFileName) + "-" + thumbnailWidth + "x"
            + thumbnailHeight + ".png";

    // does it exist?
    File thumbnailFile = new File(imagesDir, thumbnailFileName);
    if (thumbnailFile.exists()) {
        response.sendRedirect(baseUrl + "/" + thumbnailFileName);
        return;
    }

    // read the image
    File imageFile = new File(imagesDir, imageFileName);
    BufferedImage image = ImageIO.read(imageFile);
    int imageWidth = image.getWidth();
    int imageHeight = image.getHeight();
    BufferedImage imageCopy = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_RGB);
    imageCopy.getGraphics().drawImage(image, 0, 0, imageWidth, imageHeight, 0, 0, imageWidth, imageHeight,
            null);

    // height is calculated automatically
    if (thumbnailHeight == 0)
        thumbnailHeight = (int) ((double) thumbnailWidth / (double) imageWidth * (double) imageHeight);

    // width is calculated automatically
    if (thumbnailWidth == 0)
        thumbnailWidth = (int) ((double) thumbnailHeight / (double) imageHeight * (double) imageWidth);

    // create an empty thumbnail
    BufferedImage thumbnail = new BufferedImage(thumbnailWidth, thumbnailHeight, BufferedImage.TYPE_INT_RGB);
    Graphics2D gr = thumbnail.createGraphics();
    gr.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
    gr.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);

    // determine the piece of the image which we want to clip
    int clipX1, clipX2, clipY1, clipY2;
    if (imageWidth * thumbnailHeight > thumbnailWidth * imageHeight) {

        int clipWidth = (int) Math
                .round(((double) thumbnailWidth / (double) thumbnailHeight) * (double) imageHeight);
        int imgCenterX = imageWidth / 2;
        clipX1 = imgCenterX - clipWidth / 2;
        clipX2 = imgCenterX + clipWidth / 2;
        clipY1 = 0;
        clipY2 = imageHeight;
    } else {
        int clipHeight = (int) Math
                .round(((double) thumbnailHeight / (double) thumbnailWidth) * (double) imageWidth);
        int imgCenterY = imageHeight / 2;
        clipX1 = 0;
        clipX2 = imageWidth;
        clipY1 = imgCenterY - clipHeight / 2;
        clipY2 = imgCenterY + clipHeight / 2;
    }

    // we filter the image first to get better results when shrinking
    if (2 * thumbnailWidth < clipX2 - clipX1 || 2 * thumbnailHeight < clipY2 - clipY1) {

        int kernelDimX = (clipX2 - clipX1) / (thumbnailWidth);
        int kernelDimY = (clipY2 - clipY1) / (thumbnailHeight);

        if (kernelDimX % 2 == 0)
            kernelDimX++;
        if (kernelDimY % 2 == 0)
            kernelDimY++;

        if (kernelDimX < kernelDimY)
            kernelDimX = kernelDimY;
        if (kernelDimY < kernelDimX)
            kernelDimY = kernelDimX;

        float[] blurKernel = new float[kernelDimX * kernelDimY];
        for (int i = 0; i < kernelDimX; i++)
            for (int j = 0; j < kernelDimY; j++)
                blurKernel[i * kernelDimX + j] = 1.0f / (float) (kernelDimX * kernelDimY);

        BufferedImageOp op = new ConvolveOp(new Kernel(kernelDimX, kernelDimY, blurKernel));
        imageCopy = op.filter(imageCopy, null);

    }

    // draw the thumbnail
    gr.drawImage(imageCopy, 0, 0, thumbnailWidth, thumbnailHeight, clipX1, clipY1, clipX2, clipY2, null);

    // and we are done
    gr.dispose();
    ImageIO.write(thumbnail, "png", thumbnailFile);

    // redirect to it
    response.sendRedirect(baseUrl + "/" + thumbnailFileName);

}

From source file:com.github.cherimojava.orchidae.controller._PictureController.java

@Test
public void getPicture() throws Exception {
    // verify no picture there
    mvc.perform(get(url("acd3131"))).andExpect(status().isNotFound());
    // upload one picture
    createPicture("test", "jpeg");
    // retrieve its id
    MvcResult result = getLatest(10).andReturn();
    List<Picture> pictures = factory.readList(Picture.class, result.getResponse().getContentAsString());
    assertEquals(pictures.size(), 1);/*w w w  . jav a 2 s  .co m*/
    ByteArrayInputStream bais = new ByteArrayInputStream(
            mvc.perform(get(url(pictures.get(0).getId())).param("f", "o")).andExpect(status().isOk())
                    .andReturn().getResponse().getContentAsByteArray());
    BufferedImage image = ImageIO.read(bais);
    assertEquals(42, image.getWidth());
    assertEquals(42, image.getHeight());
}

From source file:com.github.cherimojava.orchidae.controller._PictureController.java

@Test
public void getSmall() throws Exception {
    controller.maxHeight = 10;/*from  w w  w.j a  v a2s.c  o  m*/
    // verify no picture there
    mvc.perform(get(url("acd3131"))).andExpect(status().isNotFound());
    // upload one picture
    createPicture("test", "jpeg");
    // retrieve its id
    MvcResult result = getLatest(10).andReturn();
    List<Picture> pictures = factory.readList(Picture.class, result.getResponse().getContentAsString());
    assertEquals(pictures.size(), 1);
    ByteArrayInputStream bais = new ByteArrayInputStream(
            mvc.perform(get(url(pictures.get(0).getId())).param("f", "s")).andExpect(status().isOk())
                    .andReturn().getResponse().getContentAsByteArray());
    BufferedImage image = ImageIO.read(bais);
    assertEquals(10, image.getWidth());
    assertEquals(10, image.getHeight());
}

From source file:alfio.manager.FileUploadManager.java

private Map<String, String> getAttributes(UploadBase64FileModification file) {
    if (!StringUtils.startsWith(file.getType(), "image/")) {
        return Collections.emptyMap();
    }//from  w  w w  .java 2  s  .c o m

    try {
        BufferedImage image = ImageIO.read(new ByteArrayInputStream(file.getFile()));
        Map<String, String> attributes = new HashMap<>();
        attributes.put(FileBlobMetadata.ATTR_IMG_WIDTH, String.valueOf(image.getWidth()));
        attributes.put(FileBlobMetadata.ATTR_IMG_HEIGHT, String.valueOf(image.getHeight()));
        return attributes;
    } catch (IOException e) {
        log.error("error while processing image: ", e);
        return Collections.emptyMap();
    }
}

From source file:com.crimelab.service.GalleryServiceImpl.java

@Override
public XWPFDocument create(GalleryResults galleryResults, HttpSession session) {
    XWPFDocument document = null;// ww w  . jav a2 s.c o  m

    //Insert into database
    galleryDAO.insertResults(galleryResults);

    try {
        //Retrieving Template
        InputStream inpDocx = session.getServletContext()
                .getResourceAsStream("/WEB-INF/templates/CompositeSketch.docx");
        document = new XWPFDocument(inpDocx);

        //Adding the picture
        XWPFParagraph pictureHolder = document.createParagraph();
        XWPFRun pictureRun = pictureHolder.createRun();

        FileInputStream getPhoto = new FileInputStream(galleryResults.getPhotoLocation());
        FileInputStream getImage = new FileInputStream(galleryResults.getPhotoLocation());
        ImageInputStream imageInput = ImageIO.createImageInputStream(getPhoto);
        BufferedImage bi = ImageIO.read(imageInput);
        int width = bi.getWidth() - 100;
        int height = bi.getHeight() - 100;

        pictureRun.addBreak();
        pictureRun.addPicture(getImage, XWPFDocument.PICTURE_TYPE_PNG, null, Units.toEMU(width),
                Units.toEMU(height));

        pictureHolder.setBorderBottom(Borders.BASIC_BLACK_DASHES);
        pictureHolder.setBorderTop(Borders.BASIC_BLACK_DASHES);
        pictureHolder.setBorderLeft(Borders.BASIC_BLACK_DASHES);
        pictureHolder.setBorderRight(Borders.BASIC_BLACK_DASHES);
        pictureHolder.setAlignment(ParagraphAlignment.CENTER);
        //            pictureRowHolder.getCell(0).setText("IMAGE PLACER");

        //Case number and Date            
        XWPFParagraph info = document.createParagraph();
        XWPFRun caseNoAndDate = info.createRun();
        caseNoAndDate.setText("Case Number: " + galleryResults.getCaseNo());
        caseNoAndDate.addTab();
        caseNoAndDate.addTab();
        caseNoAndDate.addTab();
        caseNoAndDate.addTab();
        caseNoAndDate.setText(galleryResults.getDate());
        caseNoAndDate.setFontSize(16);

        //Sketch Details
        XWPFParagraph caseDetails = document.createParagraph();
        XWPFRun detailsParagraph = caseDetails.createRun();
        detailsParagraph.setText("Offense/Incident: " + galleryResults.getOffenseIncident());
        detailsParagraph.addBreak();
        detailsParagraph.setText("Name/AKA: " + galleryResults.getNameAKA());
        detailsParagraph.addBreak();
        detailsParagraph.setText("Sex: " + galleryResults.getSex());
        detailsParagraph.addTab();
        detailsParagraph.addTab();
        detailsParagraph.addTab();
        detailsParagraph.addTab();
        detailsParagraph.addTab();
        detailsParagraph.addTab();
        detailsParagraph.addTab();
        detailsParagraph.addTab();
        detailsParagraph.addTab();
        detailsParagraph.setText("Age: " + galleryResults.getAge());
        detailsParagraph.addBreak();
        detailsParagraph.setText("Height: " + galleryResults.getHeight());
        detailsParagraph.addTab();
        detailsParagraph.addTab();
        detailsParagraph.addTab();
        detailsParagraph.addTab();
        detailsParagraph.addTab();
        detailsParagraph.addTab();
        detailsParagraph.addTab();
        detailsParagraph.addTab();
        detailsParagraph.setText("Weight: " + galleryResults.getWeight());
        detailsParagraph.addBreak();
        detailsParagraph.setText("Built: " + galleryResults.getBuilt());
        detailsParagraph.addTab();
        detailsParagraph.addTab();
        detailsParagraph.addTab();
        detailsParagraph.addTab();
        detailsParagraph.addTab();
        detailsParagraph.addTab();
        detailsParagraph.addTab();
        detailsParagraph.addTab();
        detailsParagraph.addTab();
        detailsParagraph.setText("Complexion: " + galleryResults.getComplexion());
        detailsParagraph.addBreak();
        detailsParagraph.setText("Other Information: " + galleryResults.getOtherInfo());
        detailsParagraph.addBreak();
        detailsParagraph.setText("Described by: " + galleryResults.getDescribedBy());
        detailsParagraph.addBreak();
        detailsParagraph.setText("Requesting party: " + galleryResults.getRequestingParty());

        //Details Borders
        caseDetails.setBorderBottom(Borders.BASIC_BLACK_DASHES);
        caseDetails.setBorderTop(Borders.BASIC_BLACK_DASHES);
        caseDetails.setBorderLeft(Borders.BASIC_BLACK_DASHES);
        caseDetails.setBorderRight(Borders.BASIC_BLACK_DASHES);
        caseDetails.setAlignment(ParagraphAlignment.LEFT);

        //Reference Paragraph
        XWPFParagraph outsideDetails = document.createParagraph();
        XWPFRun outsideDetailsRun = outsideDetails.createRun();
        outsideDetailsRun.addBreak();
        outsideDetailsRun.setText("Note: For reference");
        outsideDetailsRun.addBreak();
        outsideDetailsRun.setText("The witness indicates that this image is: " + galleryResults.getRating());
        getPhoto.close();
        getImage.close();
        imageInput.close();
        document.getXWPFDocument();
    } catch (IOException | InvalidFormatException e) {
        e.printStackTrace();
    }
    return document;
}

From source file:de.uni_siegen.wineme.come_in.thumbnailer.thumbnailers.PDFBoxThumbnailer.java

@Override
public void generateThumbnail(final File input, final File output) throws IOException, ThumbnailerException {

    FileUtils.deleteQuietly(output);//from  w  w  w  .  j  av a2  s. c o m

    PDDocument document = null;
    try {
        try {
            document = PDDocument.load(input);
        } catch (final IOException e) {
            throw new ThumbnailerException("Could not load PDF File", e);
        }

        final List<?> pages = document.getDocumentCatalog().getAllPages();
        final PDPage page = (PDPage) pages.get(0);
        final BufferedImage tmpImage = this.writeImageForPage(document, page, BufferedImage.TYPE_INT_RGB);

        if (tmpImage.getWidth() == this.thumbWidth) {
            ImageIO.write(tmpImage, PDFBoxThumbnailer.OUTPUT_FORMAT, output);
        } else {
            final ResizeImage resizer = new ResizeImage(this.thumbWidth, this.thumbHeight);
            resizer.resizeMethod = ResizeImage.NO_RESIZE_ONLY_CROP;
            resizer.setInputImage(tmpImage);
            resizer.writeOutput(output);
        }
    }

    finally {
        if (document != null) {
            try {
                document.close();
            } catch (final IOException e) {
            }
        }
    }
}

From source file:ddf.catalog.transformer.input.pdf.PdfInputTransformer.java

private byte[] generatePdfThumbnail(PDDocument pdfDocument) throws IOException {

    PDFRenderer pdfRenderer = new PDFRenderer(pdfDocument);

    if (pdfDocument.getNumberOfPages() < 1) {
        /*//from www  .  j ava2 s  . c o  m
         * Can there be a PDF with zero pages??? Should we throw an error or what? The
         * original implementation assumed that a PDF would always have at least one
         * page. That's what I've implemented here, but I don't like make those
         * kinds of assumptions :-( But I also don't want to change the original
         * behavior without knowing how it will impact the system.
         */
    }

    PDPage page = pdfDocument.getPage(0);

    BufferedImage image = pdfRenderer.renderImageWithDPI(0, RESOLUTION_DPI, ImageType.RGB);

    int largestDimension = Math.max(image.getHeight(), image.getWidth());
    float scalingFactor = IMAGE_HEIGHTWIDTH / largestDimension;
    int scaledHeight = (int) (image.getHeight() * scalingFactor);
    int scaledWidth = (int) (image.getWidth() * scalingFactor);

    BufferedImage scaledImage = new BufferedImage(scaledWidth, scaledHeight, BufferedImage.TYPE_INT_RGB);
    Graphics2D graphics = scaledImage.createGraphics();
    graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    graphics.drawImage(image, 0, 0, scaledWidth, scaledHeight, null);
    graphics.dispose();

    try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
        ImageIOUtil.writeImage(scaledImage, FORMAT_NAME, outputStream, RESOLUTION_DPI, IMAGE_QUALITY);
        return outputStream.toByteArray();
    }
}

From source file:dk.dma.msiproxy.common.repo.ThumbnailService.java

/**
 * Creates a thumbnail for the image file using plain old java
 * @param file the image file// w ww.j av a  2s . c  o m
 * @param thumbFile the resulting thumbnail file
 * @param size the size of the thumbnail
 */
private void createThumbnailUsingJava(Path file, Path thumbFile, IconSize size) throws IOException {

    try {
        BufferedImage image = ImageIO.read(file.toFile());

        int w = image.getWidth();
        int h = image.getHeight();

        // Never scale up
        if (w <= size.getSize() && h <= size.getSize()) {
            FileUtils.copyFile(file.toFile(), thumbFile.toFile());

        } else {
            // Compute the scale factor
            double dx = (double) size.getSize() / (double) w;
            double dy = (double) size.getSize() / (double) h;
            double d = Math.min(dx, dy);

            // Create the thumbnail
            BufferedImage thumbImage = new BufferedImage((int) Math.round(w * d), (int) Math.round(h * d),
                    BufferedImage.TYPE_INT_RGB);
            Graphics2D g2d = thumbImage.createGraphics();
            AffineTransform at = AffineTransform.getScaleInstance(d, d);
            g2d.drawRenderedImage(image, at);
            g2d.dispose();

            // Save the thumbnail
            String fileName = thumbFile.getFileName().toString();
            ImageIO.write(thumbImage, FilenameUtils.getExtension(fileName), thumbFile.toFile());

            // Releas resources
            image.flush();
            thumbImage.flush();
        }

        // Update the timestamp of the thumbnail file to match the change date of the image file
        Files.setLastModifiedTime(thumbFile, Files.getLastModifiedTime(file));

    } catch (Exception e) {
        log.error("Error creating thumbnail for image " + file, e);
        throw new IOException(e);
    }
}

From source file:de.romankreisel.faktotum.beans.BundesbruderBean.java

/**
 * @param originalPicture/*from   w  w w.j av  a 2 s .c  om*/
 * @param pictureHeight
 * @param pictureWidth
 * @return
 * @throws IOException
 */
public Byte[] resizeProfilePicture(Byte[] originalPicture, int width, int height) throws IOException {
    BufferedImage originalImage = this.getImageFromByteArray(originalPicture);
    Dimension newDimension = this.getScaledDimension(
            new Dimension(originalImage.getWidth(), originalImage.getHeight()), new Dimension(width, height));
    Image scaledImage = originalImage.getScaledInstance(newDimension.width, newDimension.height,
            Image.SCALE_SMOOTH);
    return this.storeImageToByteArray(scaledImage);
}