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:haven.Utils.java

static Coord imgsz(BufferedImage img) {
    return (new Coord(img.getWidth(), img.getHeight()));
}

From source file:no.dusken.aranea.admin.control.ImageDimensionController.java

public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) {

    // ignore the request, this is plain work
    for (Image image : imageService.getImages()) {
        File file = imageUtils.getImageFile(image);
        image.setFileSize(file.length());
        BufferedImage rendImage;
        try {// w w  w .  j  ava  2s. c o  m
            rendImage = ImageIO.read(file);
        } catch (IOException e) {
            log.error("Could not read image {} {}", image, e);
            continue;
        }
        image.setHeight(rendImage.getHeight());
        image.setWidth(rendImage.getWidth());

        imageService.saveOrUpdate(image);
    }
    return new ModelAndView("redirect:/");
}

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

@RequestMapping(value = "api/teavote/election-info", method = RequestMethod.POST)
@ResponseBody// www .  ja  v  a 2  s.c  om
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:chiliad.parser.pdf.extractor.vectorgraphics.operator.BeginInlineImage.java

/**
 * process : BI : begin inline image./*w  ww .  j ava  2s  .  c  om*/
 *
 * @param operator The operator that is being executed.
 * @param arguments List
 * @throws IOException If there is an error displaying the inline image.
 */
@Override
public void process(PDFOperator operator, List<COSBase> arguments) throws IOException {
    VectorGraphicsExtractor extractor = (VectorGraphicsExtractor) context;
    PDPage page = extractor.getPage();
    //begin inline image object
    ImageParameters params = operator.getImageParameters();
    PDInlinedImage image = new PDInlinedImage();
    image.setImageParameters(params);
    image.setImageData(operator.getImageData());
    if (params.isStencil()) {
        //TODO implement inline image stencil masks 
        LOG.warn("Stencil masks are not implemented, background may be incorrect");
    }
    BufferedImage awtImage = image.createImage(context.getColorSpaces());

    if (awtImage == null) {
        LOG.warn("BeginInlineImage.process(): createImage returned NULL");
        return;
    }
    int imageWidth = awtImage.getWidth();
    int imageHeight = awtImage.getHeight();
    double pageHeight = extractor.getPageSize().getHeight();

    Matrix ctm = extractor.getGraphicsState().getCurrentTransformationMatrix();
    int pageRotation = page.findRotation();

    AffineTransform ctmAT = ctm.createAffineTransform();
    ctmAT.scale(1f / imageWidth, 1f / imageHeight);
    Matrix rotationMatrix = new Matrix();
    rotationMatrix.setFromAffineTransform(ctmAT);
    // calculate the inverse rotation angle
    // scaleX = m00 = cos
    // shearX = m01 = -sin
    // tan = sin/cos
    double angle = Math.atan(ctmAT.getShearX() / ctmAT.getScaleX());
    Matrix translationMatrix = null;
    if (pageRotation == 0 || pageRotation == 180) {
        translationMatrix = Matrix.getTranslatingInstance((float) (Math.sin(angle) * ctm.getXScale()),
                (float) (pageHeight - 2 * ctm.getYPosition() - Math.cos(angle) * ctm.getYScale()));
    } else if (pageRotation == 90 || pageRotation == 270) {
        translationMatrix = Matrix.getTranslatingInstance((float) (Math.sin(angle) * ctm.getYScale()),
                (float) (pageHeight - 2 * ctm.getYPosition()));
    }
    rotationMatrix = rotationMatrix.multiply(translationMatrix);
    rotationMatrix.setValue(0, 1, (-1) * rotationMatrix.getValue(0, 1));
    rotationMatrix.setValue(1, 0, (-1) * rotationMatrix.getValue(1, 0));
    AffineTransform at = new AffineTransform(rotationMatrix.getValue(0, 0), rotationMatrix.getValue(0, 1),
            rotationMatrix.getValue(1, 0), rotationMatrix.getValue(1, 1), rotationMatrix.getValue(2, 0),
            rotationMatrix.getValue(2, 1));
    extractor.drawImage(awtImage, at);
}

From source file:com.tdclighthouse.prototype.services.callbacks.ImageCreationCallBack.java

private ImageSize getScaledSize(Long height, Long width, BufferedImage image) {
    Long adjustedWidth = width == 0 ? MAX_SUPPORTED_PIXELS : width;
    Long adjustedHeight = height == 0 ? MAX_SUPPORTED_PIXELS : height;
    double widthScalingFactor = ((double) adjustedWidth) / image.getWidth();
    double heightScalingFactor = ((double) adjustedHeight) / image.getHeight();
    double scalingFacotr = Math.min(widthScalingFactor, heightScalingFactor);
    if (scalingFacotr > 0) {
        adjustedWidth = (long) Math.round(Math.max(scalingFacotr * image.getWidth(), 1));
        adjustedHeight = (long) Math.round(Math.max(scalingFacotr * image.getHeight(), 1));
    }//from  ww  w . j av a2 s. c om
    return new ImageSize(adjustedHeight, adjustedWidth);
}

