List of usage examples for org.apache.poi.ss.usermodel Picture getImageDimension
Dimension getImageDimension();
From source file:nc.noumea.mairie.appock.util.StockSpreadsheetExporter.java
License:Open Source License
private static void addImage(XSSFWorkbook workbook, XSSFSheet worksheet, File file, int rowNum) throws IOException { //add picture data to this workbook. InputStream is = new FileInputStream(file); byte[] bytes = IOUtils.toByteArray(is); int pictureIdx = workbook.addPicture(bytes, Workbook.PICTURE_TYPE_PNG); is.close();//from w ww.j av a 2s . c o m XSSFDrawing drawing = worksheet.createDrawingPatriarch(); //add a picture shape XSSFClientAnchor anchor = workbook.getCreationHelper().createClientAnchor(); anchor.setAnchorType(ClientAnchor.AnchorType.MOVE_DONT_RESIZE); //set top-left corner of the picture, //subsequent call of Picture#resize() will operate relative to it anchor.setCol1(0); anchor.setRow1(rowNum); Picture pict = drawing.createPicture(anchor, pictureIdx); //auto-size picture relative to its top-left corner pict.resize(); //get the picture width int pictWidthPx = pict.getImageDimension().width; int pictHeightPt = pict.getImageDimension().height; //get the cell width float cellWidthPx = worksheet.getColumnWidthInPixels(0); float cellHeightPx = ConvertImageUnits.heightUnits2Pixel(worksheet.getRow(rowNum).getHeight()); //calculate the center position int centerPosPx = Math.round(cellWidthPx / 2f - (float) pictWidthPx / 2f); int centerPosPy = Math.round(cellHeightPx / 2f - (float) pictHeightPt / 2f + 10); //set the new upper left anchor position anchor.setCol1(0); //set the remaining pixels up to the center position as Dx in unit EMU anchor.setDx1(centerPosPx * Units.EMU_PER_PIXEL); anchor.setDy1(centerPosPy * Units.EMU_PER_PIXEL); //resize the pictutre to original size again //this will determine the new bottom rigth anchor position pict.resize(); }