Using POI version 3.2
Issue: Not able to resize an image to its original height and width. I am able to add an image to the excel file.
After adding image I
I found that you must NOT call picture.resize()
until after sheet.autoSizeColumn(i)
even if you are not calling autoSizeColumn(i)
on the column to which the picture is anchored.
On a HSSFWorkbook with a custom font I did the following to get a logo to be displayed in the right dimensions:
CreationHelper helper = wb.getCreationHelper();
Drawing drawing = sheet.createDrawingPatriarch();
ClientAnchor anchor = helper.createClientAnchor();
anchor.setDx1(LOGO_MARGIN * XSSFShape.EMU_PER_PIXEL);
anchor.setDx2(LOGO_WIDTH_IN_FUNNY_POI_FORMAT * XSSFShape.EMU_PER_PIXEL);
anchor.setDy1(LOGO_MARGIN * XSSFShape.EMU_PER_PIXEL);
anchor.setDy2(LOGO_HEIGHT_IN_FUNNY_POI_FORMAT * XSSFShape.EMU_PER_PIXEL);
drawing.createPicture(anchor, pictureIndex);
Where I set LOGO_HEIGHT... and LOGO_WIDTH.. to the wanted pixel size of the image.
The resulting image was not at its original ratio and not the expected pixel size. So I used the expected size / current size ratio and adjusted LOGO_WIDTH.. and LOGO_HEIGHT.. accordingly. Not beautiful, but it works :/
And don't call Picture.resize()
afterwards.
See Apache POIU Bug 52504 or this newsgroup discussion about poi Picture.resize() and POI quick guide for inserting pictures.
Update: current code looks like this, the original image is 2000x450:
LOGO_MARGIN = 2;
int index = getLogoPictureIndex();
CreationHelper helper = this.wb.getCreationHelper();
Drawing drawing = this.sheet.createDrawingPatriarch();
ClientAnchor anchor = helper.createClientAnchor();
anchor.setDx1(LOGO_MARGIN * XSSFShape.EMU_PER_PIXEL);
anchor.setDy1(LOGO_MARGIN * XSSFShape.EMU_PER_PIXEL);
Picture pic = drawing.createPicture(anchor, index);
pic.resize(0.064);
Good solution is to use resize() function with scale argument:
double scale = 0.3;
Picture pict = drawing.createPicture(anchor, pictureIdx);
pict.resize(scale);
Shouldn't you just hold onto the picture object and call resize() very last, after your setcolumnwidth()s are done?