From source file:com.tocsi.images.ReceivedImageController.java

public void handleFileUpload(FileUploadEvent event) {
    if (event.getFile() != null) {
        try {//w  w  w  .ja v  a  2s  . c om
            UploadedFile uf = (UploadedFile) event.getFile();
            File folder = new File(GlobalsBean.destOriginal);
            //File folderThumb = new File(destThumbnail);
            String filename = FilenameUtils.getBaseName(uf.getFileName());
            String extension = FilenameUtils.getExtension(uf.getFileName());
            File file = File.createTempFile(filename + "-", "." + extension, folder);
            //File fileThumb = File.createTempFile(filename + "-", "." + extension, folderThumb);

            //resize image here
            BufferedImage originalImage = ImageIO.read(uf.getInputstream());
            InputStream is = uf.getInputstream();
            if (originalImage.getWidth() > 700) { //resize image if image's width excess 700px
                BufferedImage origImage = Scalr.resize(originalImage, Scalr.Method.QUALITY,
                        Scalr.Mode.FIT_TO_WIDTH, 640,
                        (int) ((originalImage.getHeight() / ((double) (originalImage.getWidth() / 700.0)))),
                        Scalr.OP_ANTIALIAS);
                ByteArrayOutputStream os = new ByteArrayOutputStream();
                ImageIO.write(origImage, extension, os);
                is = new ByteArrayInputStream(os.toByteArray());
            }

            //create thumbnail
            BufferedImage thumbnail = Scalr.resize(ImageIO.read(uf.getInputstream()), 150);
            ByteArrayOutputStream osThumb = new ByteArrayOutputStream();
            ImageIO.write(thumbnail, extension, osThumb);
            InputStream isThumbnail = new ByteArrayInputStream(osThumb.toByteArray());

            try (InputStream input = is) {
                Files.copy(input, file.toPath(), StandardCopyOption.REPLACE_EXISTING);
            }

            try (InputStream input = isThumbnail) {
                Files.copy(input, Paths.get(GlobalsBean.destThumbnail + GlobalsBean.separator + file.getName()),
                        StandardCopyOption.REPLACE_EXISTING);
            }

            //File chartFile = new File(file.getAbsolutePath());
            //chart = new DefaultStreamedContent(new FileInputStream(chartFile), "image/jpg");
            ImageBean ib = new ImageBean();
            ib.setFilename(file.getName());
            ib.setThumbFile(file.getName());
            ib.setImageFileLocation(GlobalsBean.destOriginal + GlobalsBean.separator + file.getName());
            imageList.add(ib);

        } catch (IOException | IllegalArgumentException | ImagingOpException ex) {
            Utilities.displayError(ex.getMessage());
        }
    }
}

From source file:org.kawakicchi.bookshelf.interfaces.book.BookController.java

@RequestMapping(value = { "/store" }, method = RequestMethod.POST)
public String store(@ModelAttribute StoreForm form, final Model model) {
    setting(model);/*from ww w .  ja v a2  s. c o  m*/

    if (BookshelfUtil.isBlank(form.getTitle()) || form.getFile().isEmpty()) {
        model.addAttribute("form", form);

        final List<SeriesEntity> seriesList = viewerService.getSeriesList();
        model.addAttribute("seriesList", seriesList);

        return "/book/store";
    }

    File tmpDir = new File("tmp");
    tmpDir.mkdirs();

    List<ContentEntity> files = new ArrayList<ContentEntity>();

    byte[] buf = new byte[1024];
    try (ZipInputStream zipStream = new ZipInputStream(form.getFile().getInputStream(),
            Charset.forName("MS932"))) {
        for (ZipEntry entry = zipStream.getNextEntry(); entry != null; entry = zipStream.getNextEntry()) {
            if (entry.isDirectory())
                continue;

            String id = BookshelfUtil.generateUUID();
            File tmpFile = Paths.get(tmpDir.getAbsolutePath(), id).toFile();
            OutputStream oStream = new FileOutputStream(tmpFile);

            int size = -1;
            while (0 <= (size = zipStream.read(buf, 0, 1024))) {
                oStream.write(buf, 0, size);
            }

            oStream.close();

            Metadata metadata = ImageMetadataReader.readMetadata(tmpFile);
            for (Directory directory : metadata.getDirectories()) {
                for (Tag tag : directory.getTags()) {
                    System.out.format("[%s] - %s = %s", directory.getName(), tag.getTagName(),
                            tag.getDescription());
                }
                if (directory.hasErrors()) {
                    for (String error : directory.getErrors()) {
                        System.err.format("ERROR: %s", error);
                    }
                }
            }

            BufferedImage img = ImageIO.read(tmpFile);
            System.out.println(String.format("%d / %d", img.getWidth(), img.getHeight()));

            String[] ss = entry.getName().split("/");
            files.add(new ContentEntity(ss[ss.length - 1], tmpFile, img.getWidth(), img.getHeight()));
        }
    } catch (ImageProcessingException ex) {

    } catch (IOException ex) {

    }

    bookshelfService.createBook(form.getTitle(), form.getSeries(), files);

    return "/book/store";
}

From source file:dcstore.web.ImagesWeb.java

private void resizeImage(String inPath, int w, int h, String outPath) {
    try {/*www. j a v a 2 s  .  c o m*/
        BufferedImage originalImage = ImageIO.read(new File(inPath));
        int ow, oh;
        ow = originalImage.getWidth();
        oh = originalImage.getHeight();
        double ratio = (double) ow / (double) oh;
        int type = originalImage.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : originalImage.getType();
        int ch = (int) Math.round(w / ratio);

        BufferedImage resizedImage = new BufferedImage(w, h, 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.setColor(Color.white);
        g.fillRect(0, 0, w, h);
        g.drawImage(originalImage, 0, (int) (((float) h - (float) ch) / 2), w, ch, null);
        g.dispose();
        ImageIO.write(resizedImage, "jpg", new File(outPath));
    } catch (Exception e) {
        FacesContext.getCurrentInstance().addMessage("",
                new FacesMessage("Error while resizeing image: " + e.getMessage()));
    }
}

From source file:com.skcraft.launcher.swing.InstanceTableModel.java

private ImageIcon buildDownloadIcon(BufferedImage instanceIcon) {
    try {// ww  w.  j  a v a  2s .  c om
        BufferedImage iconBg = instanceIcon;
        BufferedImage iconFg = ImageIO.read(Launcher.class.getResource("download_icon_overlay.png"));
        BufferedImage iconCombined = new BufferedImage(iconBg.getWidth(), iconBg.getHeight(),
                BufferedImage.TYPE_INT_ARGB);
        Graphics2D canvas = iconCombined.createGraphics();
        canvas.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f));
        canvas.drawImage(iconBg, 0, 0, null);
        canvas.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f));
        canvas.drawImage(iconFg, iconBg.getWidth() - iconFg.getWidth(), iconBg.getHeight() - iconFg.getHeight(),
                null);
        canvas.dispose();
        return new ImageIcon(iconCombined);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:br.com.pfood.mb.imp.ProdutoMB.java

public void handleFileUpload(FileUploadEvent event) throws IOException {
    if (listaImagensProduto.size() <= 5) {
        String dir = AppUtil.getDirFilesVendor() + usuarioLogado.getUsuario().getVendedor().getIdVendedor()
                + "/";
        String fileName = event.getFile().getFileName();

        InputStream is = event.getFile().getInputstream();
        String extencao = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
        extencao = extencao.replace("jpeg", "jpg");
        if (!extencao.equalsIgnoreCase("jpg")) {
            messageUtil.addMenssageWarn("Imagens devem ser do tipo JPG");
            return;
        }//from w  ww .j a  v a  2s.com
        fileName = DigestUtils.md5Hex(fileName) + "." + extencao;

        try {
            FileOutputStream out = new FileOutputStream(dir + "or/" + fileName);
            int read = 0;
            byte[] bytes = new byte[1024];

            while ((read = is.read(bytes)) != -1) {
                out.write(bytes, 0, read);
            }

            out.close();
            out = null;
        } catch (Exception ex) {
            Logger.getLogger(ProdutoMB.class.getName()).log(Level.SEVERE, null, ex);
        }
        is.close();
        is = null;
        BufferedImage imagem = ImageIO.read(ImageIO.createImageInputStream(new File(dir + "or/" + fileName)));

        if (imagem.getWidth() >= 128 || imagem.getHeight() >= 128) {
            ImagemUtil.redimenImagem(dir + "sm/" + fileName, dir + "or/" + fileName, 128, 128, extencao);
        } else {
            ImagemUtil.redimenImagem(dir + "sm/" + fileName, dir + "or/" + fileName, imagem.getWidth(null),
                    imagem.getHeight(null), extencao);
        }

        if (imagem.getWidth() >= 640 || imagem.getHeight() >= 640) {
            ImagemUtil.redimenImagem(dir + "md/" + fileName, dir + "or/" + fileName, 640, 640, extencao);
        } else {
            ImagemUtil.redimenImagem(dir + "md/" + fileName, dir + "or/" + fileName, imagem.getWidth(null),
                    imagem.getHeight(null), extencao);
        }

        Imagem i = new Imagem();
        i.setCodigo(Imagecode.IMG_PRODUTO.getImgCode());
        i.setDescricao(event.getFile().getFileName());
        i.setHash(DigestUtils.md5Hex(event.getFile().getFileName()));
        i.setNomeArquivo(fileName);
        try {
            produtoBO.save(i);
            ImagemProduto imgProd = new ImagemProduto();
            imgProd.setProduto(obj);
            imgProd.setImagem(i);
            imgProd.setSequencia(listaImagensProduto.size() + 1);
            produtoBO.save(imgProd);
            listaImagensProduto.add(imgProd);
        } catch (Exception ex) {
            ex.printStackTrace();
            Logger.getLogger(ProdutoMB.class.getName()).log(Level.SEVERE, null, ex);
        }
    } else {
        messageUtil.addMenssageWarn("Maximo de 6 imagens por produto");
    }

}